babylon.max.js 3.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384
  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 () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array or Float32Array.
  828. * Returns the Vector2.
  829. */
  830. Vector2.FromArrayToRef = function (array, offset, result) {
  831. result.x = array[offset];
  832. result.y = array[offset + 1];
  833. };
  834. /**
  835. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  836. */
  837. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  838. var squared = amount * amount;
  839. var cubed = amount * squared;
  840. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  841. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  842. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  843. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  844. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  845. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * 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".
  850. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  851. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  852. */
  853. Vector2.Clamp = function (value, min, max) {
  854. var x = value.x;
  855. x = (x > max.x) ? max.x : x;
  856. x = (x < min.x) ? min.x : x;
  857. var y = value.y;
  858. y = (y > max.y) ? max.y : y;
  859. y = (y < min.y) ? min.y : y;
  860. return new Vector2(x, y);
  861. };
  862. /**
  863. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  864. */
  865. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  866. var squared = amount * amount;
  867. var cubed = amount * squared;
  868. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  869. var part2 = (-2.0 * cubed) + (3.0 * squared);
  870. var part3 = (cubed - (2.0 * squared)) + amount;
  871. var part4 = cubed - squared;
  872. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  873. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  874. return new Vector2(x, y);
  875. };
  876. /**
  877. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  878. */
  879. Vector2.Lerp = function (start, end, amount) {
  880. var x = start.x + ((end.x - start.x) * amount);
  881. var y = start.y + ((end.y - start.y) * amount);
  882. return new Vector2(x, y);
  883. };
  884. /**
  885. * Returns the dot product (float) of the vector "left" and the vector "right".
  886. */
  887. Vector2.Dot = function (left, right) {
  888. return left.x * right.x + left.y * right.y;
  889. };
  890. /**
  891. * Returns a new Vector2 equal to the normalized passed vector.
  892. */
  893. Vector2.Normalize = function (vector) {
  894. var newVector = vector.clone();
  895. newVector.normalize();
  896. return newVector;
  897. };
  898. /**
  899. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  900. */
  901. Vector2.Minimize = function (left, right) {
  902. var x = (left.x < right.x) ? left.x : right.x;
  903. var y = (left.y < right.y) ? left.y : right.y;
  904. return new Vector2(x, y);
  905. };
  906. /**
  907. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  908. */
  909. Vector2.Maximize = function (left, right) {
  910. var x = (left.x > right.x) ? left.x : right.x;
  911. var y = (left.y > right.y) ? left.y : right.y;
  912. return new Vector2(x, y);
  913. };
  914. /**
  915. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  916. */
  917. Vector2.Transform = function (vector, transformation) {
  918. var r = Vector2.Zero();
  919. Vector2.TransformToRef(vector, transformation, r);
  920. return r;
  921. };
  922. /**
  923. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  924. */
  925. Vector2.TransformToRef = function (vector, transformation, result) {
  926. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  927. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  928. result.x = x;
  929. result.y = y;
  930. };
  931. /**
  932. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  933. */
  934. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  935. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  936. var sign = a < 0 ? -1 : 1;
  937. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  938. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  939. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  940. };
  941. /**
  942. * Returns the distance (float) between the vectors "value1" and "value2".
  943. */
  944. Vector2.Distance = function (value1, value2) {
  945. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  946. };
  947. /**
  948. * Returns the squared distance (float) between the vectors "value1" and "value2".
  949. */
  950. Vector2.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. return (x * x) + (y * y);
  954. };
  955. /**
  956. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  957. */
  958. Vector2.Center = function (value1, value2) {
  959. var center = value1.add(value2);
  960. center.scaleInPlace(0.5);
  961. return center;
  962. };
  963. /**
  964. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  965. */
  966. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  967. var l2 = Vector2.DistanceSquared(segA, segB);
  968. if (l2 === 0.0) {
  969. return Vector2.Distance(p, segA);
  970. }
  971. var v = segB.subtract(segA);
  972. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  973. var proj = segA.add(v.multiplyByFloats(t, t));
  974. return Vector2.Distance(p, proj);
  975. };
  976. return Vector2;
  977. }());
  978. BABYLON.Vector2 = Vector2;
  979. var Vector3 = (function () {
  980. /**
  981. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  982. * A Vector3 is the main object used in 3D geometry.
  983. * It can represent etiher the coordinates of a point the space, either a direction.
  984. */
  985. function Vector3(x, y, z) {
  986. this.x = x;
  987. this.y = y;
  988. this.z = z;
  989. }
  990. /**
  991. * Returns a string with the Vector3 coordinates.
  992. */
  993. Vector3.prototype.toString = function () {
  994. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  995. };
  996. /**
  997. * Returns the string "Vector3"
  998. */
  999. Vector3.prototype.getClassName = function () {
  1000. return "Vector3";
  1001. };
  1002. /**
  1003. * Returns the Vector hash code.
  1004. */
  1005. Vector3.prototype.getHashCode = function () {
  1006. var hash = this.x || 0;
  1007. hash = (hash * 397) ^ (this.y || 0);
  1008. hash = (hash * 397) ^ (this.z || 0);
  1009. return hash;
  1010. };
  1011. // Operators
  1012. /**
  1013. * Returns a new array with three elements : the coordinates the Vector3.
  1014. */
  1015. Vector3.prototype.asArray = function () {
  1016. var result = [];
  1017. this.toArray(result, 0);
  1018. return result;
  1019. };
  1020. /**
  1021. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1022. * Returns the Vector3.
  1023. */
  1024. Vector3.prototype.toArray = function (array, index) {
  1025. if (index === void 0) { index = 0; }
  1026. array[index] = this.x;
  1027. array[index + 1] = this.y;
  1028. array[index + 2] = this.z;
  1029. return this;
  1030. };
  1031. /**
  1032. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1033. */
  1034. Vector3.prototype.toQuaternion = function () {
  1035. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1036. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1037. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1038. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1039. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1040. var cosy = Math.cos(this.y * 0.5);
  1041. var siny = Math.sin(this.y * 0.5);
  1042. result.x = coszMinusx * siny;
  1043. result.y = -sinzMinusx * siny;
  1044. result.z = sinxPlusz * cosy;
  1045. result.w = cosxPlusz * cosy;
  1046. return result;
  1047. };
  1048. /**
  1049. * Adds the passed vector to the current Vector3.
  1050. * Returns the updated Vector3.
  1051. */
  1052. Vector3.prototype.addInPlace = function (otherVector) {
  1053. this.x += otherVector.x;
  1054. this.y += otherVector.y;
  1055. this.z += otherVector.z;
  1056. return this;
  1057. };
  1058. /**
  1059. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1060. */
  1061. Vector3.prototype.add = function (otherVector) {
  1062. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1063. };
  1064. /**
  1065. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1066. * Returns the current Vector3.
  1067. */
  1068. Vector3.prototype.addToRef = function (otherVector, result) {
  1069. result.x = this.x + otherVector.x;
  1070. result.y = this.y + otherVector.y;
  1071. result.z = this.z + otherVector.z;
  1072. return this;
  1073. };
  1074. /**
  1075. * Subtract the passed vector from the current Vector3.
  1076. * Returns the updated Vector3.
  1077. */
  1078. Vector3.prototype.subtractInPlace = function (otherVector) {
  1079. this.x -= otherVector.x;
  1080. this.y -= otherVector.y;
  1081. this.z -= otherVector.z;
  1082. return this;
  1083. };
  1084. /**
  1085. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1086. */
  1087. Vector3.prototype.subtract = function (otherVector) {
  1088. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1089. };
  1090. /**
  1091. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1092. * Returns the current Vector3.
  1093. */
  1094. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1095. result.x = this.x - otherVector.x;
  1096. result.y = this.y - otherVector.y;
  1097. result.z = this.z - otherVector.z;
  1098. return this;
  1099. };
  1100. /**
  1101. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1102. */
  1103. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1104. return new Vector3(this.x - x, this.y - y, this.z - z);
  1105. };
  1106. /**
  1107. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1108. * Returns the current Vector3.
  1109. */
  1110. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1111. result.x = this.x - x;
  1112. result.y = this.y - y;
  1113. result.z = this.z - z;
  1114. return this;
  1115. };
  1116. /**
  1117. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1118. */
  1119. Vector3.prototype.negate = function () {
  1120. return new Vector3(-this.x, -this.y, -this.z);
  1121. };
  1122. /**
  1123. * Multiplies the Vector3 coordinates by the float "scale".
  1124. * Returns the updated Vector3.
  1125. */
  1126. Vector3.prototype.scaleInPlace = function (scale) {
  1127. this.x *= scale;
  1128. this.y *= scale;
  1129. this.z *= scale;
  1130. return this;
  1131. };
  1132. /**
  1133. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1134. */
  1135. Vector3.prototype.scale = function (scale) {
  1136. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1137. };
  1138. /**
  1139. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1140. * Returns the current Vector3.
  1141. */
  1142. Vector3.prototype.scaleToRef = function (scale, result) {
  1143. result.x = this.x * scale;
  1144. result.y = this.y * scale;
  1145. result.z = this.z * scale;
  1146. return this;
  1147. };
  1148. /**
  1149. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1150. */
  1151. Vector3.prototype.equals = function (otherVector) {
  1152. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1153. };
  1154. /**
  1155. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1156. */
  1157. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1160. };
  1161. /**
  1162. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1163. */
  1164. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1165. return this.x === x && this.y === y && this.z === z;
  1166. };
  1167. /**
  1168. * Muliplies the current Vector3 coordinates by the passed ones.
  1169. * Returns the updated Vector3.
  1170. */
  1171. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1172. this.x *= otherVector.x;
  1173. this.y *= otherVector.y;
  1174. this.z *= otherVector.z;
  1175. return this;
  1176. };
  1177. /**
  1178. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1179. */
  1180. Vector3.prototype.multiply = function (otherVector) {
  1181. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1182. };
  1183. /**
  1184. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1185. * Returns the current Vector3.
  1186. */
  1187. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1188. result.x = this.x * otherVector.x;
  1189. result.y = this.y * otherVector.y;
  1190. result.z = this.z * otherVector.z;
  1191. return this;
  1192. };
  1193. /**
  1194. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1195. */
  1196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1197. return new Vector3(this.x * x, this.y * y, this.z * z);
  1198. };
  1199. /**
  1200. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1201. */
  1202. Vector3.prototype.divide = function (otherVector) {
  1203. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1204. };
  1205. /**
  1206. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1207. * Returns the current Vector3.
  1208. */
  1209. Vector3.prototype.divideToRef = function (otherVector, result) {
  1210. result.x = this.x / otherVector.x;
  1211. result.y = this.y / otherVector.y;
  1212. result.z = this.z / otherVector.z;
  1213. return this;
  1214. };
  1215. /**
  1216. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1217. * Returns the updated Vector3.
  1218. */
  1219. Vector3.prototype.MinimizeInPlace = function (other) {
  1220. if (other.x < this.x)
  1221. this.x = other.x;
  1222. if (other.y < this.y)
  1223. this.y = other.y;
  1224. if (other.z < this.z)
  1225. this.z = other.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1230. * Returns the updated Vector3.
  1231. */
  1232. Vector3.prototype.MaximizeInPlace = function (other) {
  1233. if (other.x > this.x)
  1234. this.x = other.x;
  1235. if (other.y > this.y)
  1236. this.y = other.y;
  1237. if (other.z > this.z)
  1238. this.z = other.z;
  1239. return this;
  1240. };
  1241. // Properties
  1242. /**
  1243. * Returns the length of the Vector3 (float).
  1244. */
  1245. Vector3.prototype.length = function () {
  1246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1247. };
  1248. /**
  1249. * Returns the squared length of the Vector3 (float).
  1250. */
  1251. Vector3.prototype.lengthSquared = function () {
  1252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1253. };
  1254. // Methods
  1255. /**
  1256. * Normalize the current Vector3.
  1257. * Returns the updated Vector3.
  1258. */
  1259. Vector3.prototype.normalize = function () {
  1260. var len = this.length();
  1261. if (len === 0 || len === 1.0)
  1262. return this;
  1263. var num = 1.0 / len;
  1264. this.x *= num;
  1265. this.y *= num;
  1266. this.z *= num;
  1267. return this;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 copied from the current Vector3.
  1271. */
  1272. Vector3.prototype.clone = function () {
  1273. return new Vector3(this.x, this.y, this.z);
  1274. };
  1275. /**
  1276. * Copies the passed vector coordinates to the current Vector3 ones.
  1277. * Returns the updated Vector3.
  1278. */
  1279. Vector3.prototype.copyFrom = function (source) {
  1280. this.x = source.x;
  1281. this.y = source.y;
  1282. this.z = source.z;
  1283. return this;
  1284. };
  1285. /**
  1286. * Copies the passed floats to the current Vector3 coordinates.
  1287. * Returns the updated Vector3.
  1288. */
  1289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1290. this.x = x;
  1291. this.y = y;
  1292. this.z = z;
  1293. return this;
  1294. };
  1295. /**
  1296. * Copies the passed floats to the current Vector3 coordinates.
  1297. * Returns the updated Vector3.
  1298. */
  1299. Vector3.prototype.set = function (x, y, z) {
  1300. return this.copyFromFloats(x, y, z);
  1301. };
  1302. // Statics
  1303. /**
  1304. *
  1305. */
  1306. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1307. var d0 = Vector3.Dot(vector0, axis) - size;
  1308. var d1 = Vector3.Dot(vector1, axis) - size;
  1309. var s = d0 / (d0 - d1);
  1310. return s;
  1311. };
  1312. /**
  1313. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1314. */
  1315. Vector3.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1329. };
  1330. /**
  1331. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1332. */
  1333. Vector3.FromArrayToRef = function (array, offset, result) {
  1334. result.x = array[offset];
  1335. result.y = array[offset + 1];
  1336. result.z = array[offset + 2];
  1337. };
  1338. /**
  1339. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1340. */
  1341. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1342. result.x = array[offset];
  1343. result.y = array[offset + 1];
  1344. result.z = array[offset + 2];
  1345. };
  1346. /**
  1347. * Sets the passed vector "result" with the passed floats.
  1348. */
  1349. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1350. result.x = x;
  1351. result.y = y;
  1352. result.z = z;
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1356. */
  1357. Vector3.Zero = function () {
  1358. return new Vector3(0.0, 0.0, 0.0);
  1359. };
  1360. /**
  1361. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1362. */
  1363. Vector3.Up = function () {
  1364. return new Vector3(0.0, 1.0, 0.0);
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1368. */
  1369. Vector3.Forward = function () {
  1370. return new Vector3(0.0, 0.0, 1.0);
  1371. };
  1372. /**
  1373. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1374. */
  1375. Vector3.Right = function () {
  1376. return new Vector3(1.0, 0.0, 0.0);
  1377. };
  1378. /**
  1379. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1380. */
  1381. Vector3.Left = function () {
  1382. return new Vector3(-1.0, 0.0, 0.0);
  1383. };
  1384. /**
  1385. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1386. * This method computes tranformed coordinates only, not transformed direction vectors.
  1387. */
  1388. Vector3.TransformCoordinates = function (vector, transformation) {
  1389. var result = Vector3.Zero();
  1390. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1391. return result;
  1392. };
  1393. /**
  1394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1395. * This method computes tranformed coordinates only, not transformed direction vectors.
  1396. */
  1397. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1398. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1399. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1400. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1401. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1402. result.x = x / w;
  1403. result.y = y / w;
  1404. result.z = z / w;
  1405. };
  1406. /**
  1407. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1408. * This method computes tranformed coordinates only, not transformed direction vectors.
  1409. */
  1410. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1411. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1412. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1413. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1414. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1415. result.x = rx / rw;
  1416. result.y = ry / rw;
  1417. result.z = rz / rw;
  1418. };
  1419. /**
  1420. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1421. * This methods computes transformed normalized direction vectors only.
  1422. */
  1423. Vector3.TransformNormal = function (vector, transformation) {
  1424. var result = Vector3.Zero();
  1425. Vector3.TransformNormalToRef(vector, transformation, result);
  1426. return result;
  1427. };
  1428. /**
  1429. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1430. * This methods computes transformed normalized direction vectors only.
  1431. */
  1432. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1433. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1434. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1435. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1442. * This methods computes transformed normalized direction vectors only.
  1443. */
  1444. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1445. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1446. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1447. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1448. };
  1449. /**
  1450. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1451. */
  1452. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1453. var squared = amount * amount;
  1454. var cubed = amount * squared;
  1455. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1456. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1457. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1458. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1459. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1460. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1461. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1462. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1463. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1464. return new Vector3(x, y, z);
  1465. };
  1466. /**
  1467. * 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".
  1468. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1469. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1470. */
  1471. Vector3.Clamp = function (value, min, max) {
  1472. var x = value.x;
  1473. x = (x > max.x) ? max.x : x;
  1474. x = (x < min.x) ? min.x : x;
  1475. var y = value.y;
  1476. y = (y > max.y) ? max.y : y;
  1477. y = (y < min.y) ? min.y : y;
  1478. var z = value.z;
  1479. z = (z > max.z) ? max.z : z;
  1480. z = (z < min.z) ? min.z : z;
  1481. return new Vector3(x, y, z);
  1482. };
  1483. /**
  1484. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1485. */
  1486. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1487. var squared = amount * amount;
  1488. var cubed = amount * squared;
  1489. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1490. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1491. var part3 = (cubed - (2.0 * squared)) + amount;
  1492. var part4 = cubed - squared;
  1493. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1494. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1495. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1500. */
  1501. Vector3.Lerp = function (start, end, amount) {
  1502. var result = new Vector3(0, 0, 0);
  1503. Vector3.LerpToRef(start, end, amount, result);
  1504. return result;
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1508. */
  1509. Vector3.LerpToRef = function (start, end, amount, result) {
  1510. result.x = start.x + ((end.x - start.x) * amount);
  1511. result.y = start.y + ((end.y - start.y) * amount);
  1512. result.z = start.z + ((end.z - start.z) * amount);
  1513. };
  1514. /**
  1515. * Returns the dot product (float) between the vectors "left" and "right".
  1516. */
  1517. Vector3.Dot = function (left, right) {
  1518. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1519. };
  1520. /**
  1521. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1522. * The cross product is then orthogonal to both "left" and "right".
  1523. */
  1524. Vector3.Cross = function (left, right) {
  1525. var result = Vector3.Zero();
  1526. Vector3.CrossToRef(left, right, result);
  1527. return result;
  1528. };
  1529. /**
  1530. * Sets the passed vector "result" with the cross product of "left" and "right".
  1531. * The cross product is then orthogonal to both "left" and "right".
  1532. */
  1533. Vector3.CrossToRef = function (left, right, result) {
  1534. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1535. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1536. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1537. result.copyFrom(MathTmp.Vector3[0]);
  1538. };
  1539. /**
  1540. * Returns a new Vector3 as the normalization of the passed vector.
  1541. */
  1542. Vector3.Normalize = function (vector) {
  1543. var result = Vector3.Zero();
  1544. Vector3.NormalizeToRef(vector, result);
  1545. return result;
  1546. };
  1547. /**
  1548. * Sets the passed vector "result" with the normalization of the passed first vector.
  1549. */
  1550. Vector3.NormalizeToRef = function (vector, result) {
  1551. result.copyFrom(vector);
  1552. result.normalize();
  1553. };
  1554. Vector3.Project = function (vector, world, transform, viewport) {
  1555. var cw = viewport.width;
  1556. var ch = viewport.height;
  1557. var cx = viewport.x;
  1558. var cy = viewport.y;
  1559. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1560. 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);
  1561. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1562. world.multiplyToRef(transform, matrix);
  1563. matrix.multiplyToRef(viewportMatrix, matrix);
  1564. return Vector3.TransformCoordinates(vector, matrix);
  1565. };
  1566. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1567. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1568. world.multiplyToRef(transform, matrix);
  1569. matrix.invert();
  1570. source.x = source.x / viewportWidth * 2 - 1;
  1571. source.y = -(source.y / viewportHeight * 2 - 1);
  1572. var vector = Vector3.TransformCoordinates(source, matrix);
  1573. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1574. if (MathTools.WithinEpsilon(num, 1.0)) {
  1575. vector = vector.scale(1.0 / num);
  1576. }
  1577. return vector;
  1578. };
  1579. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1580. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1581. world.multiplyToRef(view, matrix);
  1582. matrix.multiplyToRef(projection, matrix);
  1583. matrix.invert();
  1584. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1585. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1586. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1587. if (MathTools.WithinEpsilon(num, 1.0)) {
  1588. vector = vector.scale(1.0 / num);
  1589. }
  1590. return vector;
  1591. };
  1592. Vector3.Minimize = function (left, right) {
  1593. var min = left.clone();
  1594. min.MinimizeInPlace(right);
  1595. return min;
  1596. };
  1597. Vector3.Maximize = function (left, right) {
  1598. var max = left.clone();
  1599. max.MaximizeInPlace(right);
  1600. return max;
  1601. };
  1602. /**
  1603. * Returns the distance (float) between the vectors "value1" and "value2".
  1604. */
  1605. Vector3.Distance = function (value1, value2) {
  1606. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1607. };
  1608. /**
  1609. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1610. */
  1611. Vector3.DistanceSquared = function (value1, value2) {
  1612. var x = value1.x - value2.x;
  1613. var y = value1.y - value2.y;
  1614. var z = value1.z - value2.z;
  1615. return (x * x) + (y * y) + (z * z);
  1616. };
  1617. /**
  1618. * Returns a new Vector3 located at the center between "value1" and "value2".
  1619. */
  1620. Vector3.Center = function (value1, value2) {
  1621. var center = value1.add(value2);
  1622. center.scaleInPlace(0.5);
  1623. return center;
  1624. };
  1625. /**
  1626. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1627. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1628. * to something in order to rotate it from its local system to the given target system.
  1629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1630. * Returns a new Vector3.
  1631. */
  1632. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1633. var rotation = Vector3.Zero();
  1634. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1635. return rotation;
  1636. };
  1637. /**
  1638. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1639. */
  1640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1641. var quat = MathTmp.Quaternion[0];
  1642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1643. quat.toEulerAnglesToRef(ref);
  1644. };
  1645. return Vector3;
  1646. }());
  1647. BABYLON.Vector3 = Vector3;
  1648. //Vector4 class created for EulerAngle class conversion to Quaternion
  1649. var Vector4 = (function () {
  1650. /**
  1651. * Creates a Vector4 object from the passed floats.
  1652. */
  1653. function Vector4(x, y, z, w) {
  1654. this.x = x;
  1655. this.y = y;
  1656. this.z = z;
  1657. this.w = w;
  1658. }
  1659. /**
  1660. * Returns the string with the Vector4 coordinates.
  1661. */
  1662. Vector4.prototype.toString = function () {
  1663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1664. };
  1665. /**
  1666. * Returns the string "Vector4".
  1667. */
  1668. Vector4.prototype.getClassName = function () {
  1669. return "Vector4";
  1670. };
  1671. /**
  1672. * Returns the Vector4 hash code.
  1673. */
  1674. Vector4.prototype.getHashCode = function () {
  1675. var hash = this.x || 0;
  1676. hash = (hash * 397) ^ (this.y || 0);
  1677. hash = (hash * 397) ^ (this.z || 0);
  1678. hash = (hash * 397) ^ (this.w || 0);
  1679. return hash;
  1680. };
  1681. // Operators
  1682. /**
  1683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1684. */
  1685. Vector4.prototype.asArray = function () {
  1686. var result = [];
  1687. this.toArray(result, 0);
  1688. return result;
  1689. };
  1690. /**
  1691. * Populates the passed array from the passed index with the Vector4 coordinates.
  1692. * Returns the Vector4.
  1693. */
  1694. Vector4.prototype.toArray = function (array, index) {
  1695. if (index === undefined) {
  1696. index = 0;
  1697. }
  1698. array[index] = this.x;
  1699. array[index + 1] = this.y;
  1700. array[index + 2] = this.z;
  1701. array[index + 3] = this.w;
  1702. return this;
  1703. };
  1704. /**
  1705. * Adds the passed vector to the current Vector4.
  1706. * Returns the updated Vector4.
  1707. */
  1708. Vector4.prototype.addInPlace = function (otherVector) {
  1709. this.x += otherVector.x;
  1710. this.y += otherVector.y;
  1711. this.z += otherVector.z;
  1712. this.w += otherVector.w;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1717. */
  1718. Vector4.prototype.add = function (otherVector) {
  1719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1720. };
  1721. /**
  1722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1723. * Returns the current Vector4.
  1724. */
  1725. Vector4.prototype.addToRef = function (otherVector, result) {
  1726. result.x = this.x + otherVector.x;
  1727. result.y = this.y + otherVector.y;
  1728. result.z = this.z + otherVector.z;
  1729. result.w = this.w + otherVector.w;
  1730. return this;
  1731. };
  1732. /**
  1733. * Subtract in place the passed vector from the current Vector4.
  1734. * Returns the updated Vector4.
  1735. */
  1736. Vector4.prototype.subtractInPlace = function (otherVector) {
  1737. this.x -= otherVector.x;
  1738. this.y -= otherVector.y;
  1739. this.z -= otherVector.z;
  1740. this.w -= otherVector.w;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1745. */
  1746. Vector4.prototype.subtract = function (otherVector) {
  1747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1748. };
  1749. /**
  1750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1751. * Returns the current Vector4.
  1752. */
  1753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1754. result.x = this.x - otherVector.x;
  1755. result.y = this.y - otherVector.y;
  1756. result.z = this.z - otherVector.z;
  1757. result.w = this.w - otherVector.w;
  1758. return this;
  1759. };
  1760. /**
  1761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1762. */
  1763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1765. };
  1766. /**
  1767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1768. * Returns the current Vector4.
  1769. */
  1770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1771. result.x = this.x - x;
  1772. result.y = this.y - y;
  1773. result.z = this.z - z;
  1774. result.w = this.w - w;
  1775. return this;
  1776. };
  1777. /**
  1778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1779. */
  1780. Vector4.prototype.negate = function () {
  1781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1782. };
  1783. /**
  1784. * Multiplies the current Vector4 coordinates by scale (float).
  1785. * Returns the updated Vector4.
  1786. */
  1787. Vector4.prototype.scaleInPlace = function (scale) {
  1788. this.x *= scale;
  1789. this.y *= scale;
  1790. this.z *= scale;
  1791. this.w *= scale;
  1792. return this;
  1793. };
  1794. /**
  1795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1796. */
  1797. Vector4.prototype.scale = function (scale) {
  1798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1799. };
  1800. /**
  1801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1802. * Returns the current Vector4.
  1803. */
  1804. Vector4.prototype.scaleToRef = function (scale, result) {
  1805. result.x = this.x * scale;
  1806. result.y = this.y * scale;
  1807. result.z = this.z * scale;
  1808. result.w = this.w * scale;
  1809. return this;
  1810. };
  1811. /**
  1812. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1813. */
  1814. Vector4.prototype.equals = function (otherVector) {
  1815. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1816. };
  1817. /**
  1818. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1819. */
  1820. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1822. return otherVector
  1823. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1824. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1825. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1826. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1827. };
  1828. /**
  1829. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1830. */
  1831. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1832. return this.x === x && this.y === y && this.z === z && this.w === w;
  1833. };
  1834. /**
  1835. * Multiplies in place the current Vector4 by the passed one.
  1836. * Returns the updated Vector4.
  1837. */
  1838. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1839. this.x *= otherVector.x;
  1840. this.y *= otherVector.y;
  1841. this.z *= otherVector.z;
  1842. this.w *= otherVector.w;
  1843. return this;
  1844. };
  1845. /**
  1846. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1847. */
  1848. Vector4.prototype.multiply = function (otherVector) {
  1849. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1850. };
  1851. /**
  1852. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1853. * Returns the current Vector4.
  1854. */
  1855. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1856. result.x = this.x * otherVector.x;
  1857. result.y = this.y * otherVector.y;
  1858. result.z = this.z * otherVector.z;
  1859. result.w = this.w * otherVector.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1864. */
  1865. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1866. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1867. };
  1868. /**
  1869. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1870. */
  1871. Vector4.prototype.divide = function (otherVector) {
  1872. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1873. };
  1874. /**
  1875. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1876. * Returns the current Vector4.
  1877. */
  1878. Vector4.prototype.divideToRef = function (otherVector, result) {
  1879. result.x = this.x / otherVector.x;
  1880. result.y = this.y / otherVector.y;
  1881. result.z = this.z / otherVector.z;
  1882. result.w = this.w / otherVector.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1887. */
  1888. Vector4.prototype.MinimizeInPlace = function (other) {
  1889. if (other.x < this.x)
  1890. this.x = other.x;
  1891. if (other.y < this.y)
  1892. this.y = other.y;
  1893. if (other.z < this.z)
  1894. this.z = other.z;
  1895. if (other.w < this.w)
  1896. this.w = other.w;
  1897. return this;
  1898. };
  1899. /**
  1900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1901. */
  1902. Vector4.prototype.MaximizeInPlace = function (other) {
  1903. if (other.x > this.x)
  1904. this.x = other.x;
  1905. if (other.y > this.y)
  1906. this.y = other.y;
  1907. if (other.z > this.z)
  1908. this.z = other.z;
  1909. if (other.w > this.w)
  1910. this.w = other.w;
  1911. return this;
  1912. };
  1913. // Properties
  1914. /**
  1915. * Returns the Vector4 length (float).
  1916. */
  1917. Vector4.prototype.length = function () {
  1918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1919. };
  1920. /**
  1921. * Returns the Vector4 squared length (float).
  1922. */
  1923. Vector4.prototype.lengthSquared = function () {
  1924. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1925. };
  1926. // Methods
  1927. /**
  1928. * Normalizes in place the Vector4.
  1929. * Returns the updated Vector4.
  1930. */
  1931. Vector4.prototype.normalize = function () {
  1932. var len = this.length();
  1933. if (len === 0)
  1934. return this;
  1935. var num = 1.0 / len;
  1936. this.x *= num;
  1937. this.y *= num;
  1938. this.z *= num;
  1939. this.w *= num;
  1940. return this;
  1941. };
  1942. /**
  1943. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1944. */
  1945. Vector4.prototype.toVector3 = function () {
  1946. return new Vector3(this.x, this.y, this.z);
  1947. };
  1948. /**
  1949. * Returns a new Vector4 copied from the current one.
  1950. */
  1951. Vector4.prototype.clone = function () {
  1952. return new Vector4(this.x, this.y, this.z, this.w);
  1953. };
  1954. /**
  1955. * Updates the current Vector4 with the passed one coordinates.
  1956. * Returns the updated Vector4.
  1957. */
  1958. Vector4.prototype.copyFrom = function (source) {
  1959. this.x = source.x;
  1960. this.y = source.y;
  1961. this.z = source.z;
  1962. this.w = source.w;
  1963. return this;
  1964. };
  1965. /**
  1966. * Updates the current Vector4 coordinates with the passed floats.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1970. this.x = x;
  1971. this.y = y;
  1972. this.z = z;
  1973. this.w = w;
  1974. return this;
  1975. };
  1976. /**
  1977. * Updates the current Vector4 coordinates with the passed floats.
  1978. * Returns the updated Vector4.
  1979. */
  1980. Vector4.prototype.set = function (x, y, z, w) {
  1981. return this.copyFromFloats(x, y, z, w);
  1982. };
  1983. // Statics
  1984. /**
  1985. * Returns a new Vector4 set from the starting index of the passed array.
  1986. */
  1987. Vector4.FromArray = function (array, offset) {
  1988. if (!offset) {
  1989. offset = 0;
  1990. }
  1991. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1992. };
  1993. /**
  1994. * Updates the passed vector "result" from the starting index of the passed array.
  1995. */
  1996. Vector4.FromArrayToRef = function (array, offset, result) {
  1997. result.x = array[offset];
  1998. result.y = array[offset + 1];
  1999. result.z = array[offset + 2];
  2000. result.w = array[offset + 3];
  2001. };
  2002. /**
  2003. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2004. */
  2005. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2006. result.x = array[offset];
  2007. result.y = array[offset + 1];
  2008. result.z = array[offset + 2];
  2009. result.w = array[offset + 3];
  2010. };
  2011. /**
  2012. * Updates the passed vector "result" coordinates from the passed floats.
  2013. */
  2014. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2015. result.x = x;
  2016. result.y = y;
  2017. result.z = z;
  2018. result.w = w;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2022. */
  2023. Vector4.Zero = function () {
  2024. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2025. };
  2026. /**
  2027. * Returns a new normalized Vector4 from the passed one.
  2028. */
  2029. Vector4.Normalize = function (vector) {
  2030. var result = Vector4.Zero();
  2031. Vector4.NormalizeToRef(vector, result);
  2032. return result;
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the normalization of the passed one.
  2036. */
  2037. Vector4.NormalizeToRef = function (vector, result) {
  2038. result.copyFrom(vector);
  2039. result.normalize();
  2040. };
  2041. Vector4.Minimize = function (left, right) {
  2042. var min = left.clone();
  2043. min.MinimizeInPlace(right);
  2044. return min;
  2045. };
  2046. Vector4.Maximize = function (left, right) {
  2047. var max = left.clone();
  2048. max.MaximizeInPlace(right);
  2049. return max;
  2050. };
  2051. /**
  2052. * Returns the distance (float) between the vectors "value1" and "value2".
  2053. */
  2054. Vector4.Distance = function (value1, value2) {
  2055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2056. };
  2057. /**
  2058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2059. */
  2060. Vector4.DistanceSquared = function (value1, value2) {
  2061. var x = value1.x - value2.x;
  2062. var y = value1.y - value2.y;
  2063. var z = value1.z - value2.z;
  2064. var w = value1.w - value2.w;
  2065. return (x * x) + (y * y) + (z * z) + (w * w);
  2066. };
  2067. /**
  2068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.Center = function (value1, value2) {
  2071. var center = value1.add(value2);
  2072. center.scaleInPlace(0.5);
  2073. return center;
  2074. };
  2075. /**
  2076. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2077. * This methods computes transformed normalized direction vectors only.
  2078. */
  2079. Vector4.TransformNormal = function (vector, transformation) {
  2080. var result = Vector4.Zero();
  2081. Vector4.TransformNormalToRef(vector, transformation, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2086. * This methods computes transformed normalized direction vectors only.
  2087. */
  2088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2092. result.x = x;
  2093. result.y = y;
  2094. result.z = z;
  2095. result.w = vector.w;
  2096. };
  2097. /**
  2098. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2099. * This methods computes transformed normalized direction vectors only.
  2100. */
  2101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2105. result.w = w;
  2106. };
  2107. return Vector4;
  2108. }());
  2109. BABYLON.Vector4 = Vector4;
  2110. var Size = (function () {
  2111. /**
  2112. * Creates a Size object from the passed width and height (floats).
  2113. */
  2114. function Size(width, height) {
  2115. this.width = width;
  2116. this.height = height;
  2117. }
  2118. // Returns a string with the Size width and height.
  2119. Size.prototype.toString = function () {
  2120. return "{W: " + this.width + ", H: " + this.height + "}";
  2121. };
  2122. /**
  2123. * Returns the string "Size"
  2124. */
  2125. Size.prototype.getClassName = function () {
  2126. return "Size";
  2127. };
  2128. /**
  2129. * Returns the Size hash code.
  2130. */
  2131. Size.prototype.getHashCode = function () {
  2132. var hash = this.width || 0;
  2133. hash = (hash * 397) ^ (this.height || 0);
  2134. return hash;
  2135. };
  2136. /**
  2137. * Updates the current size from the passed one.
  2138. * Returns the updated Size.
  2139. */
  2140. Size.prototype.copyFrom = function (src) {
  2141. this.width = src.width;
  2142. this.height = src.height;
  2143. };
  2144. /**
  2145. * Updates in place the current Size from the passed floats.
  2146. * Returns the updated Size.
  2147. */
  2148. Size.prototype.copyFromFloats = function (width, height) {
  2149. this.width = width;
  2150. this.height = height;
  2151. return this;
  2152. };
  2153. /**
  2154. * Updates in place the current Size from the passed floats.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.set = function (width, height) {
  2158. return this.copyFromFloats(width, height);
  2159. };
  2160. /**
  2161. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2162. */
  2163. Size.prototype.multiplyByFloats = function (w, h) {
  2164. return new Size(this.width * w, this.height * h);
  2165. };
  2166. /**
  2167. * Returns a new Size copied from the passed one.
  2168. */
  2169. Size.prototype.clone = function () {
  2170. return new Size(this.width, this.height);
  2171. };
  2172. /**
  2173. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2174. */
  2175. Size.prototype.equals = function (other) {
  2176. if (!other) {
  2177. return false;
  2178. }
  2179. return (this.width === other.width) && (this.height === other.height);
  2180. };
  2181. Object.defineProperty(Size.prototype, "surface", {
  2182. /**
  2183. * Returns the surface of the Size : width * height (float).
  2184. */
  2185. get: function () {
  2186. return this.width * this.height;
  2187. },
  2188. enumerable: true,
  2189. configurable: true
  2190. });
  2191. /**
  2192. * Returns a new Size set to (0.0, 0.0)
  2193. */
  2194. Size.Zero = function () {
  2195. return new Size(0.0, 0.0);
  2196. };
  2197. /**
  2198. * Returns a new Size set as the addition result of the current Size and the passed one.
  2199. */
  2200. Size.prototype.add = function (otherSize) {
  2201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2206. */
  2207. Size.prototype.subtract = function (otherSize) {
  2208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2209. return r;
  2210. };
  2211. /**
  2212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2213. */
  2214. Size.Lerp = function (start, end, amount) {
  2215. var w = start.width + ((end.width - start.width) * amount);
  2216. var h = start.height + ((end.height - start.height) * amount);
  2217. return new Size(w, h);
  2218. };
  2219. return Size;
  2220. }());
  2221. BABYLON.Size = Size;
  2222. var Quaternion = (function () {
  2223. /**
  2224. * Creates a new Quaternion from the passed floats.
  2225. */
  2226. function Quaternion(x, y, z, w) {
  2227. if (x === void 0) { x = 0.0; }
  2228. if (y === void 0) { y = 0.0; }
  2229. if (z === void 0) { z = 0.0; }
  2230. if (w === void 0) { w = 1.0; }
  2231. this.x = x;
  2232. this.y = y;
  2233. this.z = z;
  2234. this.w = w;
  2235. }
  2236. /**
  2237. * Returns a string with the Quaternion coordinates.
  2238. */
  2239. Quaternion.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Quaternion".
  2244. */
  2245. Quaternion.prototype.getClassName = function () {
  2246. return "Quaternion";
  2247. };
  2248. /**
  2249. * Returns the Quaternion hash code.
  2250. */
  2251. Quaternion.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. hash = (hash * 397) ^ (this.z || 0);
  2255. hash = (hash * 397) ^ (this.w || 0);
  2256. return hash;
  2257. };
  2258. /**
  2259. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2260. */
  2261. Quaternion.prototype.asArray = function () {
  2262. return [this.x, this.y, this.z, this.w];
  2263. };
  2264. /**
  2265. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2266. */
  2267. Quaternion.prototype.equals = function (otherQuaternion) {
  2268. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion copied from the current one.
  2272. */
  2273. Quaternion.prototype.clone = function () {
  2274. return new Quaternion(this.x, this.y, this.z, this.w);
  2275. };
  2276. /**
  2277. * Updates the current Quaternion from the passed one coordinates.
  2278. * Returns the updated Quaterion.
  2279. */
  2280. Quaternion.prototype.copyFrom = function (other) {
  2281. this.x = other.x;
  2282. this.y = other.y;
  2283. this.z = other.z;
  2284. this.w = other.w;
  2285. return this;
  2286. };
  2287. /**
  2288. * Updates the current Quaternion from the passed float coordinates.
  2289. * Returns the updated Quaterion.
  2290. */
  2291. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2292. this.x = x;
  2293. this.y = y;
  2294. this.z = z;
  2295. this.w = w;
  2296. return this;
  2297. };
  2298. /**
  2299. * Updates the current Quaternion from the passed float coordinates.
  2300. * Returns the updated Quaterion.
  2301. */
  2302. Quaternion.prototype.set = function (x, y, z, w) {
  2303. return this.copyFromFloats(x, y, z, w);
  2304. };
  2305. /**
  2306. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2307. */
  2308. Quaternion.prototype.add = function (other) {
  2309. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2310. };
  2311. /**
  2312. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2313. */
  2314. Quaternion.prototype.subtract = function (other) {
  2315. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2316. };
  2317. /**
  2318. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2319. */
  2320. Quaternion.prototype.scale = function (value) {
  2321. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2322. };
  2323. /**
  2324. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2325. */
  2326. Quaternion.prototype.multiply = function (q1) {
  2327. var result = new Quaternion(0, 0, 0, 1.0);
  2328. this.multiplyToRef(q1, result);
  2329. return result;
  2330. };
  2331. /**
  2332. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2333. * Returns the current Quaternion.
  2334. */
  2335. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2336. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2337. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2338. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2339. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2340. result.copyFromFloats(x, y, z, w);
  2341. return this;
  2342. };
  2343. /**
  2344. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.multiplyInPlace = function (q1) {
  2348. this.multiplyToRef(q1, this);
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2353. * Returns the current Quaternion.
  2354. */
  2355. Quaternion.prototype.conjugateToRef = function (ref) {
  2356. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2357. return this;
  2358. };
  2359. /**
  2360. * Conjugates in place the current Quaternion.
  2361. * Returns the updated Quaternion.
  2362. */
  2363. Quaternion.prototype.conjugateInPlace = function () {
  2364. this.x *= -1;
  2365. this.y *= -1;
  2366. this.z *= -1;
  2367. return this;
  2368. };
  2369. /**
  2370. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugate = function () {
  2373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2374. return result;
  2375. };
  2376. /**
  2377. * Returns the Quaternion length (float).
  2378. */
  2379. Quaternion.prototype.length = function () {
  2380. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2381. };
  2382. /**
  2383. * Normalize in place the current Quaternion.
  2384. * Returns the updated Quaternion.
  2385. */
  2386. Quaternion.prototype.normalize = function () {
  2387. var length = 1.0 / this.length();
  2388. this.x *= length;
  2389. this.y *= length;
  2390. this.z *= length;
  2391. this.w *= length;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2396. */
  2397. Quaternion.prototype.toEulerAngles = function (order) {
  2398. if (order === void 0) { order = "YZX"; }
  2399. var result = Vector3.Zero();
  2400. this.toEulerAnglesToRef(result, order);
  2401. return result;
  2402. };
  2403. /**
  2404. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2405. * Returns the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var qz = this.z;
  2410. var qx = this.x;
  2411. var qy = this.y;
  2412. var qw = this.w;
  2413. var sqw = qw * qw;
  2414. var sqz = qz * qz;
  2415. var sqx = qx * qx;
  2416. var sqy = qy * qy;
  2417. var zAxisY = qy * qz - qx * qw;
  2418. var limit = .4999999;
  2419. if (zAxisY < -limit) {
  2420. result.y = 2 * Math.atan2(qy, qw);
  2421. result.x = Math.PI / 2;
  2422. result.z = 0;
  2423. }
  2424. else if (zAxisY > limit) {
  2425. result.y = 2 * Math.atan2(qy, qw);
  2426. result.x = -Math.PI / 2;
  2427. result.z = 0;
  2428. }
  2429. else {
  2430. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2431. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2432. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2433. }
  2434. return this;
  2435. };
  2436. /**
  2437. * Updates the passed rotation matrix with the current Quaternion values.
  2438. * Returns the current Quaternion.
  2439. */
  2440. Quaternion.prototype.toRotationMatrix = function (result) {
  2441. var xx = this.x * this.x;
  2442. var yy = this.y * this.y;
  2443. var zz = this.z * this.z;
  2444. var xy = this.x * this.y;
  2445. var zw = this.z * this.w;
  2446. var zx = this.z * this.x;
  2447. var yw = this.y * this.w;
  2448. var yz = this.y * this.z;
  2449. var xw = this.x * this.w;
  2450. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2451. result.m[1] = 2.0 * (xy + zw);
  2452. result.m[2] = 2.0 * (zx - yw);
  2453. result.m[3] = 0;
  2454. result.m[4] = 2.0 * (xy - zw);
  2455. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2456. result.m[6] = 2.0 * (yz + xw);
  2457. result.m[7] = 0;
  2458. result.m[8] = 2.0 * (zx + yw);
  2459. result.m[9] = 2.0 * (yz - xw);
  2460. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2461. result.m[11] = 0;
  2462. result.m[12] = 0;
  2463. result.m[13] = 0;
  2464. result.m[14] = 0;
  2465. result.m[15] = 1.0;
  2466. return this;
  2467. };
  2468. /**
  2469. * Updates the current Quaternion from the passed rotation matrix values.
  2470. * Returns the updated Quaternion.
  2471. */
  2472. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2473. Quaternion.FromRotationMatrixToRef(matrix, this);
  2474. return this;
  2475. };
  2476. // Statics
  2477. /**
  2478. * Returns a new Quaternion set from the passed rotation matrix values.
  2479. */
  2480. Quaternion.FromRotationMatrix = function (matrix) {
  2481. var result = new Quaternion();
  2482. Quaternion.FromRotationMatrixToRef(matrix, result);
  2483. return result;
  2484. };
  2485. /**
  2486. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2487. */
  2488. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2489. var data = matrix.m;
  2490. var m11 = data[0], m12 = data[4], m13 = data[8];
  2491. var m21 = data[1], m22 = data[5], m23 = data[9];
  2492. var m31 = data[2], m32 = data[6], m33 = data[10];
  2493. var trace = m11 + m22 + m33;
  2494. var s;
  2495. if (trace > 0) {
  2496. s = 0.5 / Math.sqrt(trace + 1.0);
  2497. result.w = 0.25 / s;
  2498. result.x = (m32 - m23) * s;
  2499. result.y = (m13 - m31) * s;
  2500. result.z = (m21 - m12) * s;
  2501. }
  2502. else if (m11 > m22 && m11 > m33) {
  2503. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2504. result.w = (m32 - m23) / s;
  2505. result.x = 0.25 * s;
  2506. result.y = (m12 + m21) / s;
  2507. result.z = (m13 + m31) / s;
  2508. }
  2509. else if (m22 > m33) {
  2510. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2511. result.w = (m13 - m31) / s;
  2512. result.x = (m12 + m21) / s;
  2513. result.y = 0.25 * s;
  2514. result.z = (m23 + m32) / s;
  2515. }
  2516. else {
  2517. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2518. result.w = (m21 - m12) / s;
  2519. result.x = (m13 + m31) / s;
  2520. result.y = (m23 + m32) / s;
  2521. result.z = 0.25 * s;
  2522. }
  2523. };
  2524. /**
  2525. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2526. */
  2527. Quaternion.Zero = function () {
  2528. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the inverted current Quaternion.
  2532. */
  2533. Quaternion.Inverse = function (q) {
  2534. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2535. };
  2536. /**
  2537. * Returns the identity Quaternion.
  2538. */
  2539. Quaternion.Identity = function () {
  2540. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2541. };
  2542. Quaternion.IsIdentity = function (quaternion) {
  2543. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2544. };
  2545. /**
  2546. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2547. */
  2548. Quaternion.RotationAxis = function (axis, angle) {
  2549. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2550. };
  2551. /**
  2552. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2553. */
  2554. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2555. var sin = Math.sin(angle / 2);
  2556. axis.normalize();
  2557. result.w = Math.cos(angle / 2);
  2558. result.x = axis.x * sin;
  2559. result.y = axis.y * sin;
  2560. result.z = axis.z * sin;
  2561. return result;
  2562. };
  2563. /**
  2564. * Retuns a new Quaternion set from the starting index of the passed array.
  2565. */
  2566. Quaternion.FromArray = function (array, offset) {
  2567. if (!offset) {
  2568. offset = 0;
  2569. }
  2570. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2571. };
  2572. /**
  2573. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2574. */
  2575. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2576. var q = new Quaternion();
  2577. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2578. return q;
  2579. };
  2580. /**
  2581. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2582. */
  2583. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2584. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2585. var halfRoll = roll * 0.5;
  2586. var halfPitch = pitch * 0.5;
  2587. var halfYaw = yaw * 0.5;
  2588. var sinRoll = Math.sin(halfRoll);
  2589. var cosRoll = Math.cos(halfRoll);
  2590. var sinPitch = Math.sin(halfPitch);
  2591. var cosPitch = Math.cos(halfPitch);
  2592. var sinYaw = Math.sin(halfYaw);
  2593. var cosYaw = Math.cos(halfYaw);
  2594. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2595. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2596. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2597. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2598. };
  2599. /**
  2600. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2601. */
  2602. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2603. var result = new Quaternion();
  2604. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2605. return result;
  2606. };
  2607. /**
  2608. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2609. */
  2610. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2611. // Produces a quaternion from Euler angles in the z-x-z orientation
  2612. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2613. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2614. var halfBeta = beta * 0.5;
  2615. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2616. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2618. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. };
  2620. /**
  2621. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2622. * cf to Vector3.RotationFromAxis() documentation.
  2623. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2624. */
  2625. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2626. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2627. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2628. return quat;
  2629. };
  2630. /**
  2631. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2632. * cf to Vector3.RotationFromAxis() documentation.
  2633. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2634. */
  2635. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2636. var rotMat = MathTmp.Matrix[0];
  2637. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2638. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2639. };
  2640. Quaternion.Slerp = function (left, right, amount) {
  2641. var result = Quaternion.Identity();
  2642. Quaternion.SlerpToRef(left, right, amount, result);
  2643. return result;
  2644. };
  2645. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2646. var num2;
  2647. var num3;
  2648. var num = amount;
  2649. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2650. var flag = false;
  2651. if (num4 < 0) {
  2652. flag = true;
  2653. num4 = -num4;
  2654. }
  2655. if (num4 > 0.999999) {
  2656. num3 = 1 - num;
  2657. num2 = flag ? -num : num;
  2658. }
  2659. else {
  2660. var num5 = Math.acos(num4);
  2661. var num6 = (1.0 / Math.sin(num5));
  2662. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2663. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2664. }
  2665. result.x = (num3 * left.x) + (num2 * right.x);
  2666. result.y = (num3 * left.y) + (num2 * right.y);
  2667. result.z = (num3 * left.z) + (num2 * right.z);
  2668. result.w = (num3 * left.w) + (num2 * right.w);
  2669. };
  2670. return Quaternion;
  2671. }());
  2672. BABYLON.Quaternion = Quaternion;
  2673. var Matrix = (function () {
  2674. function Matrix() {
  2675. this.m = new Float32Array(16);
  2676. }
  2677. // Properties
  2678. /**
  2679. * Boolean : True is the matrix is the identity matrix
  2680. */
  2681. Matrix.prototype.isIdentity = function () {
  2682. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2683. return false;
  2684. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2685. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2686. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2687. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2688. return false;
  2689. return true;
  2690. };
  2691. /**
  2692. * Returns the matrix determinant (float).
  2693. */
  2694. Matrix.prototype.determinant = function () {
  2695. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2696. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2697. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2698. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2699. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2700. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2701. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2702. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2703. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2704. };
  2705. // Methods
  2706. /**
  2707. * Returns the matrix underlying array.
  2708. */
  2709. Matrix.prototype.toArray = function () {
  2710. return this.m;
  2711. };
  2712. /**
  2713. * Returns the matrix underlying array.
  2714. */
  2715. Matrix.prototype.asArray = function () {
  2716. return this.toArray();
  2717. };
  2718. /**
  2719. * Inverts in place the Matrix.
  2720. * Returns the Matrix inverted.
  2721. */
  2722. Matrix.prototype.invert = function () {
  2723. this.invertToRef(this);
  2724. return this;
  2725. };
  2726. /**
  2727. * Sets all the matrix elements to zero.
  2728. * Returns the Matrix.
  2729. */
  2730. Matrix.prototype.reset = function () {
  2731. for (var index = 0; index < 16; index++) {
  2732. this.m[index] = 0.0;
  2733. }
  2734. return this;
  2735. };
  2736. /**
  2737. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2738. */
  2739. Matrix.prototype.add = function (other) {
  2740. var result = new Matrix();
  2741. this.addToRef(other, result);
  2742. return result;
  2743. };
  2744. /**
  2745. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2746. * Returns the Matrix.
  2747. */
  2748. Matrix.prototype.addToRef = function (other, result) {
  2749. for (var index = 0; index < 16; index++) {
  2750. result.m[index] = this.m[index] + other.m[index];
  2751. }
  2752. return this;
  2753. };
  2754. /**
  2755. * Adds in place the passed matrix to the current Matrix.
  2756. * Returns the updated Matrix.
  2757. */
  2758. Matrix.prototype.addToSelf = function (other) {
  2759. for (var index = 0; index < 16; index++) {
  2760. this.m[index] += other.m[index];
  2761. }
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets the passed matrix with the current inverted Matrix.
  2766. * Returns the unmodified current Matrix.
  2767. */
  2768. Matrix.prototype.invertToRef = function (other) {
  2769. var l1 = this.m[0];
  2770. var l2 = this.m[1];
  2771. var l3 = this.m[2];
  2772. var l4 = this.m[3];
  2773. var l5 = this.m[4];
  2774. var l6 = this.m[5];
  2775. var l7 = this.m[6];
  2776. var l8 = this.m[7];
  2777. var l9 = this.m[8];
  2778. var l10 = this.m[9];
  2779. var l11 = this.m[10];
  2780. var l12 = this.m[11];
  2781. var l13 = this.m[12];
  2782. var l14 = this.m[13];
  2783. var l15 = this.m[14];
  2784. var l16 = this.m[15];
  2785. var l17 = (l11 * l16) - (l12 * l15);
  2786. var l18 = (l10 * l16) - (l12 * l14);
  2787. var l19 = (l10 * l15) - (l11 * l14);
  2788. var l20 = (l9 * l16) - (l12 * l13);
  2789. var l21 = (l9 * l15) - (l11 * l13);
  2790. var l22 = (l9 * l14) - (l10 * l13);
  2791. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2792. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2793. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2794. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2795. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2796. var l28 = (l7 * l16) - (l8 * l15);
  2797. var l29 = (l6 * l16) - (l8 * l14);
  2798. var l30 = (l6 * l15) - (l7 * l14);
  2799. var l31 = (l5 * l16) - (l8 * l13);
  2800. var l32 = (l5 * l15) - (l7 * l13);
  2801. var l33 = (l5 * l14) - (l6 * l13);
  2802. var l34 = (l7 * l12) - (l8 * l11);
  2803. var l35 = (l6 * l12) - (l8 * l10);
  2804. var l36 = (l6 * l11) - (l7 * l10);
  2805. var l37 = (l5 * l12) - (l8 * l9);
  2806. var l38 = (l5 * l11) - (l7 * l9);
  2807. var l39 = (l5 * l10) - (l6 * l9);
  2808. other.m[0] = l23 * l27;
  2809. other.m[4] = l24 * l27;
  2810. other.m[8] = l25 * l27;
  2811. other.m[12] = l26 * l27;
  2812. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2813. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2814. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2815. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2816. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2817. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2818. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2819. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2820. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2821. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2822. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2823. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2824. return this;
  2825. };
  2826. /**
  2827. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2828. * Returns the updated Matrix.
  2829. */
  2830. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2831. this.m[12] = x;
  2832. this.m[13] = y;
  2833. this.m[14] = z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Inserts the translation vector in the current Matrix.
  2838. * Returns the updated Matrix.
  2839. */
  2840. Matrix.prototype.setTranslation = function (vector3) {
  2841. this.m[12] = vector3.x;
  2842. this.m[13] = vector3.y;
  2843. this.m[14] = vector3.z;
  2844. return this;
  2845. };
  2846. /**
  2847. * Returns a new Vector3 as the extracted translation from the Matrix.
  2848. */
  2849. Matrix.prototype.getTranslation = function () {
  2850. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2851. };
  2852. /**
  2853. * Fill a Vector3 with the extracted translation from the Matrix.
  2854. */
  2855. Matrix.prototype.getTranslationToRef = function (result) {
  2856. result.x = this.m[12];
  2857. result.y = this.m[13];
  2858. result.z = this.m[14];
  2859. return this;
  2860. };
  2861. /**
  2862. * Remove rotation and scaling part from the Matrix.
  2863. * Returns the updated Matrix.
  2864. */
  2865. Matrix.prototype.removeRotationAndScaling = function () {
  2866. this.setRowFromFloats(0, 1, 0, 0, 0);
  2867. this.setRowFromFloats(1, 0, 1, 0, 0);
  2868. this.setRowFromFloats(2, 0, 0, 1, 0);
  2869. return this;
  2870. };
  2871. /**
  2872. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2873. */
  2874. Matrix.prototype.multiply = function (other) {
  2875. var result = new Matrix();
  2876. this.multiplyToRef(other, result);
  2877. return result;
  2878. };
  2879. /**
  2880. * Updates the current Matrix from the passed one values.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.copyFrom = function (other) {
  2884. for (var index = 0; index < 16; index++) {
  2885. this.m[index] = other.m[index];
  2886. }
  2887. return this;
  2888. };
  2889. /**
  2890. * Populates the passed array from the starting index with the Matrix values.
  2891. * Returns the Matrix.
  2892. */
  2893. Matrix.prototype.copyToArray = function (array, offset) {
  2894. if (offset === void 0) { offset = 0; }
  2895. for (var index = 0; index < 16; index++) {
  2896. array[offset + index] = this.m[index];
  2897. }
  2898. return this;
  2899. };
  2900. /**
  2901. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2902. */
  2903. Matrix.prototype.multiplyToRef = function (other, result) {
  2904. this.multiplyToArray(other, result.m, 0);
  2905. return this;
  2906. };
  2907. /**
  2908. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2909. */
  2910. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2911. var tm0 = this.m[0];
  2912. var tm1 = this.m[1];
  2913. var tm2 = this.m[2];
  2914. var tm3 = this.m[3];
  2915. var tm4 = this.m[4];
  2916. var tm5 = this.m[5];
  2917. var tm6 = this.m[6];
  2918. var tm7 = this.m[7];
  2919. var tm8 = this.m[8];
  2920. var tm9 = this.m[9];
  2921. var tm10 = this.m[10];
  2922. var tm11 = this.m[11];
  2923. var tm12 = this.m[12];
  2924. var tm13 = this.m[13];
  2925. var tm14 = this.m[14];
  2926. var tm15 = this.m[15];
  2927. var om0 = other.m[0];
  2928. var om1 = other.m[1];
  2929. var om2 = other.m[2];
  2930. var om3 = other.m[3];
  2931. var om4 = other.m[4];
  2932. var om5 = other.m[5];
  2933. var om6 = other.m[6];
  2934. var om7 = other.m[7];
  2935. var om8 = other.m[8];
  2936. var om9 = other.m[9];
  2937. var om10 = other.m[10];
  2938. var om11 = other.m[11];
  2939. var om12 = other.m[12];
  2940. var om13 = other.m[13];
  2941. var om14 = other.m[14];
  2942. var om15 = other.m[15];
  2943. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2944. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2945. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2946. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2947. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2948. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2949. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2950. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2951. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2952. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2953. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2954. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2955. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2956. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2957. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2958. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2959. return this;
  2960. };
  2961. /**
  2962. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2963. */
  2964. Matrix.prototype.equals = function (value) {
  2965. return value &&
  2966. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2967. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2968. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2969. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2970. };
  2971. /**
  2972. * Returns a new Matrix from the current Matrix.
  2973. */
  2974. Matrix.prototype.clone = function () {
  2975. 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]);
  2976. };
  2977. /**
  2978. * Returns the string "Matrix"
  2979. */
  2980. Matrix.prototype.getClassName = function () {
  2981. return "Matrix";
  2982. };
  2983. /**
  2984. * Returns the Matrix hash code.
  2985. */
  2986. Matrix.prototype.getHashCode = function () {
  2987. var hash = this.m[0] || 0;
  2988. for (var i = 1; i < 16; i++) {
  2989. hash = (hash * 397) ^ (this.m[i] || 0);
  2990. }
  2991. return hash;
  2992. };
  2993. /**
  2994. * Decomposes the current Matrix into :
  2995. * - a scale vector3 passed as a reference to update,
  2996. * - a rotation quaternion passed as a reference to update,
  2997. * - a translation vector3 passed as a reference to update.
  2998. * Returns the boolean `true`.
  2999. */
  3000. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3001. translation.x = this.m[12];
  3002. translation.y = this.m[13];
  3003. translation.z = this.m[14];
  3004. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3005. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3006. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3007. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3008. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3009. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3010. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3011. rotation.x = 0;
  3012. rotation.y = 0;
  3013. rotation.z = 0;
  3014. rotation.w = 1;
  3015. return false;
  3016. }
  3017. 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]);
  3018. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3019. return true;
  3020. };
  3021. /**
  3022. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3023. */
  3024. Matrix.prototype.getRotationMatrix = function () {
  3025. var result = Matrix.Identity();
  3026. this.getRotationMatrixToRef(result);
  3027. return result;
  3028. };
  3029. /**
  3030. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3031. * Returns the current Matrix.
  3032. */
  3033. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3034. var m = this.m;
  3035. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3036. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3037. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3038. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3039. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3040. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3041. 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);
  3042. return this;
  3043. };
  3044. // Statics
  3045. /**
  3046. * Returns a new Matrix set from the starting index of the passed array.
  3047. */
  3048. Matrix.FromArray = function (array, offset) {
  3049. var result = new Matrix();
  3050. if (!offset) {
  3051. offset = 0;
  3052. }
  3053. Matrix.FromArrayToRef(array, offset, result);
  3054. return result;
  3055. };
  3056. /**
  3057. * Sets the passed "result" matrix from the starting index of the passed array.
  3058. */
  3059. Matrix.FromArrayToRef = function (array, offset, result) {
  3060. for (var index = 0; index < 16; index++) {
  3061. result.m[index] = array[index + offset];
  3062. }
  3063. };
  3064. /**
  3065. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3066. */
  3067. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3068. for (var index = 0; index < 16; index++) {
  3069. result.m[index] = array[index + offset] * scale;
  3070. }
  3071. };
  3072. /**
  3073. * Sets the passed matrix "result" with the 16 passed floats.
  3074. */
  3075. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3076. result.m[0] = initialM11;
  3077. result.m[1] = initialM12;
  3078. result.m[2] = initialM13;
  3079. result.m[3] = initialM14;
  3080. result.m[4] = initialM21;
  3081. result.m[5] = initialM22;
  3082. result.m[6] = initialM23;
  3083. result.m[7] = initialM24;
  3084. result.m[8] = initialM31;
  3085. result.m[9] = initialM32;
  3086. result.m[10] = initialM33;
  3087. result.m[11] = initialM34;
  3088. result.m[12] = initialM41;
  3089. result.m[13] = initialM42;
  3090. result.m[14] = initialM43;
  3091. result.m[15] = initialM44;
  3092. };
  3093. /**
  3094. * Returns the index-th row of the current matrix as a new Vector4.
  3095. */
  3096. Matrix.prototype.getRow = function (index) {
  3097. if (index < 0 || index > 3) {
  3098. return null;
  3099. }
  3100. var i = index * 4;
  3101. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3102. };
  3103. /**
  3104. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3105. * Returns the updated Matrix.
  3106. */
  3107. Matrix.prototype.setRow = function (index, row) {
  3108. if (index < 0 || index > 3) {
  3109. return this;
  3110. }
  3111. var i = index * 4;
  3112. this.m[i + 0] = row.x;
  3113. this.m[i + 1] = row.y;
  3114. this.m[i + 2] = row.z;
  3115. this.m[i + 3] = row.w;
  3116. return this;
  3117. };
  3118. /**
  3119. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3120. * Returns the updated Matrix.
  3121. */
  3122. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3123. if (index < 0 || index > 3) {
  3124. return this;
  3125. }
  3126. var i = index * 4;
  3127. this.m[i + 0] = x;
  3128. this.m[i + 1] = y;
  3129. this.m[i + 2] = z;
  3130. this.m[i + 3] = w;
  3131. return this;
  3132. };
  3133. /**
  3134. * Returns a new Matrix set from the 16 passed floats.
  3135. */
  3136. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3137. var result = new Matrix();
  3138. result.m[0] = initialM11;
  3139. result.m[1] = initialM12;
  3140. result.m[2] = initialM13;
  3141. result.m[3] = initialM14;
  3142. result.m[4] = initialM21;
  3143. result.m[5] = initialM22;
  3144. result.m[6] = initialM23;
  3145. result.m[7] = initialM24;
  3146. result.m[8] = initialM31;
  3147. result.m[9] = initialM32;
  3148. result.m[10] = initialM33;
  3149. result.m[11] = initialM34;
  3150. result.m[12] = initialM41;
  3151. result.m[13] = initialM42;
  3152. result.m[14] = initialM43;
  3153. result.m[15] = initialM44;
  3154. return result;
  3155. };
  3156. /**
  3157. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3158. */
  3159. Matrix.Compose = function (scale, rotation, translation) {
  3160. var result = Matrix.Identity();
  3161. Matrix.ComposeToRef(scale, rotation, translation, result);
  3162. return result;
  3163. };
  3164. /**
  3165. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3166. */
  3167. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3168. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3169. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3170. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3171. result.setTranslation(translation);
  3172. };
  3173. /**
  3174. * Returns a new indentity Matrix.
  3175. */
  3176. Matrix.Identity = function () {
  3177. 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);
  3178. };
  3179. /**
  3180. * Sets the passed "result" as an identity matrix.
  3181. */
  3182. Matrix.IdentityToRef = function (result) {
  3183. 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);
  3184. };
  3185. /**
  3186. * Returns a new zero Matrix.
  3187. */
  3188. Matrix.Zero = function () {
  3189. 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);
  3190. };
  3191. /**
  3192. * Returns a new rotation matrix for "angle" radians around the X axis.
  3193. */
  3194. Matrix.RotationX = function (angle) {
  3195. var result = new Matrix();
  3196. Matrix.RotationXToRef(angle, result);
  3197. return result;
  3198. };
  3199. /**
  3200. * Returns a new Matrix as the passed inverted one.
  3201. */
  3202. Matrix.Invert = function (source) {
  3203. var result = new Matrix();
  3204. source.invertToRef(result);
  3205. return result;
  3206. };
  3207. /**
  3208. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3209. */
  3210. Matrix.RotationXToRef = function (angle, result) {
  3211. var s = Math.sin(angle);
  3212. var c = Math.cos(angle);
  3213. result.m[0] = 1.0;
  3214. result.m[15] = 1.0;
  3215. result.m[5] = c;
  3216. result.m[10] = c;
  3217. result.m[9] = -s;
  3218. result.m[6] = s;
  3219. result.m[1] = 0.0;
  3220. result.m[2] = 0.0;
  3221. result.m[3] = 0.0;
  3222. result.m[4] = 0.0;
  3223. result.m[7] = 0.0;
  3224. result.m[8] = 0.0;
  3225. result.m[11] = 0.0;
  3226. result.m[12] = 0.0;
  3227. result.m[13] = 0.0;
  3228. result.m[14] = 0.0;
  3229. };
  3230. /**
  3231. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3232. */
  3233. Matrix.RotationY = function (angle) {
  3234. var result = new Matrix();
  3235. Matrix.RotationYToRef(angle, result);
  3236. return result;
  3237. };
  3238. /**
  3239. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3240. */
  3241. Matrix.RotationYToRef = function (angle, result) {
  3242. var s = Math.sin(angle);
  3243. var c = Math.cos(angle);
  3244. result.m[5] = 1.0;
  3245. result.m[15] = 1.0;
  3246. result.m[0] = c;
  3247. result.m[2] = -s;
  3248. result.m[8] = s;
  3249. result.m[10] = c;
  3250. result.m[1] = 0.0;
  3251. result.m[3] = 0.0;
  3252. result.m[4] = 0.0;
  3253. result.m[6] = 0.0;
  3254. result.m[7] = 0.0;
  3255. result.m[9] = 0.0;
  3256. result.m[11] = 0.0;
  3257. result.m[12] = 0.0;
  3258. result.m[13] = 0.0;
  3259. result.m[14] = 0.0;
  3260. };
  3261. /**
  3262. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3263. */
  3264. Matrix.RotationZ = function (angle) {
  3265. var result = new Matrix();
  3266. Matrix.RotationZToRef(angle, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3271. */
  3272. Matrix.RotationZToRef = function (angle, result) {
  3273. var s = Math.sin(angle);
  3274. var c = Math.cos(angle);
  3275. result.m[10] = 1.0;
  3276. result.m[15] = 1.0;
  3277. result.m[0] = c;
  3278. result.m[1] = s;
  3279. result.m[4] = -s;
  3280. result.m[5] = c;
  3281. result.m[2] = 0.0;
  3282. result.m[3] = 0.0;
  3283. result.m[6] = 0.0;
  3284. result.m[7] = 0.0;
  3285. result.m[8] = 0.0;
  3286. result.m[9] = 0.0;
  3287. result.m[11] = 0.0;
  3288. result.m[12] = 0.0;
  3289. result.m[13] = 0.0;
  3290. result.m[14] = 0.0;
  3291. };
  3292. /**
  3293. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3294. */
  3295. Matrix.RotationAxis = function (axis, angle) {
  3296. var result = Matrix.Zero();
  3297. Matrix.RotationAxisToRef(axis, angle, result);
  3298. return result;
  3299. };
  3300. /**
  3301. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3302. */
  3303. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3304. var s = Math.sin(-angle);
  3305. var c = Math.cos(-angle);
  3306. var c1 = 1 - c;
  3307. axis.normalize();
  3308. result.m[0] = (axis.x * axis.x) * c1 + c;
  3309. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3310. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3311. result.m[3] = 0.0;
  3312. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3313. result.m[5] = (axis.y * axis.y) * c1 + c;
  3314. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3315. result.m[7] = 0.0;
  3316. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3317. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3318. result.m[10] = (axis.z * axis.z) * c1 + c;
  3319. result.m[11] = 0.0;
  3320. result.m[15] = 1.0;
  3321. };
  3322. /**
  3323. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3324. */
  3325. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3326. var result = new Matrix();
  3327. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3332. */
  3333. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3334. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3335. this._tempQuaternion.toRotationMatrix(result);
  3336. };
  3337. /**
  3338. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3339. */
  3340. Matrix.Scaling = function (x, y, z) {
  3341. var result = Matrix.Zero();
  3342. Matrix.ScalingToRef(x, y, z, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3347. */
  3348. Matrix.ScalingToRef = function (x, y, z, result) {
  3349. result.m[0] = x;
  3350. result.m[1] = 0.0;
  3351. result.m[2] = 0.0;
  3352. result.m[3] = 0.0;
  3353. result.m[4] = 0.0;
  3354. result.m[5] = y;
  3355. result.m[6] = 0.0;
  3356. result.m[7] = 0.0;
  3357. result.m[8] = 0.0;
  3358. result.m[9] = 0.0;
  3359. result.m[10] = z;
  3360. result.m[11] = 0.0;
  3361. result.m[12] = 0.0;
  3362. result.m[13] = 0.0;
  3363. result.m[14] = 0.0;
  3364. result.m[15] = 1.0;
  3365. };
  3366. /**
  3367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3368. */
  3369. Matrix.Translation = function (x, y, z) {
  3370. var result = Matrix.Identity();
  3371. Matrix.TranslationToRef(x, y, z, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3376. */
  3377. Matrix.TranslationToRef = function (x, y, z, result) {
  3378. 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);
  3379. };
  3380. /**
  3381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3382. */
  3383. Matrix.Lerp = function (startValue, endValue, gradient) {
  3384. var result = Matrix.Zero();
  3385. for (var index = 0; index < 16; index++) {
  3386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3387. }
  3388. return result;
  3389. };
  3390. /**
  3391. * Returns a new Matrix whose values are computed by :
  3392. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3393. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3394. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3395. */
  3396. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3397. var startScale = new Vector3(0, 0, 0);
  3398. var startRotation = new Quaternion();
  3399. var startTranslation = new Vector3(0, 0, 0);
  3400. startValue.decompose(startScale, startRotation, startTranslation);
  3401. var endScale = new Vector3(0, 0, 0);
  3402. var endRotation = new Quaternion();
  3403. var endTranslation = new Vector3(0, 0, 0);
  3404. endValue.decompose(endScale, endRotation, endTranslation);
  3405. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3406. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3407. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3408. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3409. };
  3410. /**
  3411. * 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".
  3412. * This methods works for a Left-Handed system.
  3413. */
  3414. Matrix.LookAtLH = function (eye, target, up) {
  3415. var result = Matrix.Zero();
  3416. Matrix.LookAtLHToRef(eye, target, up, result);
  3417. return result;
  3418. };
  3419. /**
  3420. * 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".
  3421. * This methods works for a Left-Handed system.
  3422. */
  3423. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3424. // Z axis
  3425. target.subtractToRef(eye, this._zAxis);
  3426. this._zAxis.normalize();
  3427. // X axis
  3428. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3429. if (this._xAxis.lengthSquared() === 0) {
  3430. this._xAxis.x = 1.0;
  3431. }
  3432. else {
  3433. this._xAxis.normalize();
  3434. }
  3435. // Y axis
  3436. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3437. this._yAxis.normalize();
  3438. // Eye angles
  3439. var ex = -Vector3.Dot(this._xAxis, eye);
  3440. var ey = -Vector3.Dot(this._yAxis, eye);
  3441. var ez = -Vector3.Dot(this._zAxis, eye);
  3442. 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);
  3443. };
  3444. /**
  3445. * 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".
  3446. * This methods works for a Right-Handed system.
  3447. */
  3448. Matrix.LookAtRH = function (eye, target, up) {
  3449. var result = Matrix.Zero();
  3450. Matrix.LookAtRHToRef(eye, target, up, result);
  3451. return result;
  3452. };
  3453. /**
  3454. * 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".
  3455. * This methods works for a Left-Handed system.
  3456. */
  3457. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3458. // Z axis
  3459. eye.subtractToRef(target, this._zAxis);
  3460. this._zAxis.normalize();
  3461. // X axis
  3462. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3463. if (this._xAxis.lengthSquared() === 0) {
  3464. this._xAxis.x = 1.0;
  3465. }
  3466. else {
  3467. this._xAxis.normalize();
  3468. }
  3469. // Y axis
  3470. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3471. this._yAxis.normalize();
  3472. // Eye angles
  3473. var ex = -Vector3.Dot(this._xAxis, eye);
  3474. var ey = -Vector3.Dot(this._yAxis, eye);
  3475. var ez = -Vector3.Dot(this._zAxis, eye);
  3476. 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);
  3477. };
  3478. /**
  3479. * 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.
  3480. */
  3481. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3482. var matrix = Matrix.Zero();
  3483. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3484. return matrix;
  3485. };
  3486. /**
  3487. * 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.
  3488. */
  3489. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3490. var n = znear;
  3491. var f = zfar;
  3492. var a = 2.0 / width;
  3493. var b = 2.0 / height;
  3494. var c = 2.0 / (f - n);
  3495. var d = -(f + n) / (f - n);
  3496. 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);
  3497. };
  3498. /**
  3499. * 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.
  3500. */
  3501. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3502. var matrix = Matrix.Zero();
  3503. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3504. return matrix;
  3505. };
  3506. /**
  3507. * 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.
  3508. */
  3509. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3510. var n = znear;
  3511. var f = zfar;
  3512. var a = 2.0 / (right - left);
  3513. var b = 2.0 / (top - bottom);
  3514. var c = 2.0 / (f - n);
  3515. var d = -(f + n) / (f - n);
  3516. var i0 = (left + right) / (left - right);
  3517. var i1 = (top + bottom) / (bottom - top);
  3518. 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);
  3519. };
  3520. /**
  3521. * 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.
  3522. */
  3523. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3524. var matrix = Matrix.Zero();
  3525. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3526. return matrix;
  3527. };
  3528. /**
  3529. * 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.
  3530. */
  3531. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3532. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3533. result.m[10] *= -1.0;
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. var n = znear;
  3541. var f = zfar;
  3542. var a = 2.0 * n / width;
  3543. var b = 2.0 * n / height;
  3544. var c = (f + n) / (f - n);
  3545. var d = -2.0 * f * n / (f - n);
  3546. 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);
  3547. return matrix;
  3548. };
  3549. /**
  3550. * 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.
  3551. */
  3552. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3553. var matrix = Matrix.Zero();
  3554. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3555. return matrix;
  3556. };
  3557. /**
  3558. * 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.
  3559. */
  3560. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3561. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3562. var n = znear;
  3563. var f = zfar;
  3564. var t = 1.0 / (Math.tan(fov * 0.5));
  3565. var a = isVerticalFovFixed ? (t / aspect) : t;
  3566. var b = isVerticalFovFixed ? t : (t * aspect);
  3567. var c = (f + n) / (f - n);
  3568. var d = -2.0 * f * n / (f - n);
  3569. 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);
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3575. var matrix = Matrix.Zero();
  3576. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3577. return matrix;
  3578. };
  3579. /**
  3580. * 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.
  3581. */
  3582. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3583. //alternatively this could be expressed as:
  3584. // m = PerspectiveFovLHToRef
  3585. // m[10] *= -1.0;
  3586. // m[11] *= -1.0;
  3587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3588. var n = znear;
  3589. var f = zfar;
  3590. var t = 1.0 / (Math.tan(fov * 0.5));
  3591. var a = isVerticalFovFixed ? (t / aspect) : t;
  3592. var b = isVerticalFovFixed ? t : (t * aspect);
  3593. var c = -(f + n) / (f - n);
  3594. var d = -2 * f * n / (f - n);
  3595. 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);
  3596. };
  3597. /**
  3598. * 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.
  3599. */
  3600. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3601. if (rightHanded === void 0) { rightHanded = false; }
  3602. var rightHandedFactor = rightHanded ? -1 : 1;
  3603. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3604. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3605. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3606. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3607. var xScale = 2.0 / (leftTan + rightTan);
  3608. var yScale = 2.0 / (upTan + downTan);
  3609. result.m[0] = xScale;
  3610. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3611. result.m[5] = yScale;
  3612. result.m[6] = result.m[7] = 0.0;
  3613. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3614. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3615. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3616. // result.m[10] = -zfar / (znear - zfar);
  3617. result.m[11] = 1.0 * rightHandedFactor;
  3618. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3619. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3620. // result.m[14] = (znear * zfar) / (znear - zfar);
  3621. };
  3622. /**
  3623. * Returns the final transformation matrix : world * view * projection * viewport
  3624. */
  3625. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3626. var cw = viewport.width;
  3627. var ch = viewport.height;
  3628. var cx = viewport.x;
  3629. var cy = viewport.y;
  3630. 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);
  3631. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3632. };
  3633. /**
  3634. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3635. */
  3636. Matrix.GetAsMatrix2x2 = function (matrix) {
  3637. return new Float32Array([
  3638. matrix.m[0], matrix.m[1],
  3639. matrix.m[4], matrix.m[5]
  3640. ]);
  3641. };
  3642. /**
  3643. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3644. */
  3645. Matrix.GetAsMatrix3x3 = function (matrix) {
  3646. return new Float32Array([
  3647. matrix.m[0], matrix.m[1], matrix.m[2],
  3648. matrix.m[4], matrix.m[5], matrix.m[6],
  3649. matrix.m[8], matrix.m[9], matrix.m[10]
  3650. ]);
  3651. };
  3652. /**
  3653. * Compute the transpose of the passed Matrix.
  3654. * Returns a new Matrix.
  3655. */
  3656. Matrix.Transpose = function (matrix) {
  3657. var result = new Matrix();
  3658. result.m[0] = matrix.m[0];
  3659. result.m[1] = matrix.m[4];
  3660. result.m[2] = matrix.m[8];
  3661. result.m[3] = matrix.m[12];
  3662. result.m[4] = matrix.m[1];
  3663. result.m[5] = matrix.m[5];
  3664. result.m[6] = matrix.m[9];
  3665. result.m[7] = matrix.m[13];
  3666. result.m[8] = matrix.m[2];
  3667. result.m[9] = matrix.m[6];
  3668. result.m[10] = matrix.m[10];
  3669. result.m[11] = matrix.m[14];
  3670. result.m[12] = matrix.m[3];
  3671. result.m[13] = matrix.m[7];
  3672. result.m[14] = matrix.m[11];
  3673. result.m[15] = matrix.m[15];
  3674. return result;
  3675. };
  3676. /**
  3677. * Returns a new Matrix as the reflection matrix across the passed plane.
  3678. */
  3679. Matrix.Reflection = function (plane) {
  3680. var matrix = new Matrix();
  3681. Matrix.ReflectionToRef(plane, matrix);
  3682. return matrix;
  3683. };
  3684. /**
  3685. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3686. */
  3687. Matrix.ReflectionToRef = function (plane, result) {
  3688. plane.normalize();
  3689. var x = plane.normal.x;
  3690. var y = plane.normal.y;
  3691. var z = plane.normal.z;
  3692. var temp = -2 * x;
  3693. var temp2 = -2 * y;
  3694. var temp3 = -2 * z;
  3695. result.m[0] = (temp * x) + 1;
  3696. result.m[1] = temp2 * x;
  3697. result.m[2] = temp3 * x;
  3698. result.m[3] = 0.0;
  3699. result.m[4] = temp * y;
  3700. result.m[5] = (temp2 * y) + 1;
  3701. result.m[6] = temp3 * y;
  3702. result.m[7] = 0.0;
  3703. result.m[8] = temp * z;
  3704. result.m[9] = temp2 * z;
  3705. result.m[10] = (temp3 * z) + 1;
  3706. result.m[11] = 0.0;
  3707. result.m[12] = temp * plane.d;
  3708. result.m[13] = temp2 * plane.d;
  3709. result.m[14] = temp3 * plane.d;
  3710. result.m[15] = 1.0;
  3711. };
  3712. /**
  3713. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3714. */
  3715. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3716. mat.m[0] = xaxis.x;
  3717. mat.m[1] = xaxis.y;
  3718. mat.m[2] = xaxis.z;
  3719. mat.m[3] = 0.0;
  3720. mat.m[4] = yaxis.x;
  3721. mat.m[5] = yaxis.y;
  3722. mat.m[6] = yaxis.z;
  3723. mat.m[7] = 0.0;
  3724. mat.m[8] = zaxis.x;
  3725. mat.m[9] = zaxis.y;
  3726. mat.m[10] = zaxis.z;
  3727. mat.m[11] = 0.0;
  3728. mat.m[12] = 0.0;
  3729. mat.m[13] = 0.0;
  3730. mat.m[14] = 0.0;
  3731. mat.m[15] = 1.0;
  3732. };
  3733. /**
  3734. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3735. */
  3736. Matrix.FromQuaternionToRef = function (quat, result) {
  3737. var xx = quat.x * quat.x;
  3738. var yy = quat.y * quat.y;
  3739. var zz = quat.z * quat.z;
  3740. var xy = quat.x * quat.y;
  3741. var zw = quat.z * quat.w;
  3742. var zx = quat.z * quat.x;
  3743. var yw = quat.y * quat.w;
  3744. var yz = quat.y * quat.z;
  3745. var xw = quat.x * quat.w;
  3746. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3747. result.m[1] = 2.0 * (xy + zw);
  3748. result.m[2] = 2.0 * (zx - yw);
  3749. result.m[3] = 0.0;
  3750. result.m[4] = 2.0 * (xy - zw);
  3751. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3752. result.m[6] = 2.0 * (yz + xw);
  3753. result.m[7] = 0.0;
  3754. result.m[8] = 2.0 * (zx + yw);
  3755. result.m[9] = 2.0 * (yz - xw);
  3756. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3757. result.m[11] = 0.0;
  3758. result.m[12] = 0.0;
  3759. result.m[13] = 0.0;
  3760. result.m[14] = 0.0;
  3761. result.m[15] = 1.0;
  3762. };
  3763. return Matrix;
  3764. }());
  3765. Matrix._tempQuaternion = new Quaternion();
  3766. Matrix._xAxis = Vector3.Zero();
  3767. Matrix._yAxis = Vector3.Zero();
  3768. Matrix._zAxis = Vector3.Zero();
  3769. BABYLON.Matrix = Matrix;
  3770. var Plane = (function () {
  3771. /**
  3772. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3773. */
  3774. function Plane(a, b, c, d) {
  3775. this.normal = new Vector3(a, b, c);
  3776. this.d = d;
  3777. }
  3778. /**
  3779. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3780. */
  3781. Plane.prototype.asArray = function () {
  3782. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3783. };
  3784. // Methods
  3785. /**
  3786. * Returns a new plane copied from the current Plane.
  3787. */
  3788. Plane.prototype.clone = function () {
  3789. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3790. };
  3791. /**
  3792. * Returns the string "Plane".
  3793. */
  3794. Plane.prototype.getClassName = function () {
  3795. return "Plane";
  3796. };
  3797. /**
  3798. * Returns the Plane hash code.
  3799. */
  3800. Plane.prototype.getHashCode = function () {
  3801. var hash = this.normal.getHashCode();
  3802. hash = (hash * 397) ^ (this.d || 0);
  3803. return hash;
  3804. };
  3805. /**
  3806. * Normalize the current Plane in place.
  3807. * Returns the updated Plane.
  3808. */
  3809. Plane.prototype.normalize = function () {
  3810. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3811. var magnitude = 0.0;
  3812. if (norm !== 0) {
  3813. magnitude = 1.0 / norm;
  3814. }
  3815. this.normal.x *= magnitude;
  3816. this.normal.y *= magnitude;
  3817. this.normal.z *= magnitude;
  3818. this.d *= magnitude;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3823. */
  3824. Plane.prototype.transform = function (transformation) {
  3825. var transposedMatrix = Matrix.Transpose(transformation);
  3826. var x = this.normal.x;
  3827. var y = this.normal.y;
  3828. var z = this.normal.z;
  3829. var d = this.d;
  3830. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3831. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3832. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3833. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3834. return new Plane(normalX, normalY, normalZ, finalD);
  3835. };
  3836. /**
  3837. * Returns the dot product (float) of the point coordinates and the plane normal.
  3838. */
  3839. Plane.prototype.dotCoordinate = function (point) {
  3840. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3841. };
  3842. /**
  3843. * Updates the current Plane from the plane defined by the three passed points.
  3844. * Returns the updated Plane.
  3845. */
  3846. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3847. var x1 = point2.x - point1.x;
  3848. var y1 = point2.y - point1.y;
  3849. var z1 = point2.z - point1.z;
  3850. var x2 = point3.x - point1.x;
  3851. var y2 = point3.y - point1.y;
  3852. var z2 = point3.z - point1.z;
  3853. var yz = (y1 * z2) - (z1 * y2);
  3854. var xz = (z1 * x2) - (x1 * z2);
  3855. var xy = (x1 * y2) - (y1 * x2);
  3856. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3857. var invPyth;
  3858. if (pyth !== 0) {
  3859. invPyth = 1.0 / pyth;
  3860. }
  3861. else {
  3862. invPyth = 0.0;
  3863. }
  3864. this.normal.x = yz * invPyth;
  3865. this.normal.y = xz * invPyth;
  3866. this.normal.z = xy * invPyth;
  3867. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3868. return this;
  3869. };
  3870. /**
  3871. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3872. */
  3873. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3874. var dot = Vector3.Dot(this.normal, direction);
  3875. return (dot <= epsilon);
  3876. };
  3877. /**
  3878. * Returns the signed distance (float) from the passed point to the Plane.
  3879. */
  3880. Plane.prototype.signedDistanceTo = function (point) {
  3881. return Vector3.Dot(point, this.normal) + this.d;
  3882. };
  3883. // Statics
  3884. /**
  3885. * Returns a new Plane from the passed array.
  3886. */
  3887. Plane.FromArray = function (array) {
  3888. return new Plane(array[0], array[1], array[2], array[3]);
  3889. };
  3890. /**
  3891. * Returns a new Plane defined by the three passed points.
  3892. */
  3893. Plane.FromPoints = function (point1, point2, point3) {
  3894. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3895. result.copyFromPoints(point1, point2, point3);
  3896. return result;
  3897. };
  3898. /**
  3899. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3900. * Note : the vector "normal" is updated because normalized.
  3901. */
  3902. Plane.FromPositionAndNormal = function (origin, normal) {
  3903. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3904. normal.normalize();
  3905. result.normal = normal;
  3906. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3907. return result;
  3908. };
  3909. /**
  3910. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3911. */
  3912. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3913. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3914. return Vector3.Dot(point, normal) + d;
  3915. };
  3916. return Plane;
  3917. }());
  3918. BABYLON.Plane = Plane;
  3919. var Viewport = (function () {
  3920. /**
  3921. * Creates a Viewport object located at (x, y) and sized (width, height).
  3922. */
  3923. function Viewport(x, y, width, height) {
  3924. this.x = x;
  3925. this.y = y;
  3926. this.width = width;
  3927. this.height = height;
  3928. }
  3929. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3930. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3931. };
  3932. /**
  3933. * Returns a new Viewport copied from the current one.
  3934. */
  3935. Viewport.prototype.clone = function () {
  3936. return new Viewport(this.x, this.y, this.width, this.height);
  3937. };
  3938. return Viewport;
  3939. }());
  3940. BABYLON.Viewport = Viewport;
  3941. var Frustum = (function () {
  3942. function Frustum() {
  3943. }
  3944. /**
  3945. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3946. */
  3947. Frustum.GetPlanes = function (transform) {
  3948. var frustumPlanes = [];
  3949. for (var index = 0; index < 6; index++) {
  3950. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3951. }
  3952. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3953. return frustumPlanes;
  3954. };
  3955. /**
  3956. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3957. */
  3958. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3959. // Near
  3960. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3961. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3962. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3963. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3964. frustumPlanes[0].normalize();
  3965. // Far
  3966. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3967. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3968. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3969. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3970. frustumPlanes[1].normalize();
  3971. // Left
  3972. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3973. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3974. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3975. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3976. frustumPlanes[2].normalize();
  3977. // Right
  3978. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3979. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3980. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3981. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3982. frustumPlanes[3].normalize();
  3983. // Top
  3984. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3985. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3986. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3987. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3988. frustumPlanes[4].normalize();
  3989. // Bottom
  3990. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3991. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3992. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3993. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3994. frustumPlanes[5].normalize();
  3995. };
  3996. return Frustum;
  3997. }());
  3998. BABYLON.Frustum = Frustum;
  3999. var Space;
  4000. (function (Space) {
  4001. Space[Space["LOCAL"] = 0] = "LOCAL";
  4002. Space[Space["WORLD"] = 1] = "WORLD";
  4003. Space[Space["BONE"] = 2] = "BONE";
  4004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4005. var Axis = (function () {
  4006. function Axis() {
  4007. }
  4008. return Axis;
  4009. }());
  4010. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4011. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4012. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4013. BABYLON.Axis = Axis;
  4014. ;
  4015. var BezierCurve = (function () {
  4016. function BezierCurve() {
  4017. }
  4018. /**
  4019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4020. */
  4021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4022. // Extract X (which is equal to time here)
  4023. var f0 = 1 - 3 * x2 + 3 * x1;
  4024. var f1 = 3 * x2 - 6 * x1;
  4025. var f2 = 3 * x1;
  4026. var refinedT = t;
  4027. for (var i = 0; i < 5; i++) {
  4028. var refinedT2 = refinedT * refinedT;
  4029. var refinedT3 = refinedT2 * refinedT;
  4030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4032. refinedT -= (x - t) * slope;
  4033. refinedT = Math.min(1, Math.max(0, refinedT));
  4034. }
  4035. // Resolve cubic bezier for the given x
  4036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4038. Math.pow(refinedT, 3);
  4039. };
  4040. return BezierCurve;
  4041. }());
  4042. BABYLON.BezierCurve = BezierCurve;
  4043. var Orientation;
  4044. (function (Orientation) {
  4045. Orientation[Orientation["CW"] = 0] = "CW";
  4046. Orientation[Orientation["CCW"] = 1] = "CCW";
  4047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4048. var Angle = (function () {
  4049. /**
  4050. * Creates an Angle object of "radians" radians (float).
  4051. */
  4052. function Angle(radians) {
  4053. var _this = this;
  4054. /**
  4055. * Returns the Angle value in degrees (float).
  4056. */
  4057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4058. /**
  4059. * Returns the Angle value in radians (float).
  4060. */
  4061. this.radians = function () { return _this._radians; };
  4062. this._radians = radians;
  4063. if (this._radians < 0.0)
  4064. this._radians += (2.0 * Math.PI);
  4065. }
  4066. /**
  4067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4068. */
  4069. Angle.BetweenTwoPoints = function (a, b) {
  4070. var delta = b.subtract(a);
  4071. var theta = Math.atan2(delta.y, delta.x);
  4072. return new Angle(theta);
  4073. };
  4074. /**
  4075. * Returns a new Angle object from the passed float in radians.
  4076. */
  4077. Angle.FromRadians = function (radians) {
  4078. return new Angle(radians);
  4079. };
  4080. /**
  4081. * Returns a new Angle object from the passed float in degrees.
  4082. */
  4083. Angle.FromDegrees = function (degrees) {
  4084. return new Angle(degrees * Math.PI / 180.0);
  4085. };
  4086. return Angle;
  4087. }());
  4088. BABYLON.Angle = Angle;
  4089. var Arc2 = (function () {
  4090. /**
  4091. * Creates an Arc object from the three passed points : start, middle and end.
  4092. */
  4093. function Arc2(startPoint, midPoint, endPoint) {
  4094. this.startPoint = startPoint;
  4095. this.midPoint = midPoint;
  4096. this.endPoint = endPoint;
  4097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4101. 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);
  4102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4104. var a1 = this.startAngle.degrees();
  4105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4107. // angles correction
  4108. if (a2 - a1 > +180.0)
  4109. a2 -= 360.0;
  4110. if (a2 - a1 < -180.0)
  4111. a2 += 360.0;
  4112. if (a3 - a2 > +180.0)
  4113. a3 -= 360.0;
  4114. if (a3 - a2 < -180.0)
  4115. a3 += 360.0;
  4116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4118. }
  4119. return Arc2;
  4120. }());
  4121. BABYLON.Arc2 = Arc2;
  4122. var Path2 = (function () {
  4123. /**
  4124. * Creates a Path2 object from the starting 2D coordinates x and y.
  4125. */
  4126. function Path2(x, y) {
  4127. this._points = new Array();
  4128. this._length = 0.0;
  4129. this.closed = false;
  4130. this._points.push(new Vector2(x, y));
  4131. }
  4132. /**
  4133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4134. * Returns the updated Path2.
  4135. */
  4136. Path2.prototype.addLineTo = function (x, y) {
  4137. if (closed) {
  4138. //Tools.Error("cannot add lines to closed paths");
  4139. return this;
  4140. }
  4141. var newPoint = new Vector2(x, y);
  4142. var previousPoint = this._points[this._points.length - 1];
  4143. this._points.push(newPoint);
  4144. this._length += newPoint.subtract(previousPoint).length();
  4145. return this;
  4146. };
  4147. /**
  4148. * 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.
  4149. * Returns the updated Path2.
  4150. */
  4151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4153. if (closed) {
  4154. //Tools.Error("cannot add arcs to closed paths");
  4155. return this;
  4156. }
  4157. var startPoint = this._points[this._points.length - 1];
  4158. var midPoint = new Vector2(midX, midY);
  4159. var endPoint = new Vector2(endX, endY);
  4160. var arc = new Arc2(startPoint, midPoint, endPoint);
  4161. var increment = arc.angle.radians() / numberOfSegments;
  4162. if (arc.orientation === Orientation.CW)
  4163. increment *= -1;
  4164. var currentAngle = arc.startAngle.radians() + increment;
  4165. for (var i = 0; i < numberOfSegments; i++) {
  4166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4168. this.addLineTo(x, y);
  4169. currentAngle += increment;
  4170. }
  4171. return this;
  4172. };
  4173. /**
  4174. * Closes the Path2.
  4175. * Returns the Path2.
  4176. */
  4177. Path2.prototype.close = function () {
  4178. this.closed = true;
  4179. return this;
  4180. };
  4181. /**
  4182. * Returns the Path2 total length (float).
  4183. */
  4184. Path2.prototype.length = function () {
  4185. var result = this._length;
  4186. if (!this.closed) {
  4187. var lastPoint = this._points[this._points.length - 1];
  4188. var firstPoint = this._points[0];
  4189. result += (firstPoint.subtract(lastPoint).length());
  4190. }
  4191. return result;
  4192. };
  4193. /**
  4194. * Returns the Path2 internal array of points.
  4195. */
  4196. Path2.prototype.getPoints = function () {
  4197. return this._points;
  4198. };
  4199. /**
  4200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4201. */
  4202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4204. //Tools.Error("normalized length position should be between 0 and 1.");
  4205. return Vector2.Zero();
  4206. }
  4207. var lengthPosition = normalizedLengthPosition * this.length();
  4208. var previousOffset = 0;
  4209. for (var i = 0; i < this._points.length; i++) {
  4210. var j = (i + 1) % this._points.length;
  4211. var a = this._points[i];
  4212. var b = this._points[j];
  4213. var bToA = b.subtract(a);
  4214. var nextOffset = (bToA.length() + previousOffset);
  4215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4216. var dir = bToA.normalize();
  4217. var localOffset = lengthPosition - previousOffset;
  4218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4219. }
  4220. previousOffset = nextOffset;
  4221. }
  4222. //Tools.Error("internal error");
  4223. return Vector2.Zero();
  4224. };
  4225. /**
  4226. * Returns a new Path2 starting at the coordinates (x, y).
  4227. */
  4228. Path2.StartingAt = function (x, y) {
  4229. return new Path2(x, y);
  4230. };
  4231. return Path2;
  4232. }());
  4233. BABYLON.Path2 = Path2;
  4234. var Path3D = (function () {
  4235. /**
  4236. * new Path3D(path, normal, raw)
  4237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4239. * path : an array of Vector3, the curve axis of the Path3D
  4240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4242. */
  4243. function Path3D(path, firstNormal, raw) {
  4244. this.path = path;
  4245. this._curve = new Array();
  4246. this._distances = new Array();
  4247. this._tangents = new Array();
  4248. this._normals = new Array();
  4249. this._binormals = new Array();
  4250. for (var p = 0; p < path.length; p++) {
  4251. this._curve[p] = path[p].clone(); // hard copy
  4252. }
  4253. this._raw = raw || false;
  4254. this._compute(firstNormal);
  4255. }
  4256. /**
  4257. * Returns the Path3D array of successive Vector3 designing its curve.
  4258. */
  4259. Path3D.prototype.getCurve = function () {
  4260. return this._curve;
  4261. };
  4262. /**
  4263. * Returns an array populated with tangent vectors on each Path3D curve point.
  4264. */
  4265. Path3D.prototype.getTangents = function () {
  4266. return this._tangents;
  4267. };
  4268. /**
  4269. * Returns an array populated with normal vectors on each Path3D curve point.
  4270. */
  4271. Path3D.prototype.getNormals = function () {
  4272. return this._normals;
  4273. };
  4274. /**
  4275. * Returns an array populated with binormal vectors on each Path3D curve point.
  4276. */
  4277. Path3D.prototype.getBinormals = function () {
  4278. return this._binormals;
  4279. };
  4280. /**
  4281. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4282. */
  4283. Path3D.prototype.getDistances = function () {
  4284. return this._distances;
  4285. };
  4286. /**
  4287. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4288. * Returns the same object updated.
  4289. */
  4290. Path3D.prototype.update = function (path, firstNormal) {
  4291. for (var p = 0; p < path.length; p++) {
  4292. this._curve[p].x = path[p].x;
  4293. this._curve[p].y = path[p].y;
  4294. this._curve[p].z = path[p].z;
  4295. }
  4296. this._compute(firstNormal);
  4297. return this;
  4298. };
  4299. // private function compute() : computes tangents, normals and binormals
  4300. Path3D.prototype._compute = function (firstNormal) {
  4301. var l = this._curve.length;
  4302. // first and last tangents
  4303. this._tangents[0] = this._getFirstNonNullVector(0);
  4304. if (!this._raw) {
  4305. this._tangents[0].normalize();
  4306. }
  4307. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4308. if (!this._raw) {
  4309. this._tangents[l - 1].normalize();
  4310. }
  4311. // normals and binormals at first point : arbitrary vector with _normalVector()
  4312. var tg0 = this._tangents[0];
  4313. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4314. this._normals[0] = pp0;
  4315. if (!this._raw) {
  4316. this._normals[0].normalize();
  4317. }
  4318. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4319. if (!this._raw) {
  4320. this._binormals[0].normalize();
  4321. }
  4322. this._distances[0] = 0.0;
  4323. // normals and binormals : next points
  4324. var prev; // previous vector (segment)
  4325. var cur; // current vector (segment)
  4326. var curTang; // current tangent
  4327. // previous normal
  4328. var prevBinor; // previous binormal
  4329. for (var i = 1; i < l; i++) {
  4330. // tangents
  4331. prev = this._getLastNonNullVector(i);
  4332. if (i < l - 1) {
  4333. cur = this._getFirstNonNullVector(i);
  4334. this._tangents[i] = prev.add(cur);
  4335. this._tangents[i].normalize();
  4336. }
  4337. this._distances[i] = this._distances[i - 1] + prev.length();
  4338. // normals and binormals
  4339. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4340. curTang = this._tangents[i];
  4341. prevBinor = this._binormals[i - 1];
  4342. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4343. if (!this._raw) {
  4344. this._normals[i].normalize();
  4345. }
  4346. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4347. if (!this._raw) {
  4348. this._binormals[i].normalize();
  4349. }
  4350. }
  4351. };
  4352. // private function getFirstNonNullVector(index)
  4353. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4354. Path3D.prototype._getFirstNonNullVector = function (index) {
  4355. var i = 1;
  4356. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4357. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4358. i++;
  4359. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4360. }
  4361. return nNVector;
  4362. };
  4363. // private function getLastNonNullVector(index)
  4364. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4365. Path3D.prototype._getLastNonNullVector = function (index) {
  4366. var i = 1;
  4367. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4368. while (nLVector.length() === 0 && index > i + 1) {
  4369. i++;
  4370. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4371. }
  4372. return nLVector;
  4373. };
  4374. // private function normalVector(v0, vt, va) :
  4375. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4376. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4377. Path3D.prototype._normalVector = function (v0, vt, va) {
  4378. var normal0;
  4379. var tgl = vt.length();
  4380. if (tgl === 0.0) {
  4381. tgl = 1.0;
  4382. }
  4383. if (va === undefined || va === null) {
  4384. var point;
  4385. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4386. point = new Vector3(0.0, -1.0, 0.0);
  4387. }
  4388. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4389. point = new Vector3(1.0, 0.0, 0.0);
  4390. }
  4391. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4392. point = new Vector3(0.0, 0.0, 1.0);
  4393. }
  4394. normal0 = Vector3.Cross(vt, point);
  4395. }
  4396. else {
  4397. normal0 = Vector3.Cross(vt, va);
  4398. Vector3.CrossToRef(normal0, vt, normal0);
  4399. }
  4400. normal0.normalize();
  4401. return normal0;
  4402. };
  4403. return Path3D;
  4404. }());
  4405. BABYLON.Path3D = Path3D;
  4406. var Curve3 = (function () {
  4407. /**
  4408. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4409. * A Curve3 is designed from a series of successive Vector3.
  4410. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4411. */
  4412. function Curve3(points) {
  4413. this._length = 0.0;
  4414. this._points = points;
  4415. this._length = this._computeLength(points);
  4416. }
  4417. /**
  4418. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4419. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4420. * @param v1 (Vector3) the control point
  4421. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4422. * @param nbPoints (integer) the wanted number of points in the curve
  4423. */
  4424. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4425. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4426. var bez = new Array();
  4427. var equation = function (t, val0, val1, val2) {
  4428. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4429. return res;
  4430. };
  4431. for (var i = 0; i <= nbPoints; i++) {
  4432. 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)));
  4433. }
  4434. return new Curve3(bez);
  4435. };
  4436. /**
  4437. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4438. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4439. * @param v1 (Vector3) the first control point
  4440. * @param v2 (Vector3) the second control point
  4441. * @param v3 (Vector3) the end point of the Cubic Bezier
  4442. * @param nbPoints (integer) the wanted number of points in the curve
  4443. */
  4444. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4445. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4446. var bez = new Array();
  4447. var equation = function (t, val0, val1, val2, val3) {
  4448. 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;
  4449. return res;
  4450. };
  4451. for (var i = 0; i <= nbPoints; i++) {
  4452. 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)));
  4453. }
  4454. return new Curve3(bez);
  4455. };
  4456. /**
  4457. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4458. * @param p1 (Vector3) the origin point of the Hermite Spline
  4459. * @param t1 (Vector3) the tangent vector at the origin point
  4460. * @param p2 (Vector3) the end point of the Hermite Spline
  4461. * @param t2 (Vector3) the tangent vector at the end point
  4462. * @param nbPoints (integer) the wanted number of points in the curve
  4463. */
  4464. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4465. var hermite = new Array();
  4466. var step = 1.0 / nbPoints;
  4467. for (var i = 0; i <= nbPoints; i++) {
  4468. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4469. }
  4470. return new Curve3(hermite);
  4471. };
  4472. /**
  4473. * Returns a Curve3 object along a CatmullRom Spline curve :
  4474. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4475. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4476. */
  4477. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4478. var totalPoints = new Array();
  4479. totalPoints.push(points[0].clone());
  4480. Array.prototype.push.apply(totalPoints, points);
  4481. totalPoints.push(points[points.length - 1].clone());
  4482. var catmullRom = new Array();
  4483. var step = 1.0 / nbPoints;
  4484. for (var i = 0; i < totalPoints.length - 3; i++) {
  4485. var amount = 0.0;
  4486. for (var c = 0; c < nbPoints; c++) {
  4487. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4488. amount += step;
  4489. }
  4490. }
  4491. i--;
  4492. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4493. return new Curve3(catmullRom);
  4494. };
  4495. /**
  4496. * Returns the Curve3 stored array of successive Vector3
  4497. */
  4498. Curve3.prototype.getPoints = function () {
  4499. return this._points;
  4500. };
  4501. /**
  4502. * Returns the computed length (float) of the curve.
  4503. */
  4504. Curve3.prototype.length = function () {
  4505. return this._length;
  4506. };
  4507. /**
  4508. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4509. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4510. * curveA and curveB keep unchanged.
  4511. */
  4512. Curve3.prototype.continue = function (curve) {
  4513. var lastPoint = this._points[this._points.length - 1];
  4514. var continuedPoints = this._points.slice();
  4515. var curvePoints = curve.getPoints();
  4516. for (var i = 1; i < curvePoints.length; i++) {
  4517. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4518. }
  4519. var continuedCurve = new Curve3(continuedPoints);
  4520. return continuedCurve;
  4521. };
  4522. Curve3.prototype._computeLength = function (path) {
  4523. var l = 0;
  4524. for (var i = 1; i < path.length; i++) {
  4525. l += (path[i].subtract(path[i - 1])).length();
  4526. }
  4527. return l;
  4528. };
  4529. return Curve3;
  4530. }());
  4531. BABYLON.Curve3 = Curve3;
  4532. // SphericalHarmonics
  4533. var SphericalHarmonics = (function () {
  4534. function SphericalHarmonics() {
  4535. this.L00 = Vector3.Zero();
  4536. this.L1_1 = Vector3.Zero();
  4537. this.L10 = Vector3.Zero();
  4538. this.L11 = Vector3.Zero();
  4539. this.L2_2 = Vector3.Zero();
  4540. this.L2_1 = Vector3.Zero();
  4541. this.L20 = Vector3.Zero();
  4542. this.L21 = Vector3.Zero();
  4543. this.L22 = Vector3.Zero();
  4544. }
  4545. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4546. var colorVector = new Vector3(color.r, color.g, color.b);
  4547. var c = colorVector.scale(deltaSolidAngle);
  4548. this.L00 = this.L00.add(c.scale(0.282095));
  4549. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4550. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4551. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4552. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4553. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4554. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4555. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4556. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4557. };
  4558. SphericalHarmonics.prototype.scale = function (scale) {
  4559. this.L00 = this.L00.scale(scale);
  4560. this.L1_1 = this.L1_1.scale(scale);
  4561. this.L10 = this.L10.scale(scale);
  4562. this.L11 = this.L11.scale(scale);
  4563. this.L2_2 = this.L2_2.scale(scale);
  4564. this.L2_1 = this.L2_1.scale(scale);
  4565. this.L20 = this.L20.scale(scale);
  4566. this.L21 = this.L21.scale(scale);
  4567. this.L22 = this.L22.scale(scale);
  4568. };
  4569. return SphericalHarmonics;
  4570. }());
  4571. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4572. // SphericalPolynomial
  4573. var SphericalPolynomial = (function () {
  4574. function SphericalPolynomial() {
  4575. this.x = Vector3.Zero();
  4576. this.y = Vector3.Zero();
  4577. this.z = Vector3.Zero();
  4578. this.xx = Vector3.Zero();
  4579. this.yy = Vector3.Zero();
  4580. this.zz = Vector3.Zero();
  4581. this.xy = Vector3.Zero();
  4582. this.yz = Vector3.Zero();
  4583. this.zx = Vector3.Zero();
  4584. }
  4585. SphericalPolynomial.prototype.addAmbient = function (color) {
  4586. var colorVector = new Vector3(color.r, color.g, color.b);
  4587. this.xx = this.xx.add(colorVector);
  4588. this.yy = this.yy.add(colorVector);
  4589. this.zz = this.zz.add(colorVector);
  4590. };
  4591. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4592. var result = new SphericalPolynomial();
  4593. result.x = harmonics.L11.scale(1.02333);
  4594. result.y = harmonics.L1_1.scale(1.02333);
  4595. result.z = harmonics.L10.scale(1.02333);
  4596. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4597. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4598. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4599. result.yz = harmonics.L2_1.scale(0.858086);
  4600. result.zx = harmonics.L21.scale(0.858086);
  4601. result.xy = harmonics.L2_2.scale(0.858086);
  4602. return result;
  4603. };
  4604. return SphericalPolynomial;
  4605. }());
  4606. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. return Tmp;
  4644. }());
  4645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero(),
  4653. Matrix.Zero(), Matrix.Zero(),
  4654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. return MathTmp;
  4661. }());
  4662. MathTmp.Vector3 = [Vector3.Zero()];
  4663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4664. MathTmp.Quaternion = [Quaternion.Zero()];
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. //# sourceMappingURL=babylon.mixins.js.map
  4668. var BABYLON;
  4669. (function (BABYLON) {
  4670. function generateSerializableMember(type, sourceName) {
  4671. return function (target, propertyKey) {
  4672. if (!target.__serializableMembers) {
  4673. target.__serializableMembers = {};
  4674. }
  4675. if (!target.__serializableMembers[propertyKey]) {
  4676. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4677. }
  4678. };
  4679. }
  4680. function serialize(sourceName) {
  4681. return generateSerializableMember(0, sourceName); // value member
  4682. }
  4683. BABYLON.serialize = serialize;
  4684. function serializeAsTexture(sourceName) {
  4685. return generateSerializableMember(1, sourceName); // texture member
  4686. }
  4687. BABYLON.serializeAsTexture = serializeAsTexture;
  4688. function serializeAsColor3(sourceName) {
  4689. return generateSerializableMember(2, sourceName); // color3 member
  4690. }
  4691. BABYLON.serializeAsColor3 = serializeAsColor3;
  4692. function serializeAsFresnelParameters(sourceName) {
  4693. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4694. }
  4695. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4696. function serializeAsVector2(sourceName) {
  4697. return generateSerializableMember(4, sourceName); // vector2 member
  4698. }
  4699. BABYLON.serializeAsVector2 = serializeAsVector2;
  4700. function serializeAsVector3(sourceName) {
  4701. return generateSerializableMember(5, sourceName); // vector3 member
  4702. }
  4703. BABYLON.serializeAsVector3 = serializeAsVector3;
  4704. function serializeAsMeshReference(sourceName) {
  4705. return generateSerializableMember(6, sourceName); // mesh reference member
  4706. }
  4707. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4708. function serializeAsColorCurves(sourceName) {
  4709. return generateSerializableMember(7, sourceName); // color curves
  4710. }
  4711. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4712. var SerializationHelper = (function () {
  4713. function SerializationHelper() {
  4714. }
  4715. SerializationHelper.Serialize = function (entity, serializationObject) {
  4716. if (!serializationObject) {
  4717. serializationObject = {};
  4718. }
  4719. // Tags
  4720. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4721. // Properties
  4722. for (var property in entity.__serializableMembers) {
  4723. var propertyDescriptor = entity.__serializableMembers[property];
  4724. var targetPropertyName = propertyDescriptor.sourceName || property;
  4725. var propertyType = propertyDescriptor.type;
  4726. var sourceProperty = entity[property];
  4727. if (sourceProperty !== undefined && sourceProperty !== null) {
  4728. switch (propertyType) {
  4729. case 0:
  4730. serializationObject[targetPropertyName] = sourceProperty;
  4731. break;
  4732. case 1:
  4733. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4734. break;
  4735. case 2:
  4736. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4737. break;
  4738. case 3:
  4739. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4740. break;
  4741. case 4:
  4742. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4743. break;
  4744. case 5:
  4745. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4746. break;
  4747. case 6:
  4748. serializationObject[targetPropertyName] = sourceProperty.id;
  4749. break;
  4750. case 7:
  4751. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4752. break;
  4753. }
  4754. }
  4755. }
  4756. return serializationObject;
  4757. };
  4758. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4759. var destination = creationFunction();
  4760. // Tags
  4761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4762. // Properties
  4763. for (var property in destination.__serializableMembers) {
  4764. var propertyDescriptor = destination.__serializableMembers[property];
  4765. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4766. var propertyType = propertyDescriptor.type;
  4767. if (sourceProperty !== undefined && sourceProperty !== null) {
  4768. switch (propertyType) {
  4769. case 0:
  4770. destination[property] = sourceProperty;
  4771. break;
  4772. case 1:
  4773. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4774. break;
  4775. case 2:
  4776. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4777. break;
  4778. case 3:
  4779. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4780. break;
  4781. case 4:
  4782. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4783. break;
  4784. case 5:
  4785. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4786. break;
  4787. case 6:
  4788. destination[property] = scene.getLastMeshByID(sourceProperty);
  4789. break;
  4790. case 7:
  4791. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4792. break;
  4793. }
  4794. }
  4795. }
  4796. return destination;
  4797. };
  4798. SerializationHelper.Clone = function (creationFunction, source) {
  4799. var destination = creationFunction();
  4800. // Tags
  4801. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4802. // Properties
  4803. for (var property in destination.__serializableMembers) {
  4804. var propertyDescriptor = destination.__serializableMembers[property];
  4805. var sourceProperty = source[property];
  4806. var propertyType = propertyDescriptor.type;
  4807. if (sourceProperty !== undefined && sourceProperty !== null) {
  4808. switch (propertyType) {
  4809. case 0: // Value
  4810. case 6:
  4811. destination[property] = sourceProperty;
  4812. break;
  4813. case 1: // Texture
  4814. case 2: // Color3
  4815. case 3: // FresnelParameters
  4816. case 4: // Vector2
  4817. case 5: // Vector3
  4818. case 7:
  4819. destination[property] = sourceProperty.clone();
  4820. break;
  4821. }
  4822. }
  4823. }
  4824. return destination;
  4825. };
  4826. return SerializationHelper;
  4827. }());
  4828. BABYLON.SerializationHelper = SerializationHelper;
  4829. })(BABYLON || (BABYLON = {}));
  4830. //# sourceMappingURL=babylon.decorators.js.map
  4831. var BABYLON;
  4832. (function (BABYLON) {
  4833. /**
  4834. * A class serves as a medium between the observable and its observers
  4835. */
  4836. var EventState = (function () {
  4837. /**
  4838. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4839. */
  4840. function EventState(mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.initalize(mask, skipNextObservers);
  4843. }
  4844. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4845. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4846. this.mask = mask;
  4847. this.skipNextObservers = skipNextObservers;
  4848. return this;
  4849. };
  4850. return EventState;
  4851. }());
  4852. BABYLON.EventState = EventState;
  4853. /**
  4854. * Represent an Observer registered to a given Observable object.
  4855. */
  4856. var Observer = (function () {
  4857. function Observer(callback, mask) {
  4858. this.callback = callback;
  4859. this.mask = mask;
  4860. }
  4861. return Observer;
  4862. }());
  4863. BABYLON.Observer = Observer;
  4864. /**
  4865. * The Observable class is a simple implementation of the Observable pattern.
  4866. * 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.
  4867. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4868. * 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).
  4869. * 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.
  4870. */
  4871. var Observable = (function () {
  4872. function Observable() {
  4873. this._observers = new Array();
  4874. this._eventState = new EventState(0);
  4875. }
  4876. /**
  4877. * Create a new Observer with the specified callback
  4878. * @param callback the callback that will be executed for that Observer
  4879. * @param mask the mask used to filter observers
  4880. * @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.
  4881. */
  4882. Observable.prototype.add = function (callback, mask, insertFirst) {
  4883. if (mask === void 0) { mask = -1; }
  4884. if (insertFirst === void 0) { insertFirst = false; }
  4885. if (!callback) {
  4886. return null;
  4887. }
  4888. var observer = new Observer(callback, mask);
  4889. if (insertFirst) {
  4890. this._observers.unshift(observer);
  4891. }
  4892. else {
  4893. this._observers.push(observer);
  4894. }
  4895. return observer;
  4896. };
  4897. /**
  4898. * Remove an Observer from the Observable object
  4899. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4900. */
  4901. Observable.prototype.remove = function (observer) {
  4902. var index = this._observers.indexOf(observer);
  4903. if (index !== -1) {
  4904. this._observers.splice(index, 1);
  4905. return true;
  4906. }
  4907. return false;
  4908. };
  4909. /**
  4910. * Remove a callback from the Observable object
  4911. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4912. */
  4913. Observable.prototype.removeCallback = function (callback) {
  4914. for (var index = 0; index < this._observers.length; index++) {
  4915. if (this._observers[index].callback === callback) {
  4916. this._observers.splice(index, 1);
  4917. return true;
  4918. }
  4919. }
  4920. return false;
  4921. };
  4922. /**
  4923. * Notify all Observers by calling their respective callback with the given data
  4924. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4925. * @param eventData
  4926. * @param mask
  4927. */
  4928. Observable.prototype.notifyObservers = function (eventData, mask) {
  4929. if (mask === void 0) { mask = -1; }
  4930. var state = this._eventState;
  4931. state.mask = mask;
  4932. state.skipNextObservers = false;
  4933. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4934. var obs = _a[_i];
  4935. if (obs.mask & mask) {
  4936. obs.callback(eventData, state);
  4937. }
  4938. if (state.skipNextObservers) {
  4939. return false;
  4940. }
  4941. }
  4942. return true;
  4943. };
  4944. /**
  4945. * return true is the Observable has at least one Observer registered
  4946. */
  4947. Observable.prototype.hasObservers = function () {
  4948. return this._observers.length > 0;
  4949. };
  4950. /**
  4951. * Clear the list of observers
  4952. */
  4953. Observable.prototype.clear = function () {
  4954. this._observers = new Array();
  4955. };
  4956. /**
  4957. * Clone the current observable
  4958. */
  4959. Observable.prototype.clone = function () {
  4960. var result = new Observable();
  4961. result._observers = this._observers.slice(0);
  4962. return result;
  4963. };
  4964. /**
  4965. * Does this observable handles observer registered with a given mask
  4966. * @param {number} trigger - the mask to be tested
  4967. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4968. **/
  4969. Observable.prototype.hasSpecificMask = function (mask) {
  4970. if (mask === void 0) { mask = -1; }
  4971. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4972. var obs = _a[_i];
  4973. if (obs.mask & mask && obs.mask === mask) {
  4974. return true;
  4975. }
  4976. }
  4977. return false;
  4978. };
  4979. return Observable;
  4980. }());
  4981. BABYLON.Observable = Observable;
  4982. })(BABYLON || (BABYLON = {}));
  4983. //# sourceMappingURL=babylon.observable.js.map
  4984. var BABYLON;
  4985. (function (BABYLON) {
  4986. var Database = (function () {
  4987. function Database(urlToScene, callbackManifestChecked) {
  4988. // Handling various flavors of prefixed version of IndexedDB
  4989. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4990. this.callbackManifestChecked = callbackManifestChecked;
  4991. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4992. this.db = null;
  4993. this.enableSceneOffline = false;
  4994. this.enableTexturesOffline = false;
  4995. this.manifestVersionFound = 0;
  4996. this.mustUpdateRessources = false;
  4997. this.hasReachedQuota = false;
  4998. if (!Database.IDBStorageEnabled) {
  4999. this.callbackManifestChecked(true);
  5000. }
  5001. else {
  5002. this.checkManifestFile();
  5003. }
  5004. }
  5005. Database.prototype.checkManifestFile = function () {
  5006. var _this = this;
  5007. function noManifestFile() {
  5008. that.enableSceneOffline = false;
  5009. that.enableTexturesOffline = false;
  5010. that.callbackManifestChecked(false);
  5011. }
  5012. var that = this;
  5013. var timeStampUsed = false;
  5014. var manifestURL = this.currentSceneUrl + ".manifest";
  5015. var xhr = new XMLHttpRequest();
  5016. if (navigator.onLine) {
  5017. // Adding a timestamp to by-pass browsers' cache
  5018. timeStampUsed = true;
  5019. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5020. }
  5021. xhr.open("GET", manifestURL, true);
  5022. xhr.addEventListener("load", function () {
  5023. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5024. try {
  5025. var manifestFile = JSON.parse(xhr.response);
  5026. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5027. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5028. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5029. _this.manifestVersionFound = manifestFile.version;
  5030. }
  5031. if (_this.callbackManifestChecked) {
  5032. _this.callbackManifestChecked(true);
  5033. }
  5034. }
  5035. catch (ex) {
  5036. noManifestFile();
  5037. }
  5038. }
  5039. else {
  5040. noManifestFile();
  5041. }
  5042. }, false);
  5043. xhr.addEventListener("error", function (event) {
  5044. if (timeStampUsed) {
  5045. timeStampUsed = false;
  5046. // Let's retry without the timeStamp
  5047. // It could fail when coupled with HTML5 Offline API
  5048. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5049. xhr.open("GET", retryManifestURL, true);
  5050. xhr.send();
  5051. }
  5052. else {
  5053. noManifestFile();
  5054. }
  5055. }, false);
  5056. try {
  5057. xhr.send();
  5058. }
  5059. catch (ex) {
  5060. BABYLON.Tools.Error("Error on XHR send request.");
  5061. that.callbackManifestChecked(false);
  5062. }
  5063. };
  5064. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5065. var _this = this;
  5066. function handleError() {
  5067. that.isSupported = false;
  5068. if (errorCallback)
  5069. errorCallback();
  5070. }
  5071. var that = this;
  5072. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5073. // Your browser doesn't support IndexedDB
  5074. this.isSupported = false;
  5075. if (errorCallback)
  5076. errorCallback();
  5077. }
  5078. else {
  5079. // If the DB hasn't been opened or created yet
  5080. if (!this.db) {
  5081. this.hasReachedQuota = false;
  5082. this.isSupported = true;
  5083. var request = this.idbFactory.open("babylonjs", 1);
  5084. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5085. request.onerror = function (event) {
  5086. handleError();
  5087. };
  5088. // executes when a version change transaction cannot complete due to other active transactions
  5089. request.onblocked = function (event) {
  5090. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5091. handleError();
  5092. };
  5093. // DB has been opened successfully
  5094. request.onsuccess = function (event) {
  5095. _this.db = request.result;
  5096. successCallback();
  5097. };
  5098. // Initialization of the DB. Creating Scenes & Textures stores
  5099. request.onupgradeneeded = function (event) {
  5100. _this.db = (event.target).result;
  5101. try {
  5102. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5103. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5104. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5105. }
  5106. catch (ex) {
  5107. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5108. handleError();
  5109. }
  5110. };
  5111. }
  5112. else {
  5113. if (successCallback)
  5114. successCallback();
  5115. }
  5116. }
  5117. };
  5118. Database.prototype.loadImageFromDB = function (url, image) {
  5119. var _this = this;
  5120. var completeURL = Database.ReturnFullUrlLocation(url);
  5121. var saveAndLoadImage = function () {
  5122. if (!_this.hasReachedQuota && _this.db !== null) {
  5123. // the texture is not yet in the DB, let's try to save it
  5124. _this._saveImageIntoDBAsync(completeURL, image);
  5125. }
  5126. else {
  5127. image.src = url;
  5128. }
  5129. };
  5130. if (!this.mustUpdateRessources) {
  5131. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5132. }
  5133. else {
  5134. saveAndLoadImage();
  5135. }
  5136. };
  5137. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5138. if (this.isSupported && this.db !== null) {
  5139. var texture;
  5140. var transaction = this.db.transaction(["textures"]);
  5141. transaction.onabort = function (event) {
  5142. image.src = url;
  5143. };
  5144. transaction.oncomplete = function (event) {
  5145. var blobTextureURL;
  5146. if (texture) {
  5147. var URL = window.URL || window.webkitURL;
  5148. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5149. image.onerror = function () {
  5150. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5151. image.src = url;
  5152. };
  5153. image.src = blobTextureURL;
  5154. }
  5155. else {
  5156. notInDBCallback();
  5157. }
  5158. };
  5159. var getRequest = transaction.objectStore("textures").get(url);
  5160. getRequest.onsuccess = function (event) {
  5161. texture = (event.target).result;
  5162. };
  5163. getRequest.onerror = function (event) {
  5164. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5165. image.src = url;
  5166. };
  5167. }
  5168. else {
  5169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5170. image.src = url;
  5171. }
  5172. };
  5173. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5174. var _this = this;
  5175. if (this.isSupported) {
  5176. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5177. var generateBlobUrl = function () {
  5178. var blobTextureURL;
  5179. if (blob) {
  5180. var URL = window.URL || window.webkitURL;
  5181. try {
  5182. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5183. }
  5184. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5185. catch (ex) {
  5186. blobTextureURL = URL.createObjectURL(blob);
  5187. }
  5188. }
  5189. image.src = blobTextureURL;
  5190. };
  5191. if (Database.IsUASupportingBlobStorage) {
  5192. var xhr = new XMLHttpRequest(), blob;
  5193. xhr.open("GET", url, true);
  5194. xhr.responseType = "blob";
  5195. xhr.addEventListener("load", function () {
  5196. if (xhr.status === 200) {
  5197. // Blob as response (XHR2)
  5198. blob = xhr.response;
  5199. var transaction = _this.db.transaction(["textures"], "readwrite");
  5200. // the transaction could abort because of a QuotaExceededError error
  5201. transaction.onabort = function (event) {
  5202. try {
  5203. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5204. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5205. _this.hasReachedQuota = true;
  5206. }
  5207. }
  5208. catch (ex) { }
  5209. generateBlobUrl();
  5210. };
  5211. transaction.oncomplete = function (event) {
  5212. generateBlobUrl();
  5213. };
  5214. var newTexture = { textureUrl: url, data: blob };
  5215. try {
  5216. // Put the blob into the dabase
  5217. var addRequest = transaction.objectStore("textures").put(newTexture);
  5218. addRequest.onsuccess = function (event) {
  5219. };
  5220. addRequest.onerror = function (event) {
  5221. generateBlobUrl();
  5222. };
  5223. }
  5224. catch (ex) {
  5225. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5226. if (ex.code === 25) {
  5227. Database.IsUASupportingBlobStorage = false;
  5228. }
  5229. image.src = url;
  5230. }
  5231. }
  5232. else {
  5233. image.src = url;
  5234. }
  5235. }, false);
  5236. xhr.addEventListener("error", function (event) {
  5237. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5238. image.src = url;
  5239. }, false);
  5240. xhr.send();
  5241. }
  5242. else {
  5243. image.src = url;
  5244. }
  5245. }
  5246. else {
  5247. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5248. image.src = url;
  5249. }
  5250. };
  5251. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5252. var _this = this;
  5253. var updateVersion = function (event) {
  5254. // the version is not yet in the DB or we need to update it
  5255. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5256. };
  5257. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5258. };
  5259. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5260. var _this = this;
  5261. if (this.isSupported) {
  5262. var version;
  5263. try {
  5264. var transaction = this.db.transaction(["versions"]);
  5265. transaction.oncomplete = function (event) {
  5266. if (version) {
  5267. // If the version in the JSON file is > than the version in DB
  5268. if (_this.manifestVersionFound > version.data) {
  5269. _this.mustUpdateRessources = true;
  5270. updateInDBCallback();
  5271. }
  5272. else {
  5273. callback(version.data);
  5274. }
  5275. }
  5276. else {
  5277. _this.mustUpdateRessources = true;
  5278. updateInDBCallback();
  5279. }
  5280. };
  5281. transaction.onabort = function (event) {
  5282. callback(-1);
  5283. };
  5284. var getRequest = transaction.objectStore("versions").get(url);
  5285. getRequest.onsuccess = function (event) {
  5286. version = (event.target).result;
  5287. };
  5288. getRequest.onerror = function (event) {
  5289. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5290. callback(-1);
  5291. };
  5292. }
  5293. catch (ex) {
  5294. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5295. callback(-1);
  5296. }
  5297. }
  5298. else {
  5299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5300. callback(-1);
  5301. }
  5302. };
  5303. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5304. var _this = this;
  5305. if (this.isSupported && !this.hasReachedQuota) {
  5306. try {
  5307. // Open a transaction to the database
  5308. var transaction = this.db.transaction(["versions"], "readwrite");
  5309. // the transaction could abort because of a QuotaExceededError error
  5310. transaction.onabort = function (event) {
  5311. try {
  5312. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5313. _this.hasReachedQuota = true;
  5314. }
  5315. }
  5316. catch (ex) { }
  5317. callback(-1);
  5318. };
  5319. transaction.oncomplete = function (event) {
  5320. callback(_this.manifestVersionFound);
  5321. };
  5322. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5323. // Put the scene into the database
  5324. var addRequest = transaction.objectStore("versions").put(newVersion);
  5325. addRequest.onsuccess = function (event) {
  5326. };
  5327. addRequest.onerror = function (event) {
  5328. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5329. };
  5330. }
  5331. catch (ex) {
  5332. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5333. callback(-1);
  5334. }
  5335. }
  5336. else {
  5337. callback(-1);
  5338. }
  5339. };
  5340. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5341. var _this = this;
  5342. var completeUrl = Database.ReturnFullUrlLocation(url);
  5343. var saveAndLoadFile = function (event) {
  5344. // the scene is not yet in the DB, let's try to save it
  5345. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5346. };
  5347. this._checkVersionFromDB(completeUrl, function (version) {
  5348. if (version !== -1) {
  5349. if (!_this.mustUpdateRessources) {
  5350. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5351. }
  5352. else {
  5353. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5354. }
  5355. }
  5356. else {
  5357. errorCallback();
  5358. }
  5359. });
  5360. };
  5361. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5362. if (this.isSupported) {
  5363. var targetStore;
  5364. if (url.indexOf(".babylon") !== -1) {
  5365. targetStore = "scenes";
  5366. }
  5367. else {
  5368. targetStore = "textures";
  5369. }
  5370. var file;
  5371. var transaction = this.db.transaction([targetStore]);
  5372. transaction.oncomplete = function (event) {
  5373. if (file) {
  5374. callback(file.data);
  5375. }
  5376. else {
  5377. notInDBCallback();
  5378. }
  5379. };
  5380. transaction.onabort = function (event) {
  5381. notInDBCallback();
  5382. };
  5383. var getRequest = transaction.objectStore(targetStore).get(url);
  5384. getRequest.onsuccess = function (event) {
  5385. file = (event.target).result;
  5386. };
  5387. getRequest.onerror = function (event) {
  5388. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5389. notInDBCallback();
  5390. };
  5391. }
  5392. else {
  5393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5394. callback();
  5395. }
  5396. };
  5397. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5398. var _this = this;
  5399. if (this.isSupported) {
  5400. var targetStore;
  5401. if (url.indexOf(".babylon") !== -1) {
  5402. targetStore = "scenes";
  5403. }
  5404. else {
  5405. targetStore = "textures";
  5406. }
  5407. // Create XHR
  5408. var xhr = new XMLHttpRequest(), fileData;
  5409. xhr.open("GET", url, true);
  5410. if (useArrayBuffer) {
  5411. xhr.responseType = "arraybuffer";
  5412. }
  5413. xhr.onprogress = progressCallback;
  5414. xhr.addEventListener("load", function () {
  5415. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5416. // Blob as response (XHR2)
  5417. //fileData = xhr.responseText;
  5418. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5419. if (!_this.hasReachedQuota) {
  5420. // Open a transaction to the database
  5421. var transaction = _this.db.transaction([targetStore], "readwrite");
  5422. // the transaction could abort because of a QuotaExceededError error
  5423. transaction.onabort = function (event) {
  5424. try {
  5425. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5426. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5427. _this.hasReachedQuota = true;
  5428. }
  5429. }
  5430. catch (ex) { }
  5431. callback(fileData);
  5432. };
  5433. transaction.oncomplete = function (event) {
  5434. callback(fileData);
  5435. };
  5436. var newFile;
  5437. if (targetStore === "scenes") {
  5438. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5439. }
  5440. else {
  5441. newFile = { textureUrl: url, data: fileData };
  5442. }
  5443. try {
  5444. // Put the scene into the database
  5445. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5446. addRequest.onsuccess = function (event) {
  5447. };
  5448. addRequest.onerror = function (event) {
  5449. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5450. };
  5451. }
  5452. catch (ex) {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback(fileData);
  5458. }
  5459. }
  5460. else {
  5461. callback();
  5462. }
  5463. }, false);
  5464. xhr.addEventListener("error", function (event) {
  5465. BABYLON.Tools.Error("error on XHR request.");
  5466. callback();
  5467. }, false);
  5468. xhr.send();
  5469. }
  5470. else {
  5471. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5472. callback();
  5473. }
  5474. };
  5475. return Database;
  5476. }());
  5477. Database.IsUASupportingBlobStorage = true;
  5478. Database.IDBStorageEnabled = true;
  5479. Database.parseURL = function (url) {
  5480. var a = document.createElement('a');
  5481. a.href = url;
  5482. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5483. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5484. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5485. return absLocation;
  5486. };
  5487. Database.ReturnFullUrlLocation = function (url) {
  5488. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5489. return (Database.parseURL(window.location.href) + url);
  5490. }
  5491. else {
  5492. return url;
  5493. }
  5494. };
  5495. BABYLON.Database = Database;
  5496. })(BABYLON || (BABYLON = {}));
  5497. //# sourceMappingURL=babylon.database.js.map
  5498. var BABYLON;
  5499. (function (BABYLON) {
  5500. var Internals;
  5501. (function (Internals) {
  5502. /*
  5503. * Based on jsTGALoader - Javascript loader for TGA file
  5504. * By Vincent Thibault
  5505. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5506. */
  5507. var TGATools = (function () {
  5508. function TGATools() {
  5509. }
  5510. TGATools.GetTGAHeader = function (data) {
  5511. var offset = 0;
  5512. var header = {
  5513. id_length: data[offset++],
  5514. colormap_type: data[offset++],
  5515. image_type: data[offset++],
  5516. colormap_index: data[offset++] | data[offset++] << 8,
  5517. colormap_length: data[offset++] | data[offset++] << 8,
  5518. colormap_size: data[offset++],
  5519. origin: [
  5520. data[offset++] | data[offset++] << 8,
  5521. data[offset++] | data[offset++] << 8
  5522. ],
  5523. width: data[offset++] | data[offset++] << 8,
  5524. height: data[offset++] | data[offset++] << 8,
  5525. pixel_size: data[offset++],
  5526. flags: data[offset++]
  5527. };
  5528. return header;
  5529. };
  5530. TGATools.UploadContent = function (gl, data) {
  5531. // Not enough data to contain header ?
  5532. if (data.length < 19) {
  5533. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5534. return;
  5535. }
  5536. // Read Header
  5537. var offset = 18;
  5538. var header = TGATools.GetTGAHeader(data);
  5539. // Assume it's a valid Targa file.
  5540. if (header.id_length + offset > data.length) {
  5541. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5542. return;
  5543. }
  5544. // Skip not needed data
  5545. offset += header.id_length;
  5546. var use_rle = false;
  5547. var use_pal = false;
  5548. var use_rgb = false;
  5549. var use_grey = false;
  5550. // Get some informations.
  5551. switch (header.image_type) {
  5552. case TGATools._TYPE_RLE_INDEXED:
  5553. use_rle = true;
  5554. case TGATools._TYPE_INDEXED:
  5555. use_pal = true;
  5556. break;
  5557. case TGATools._TYPE_RLE_RGB:
  5558. use_rle = true;
  5559. case TGATools._TYPE_RGB:
  5560. use_rgb = true;
  5561. break;
  5562. case TGATools._TYPE_RLE_GREY:
  5563. use_rle = true;
  5564. case TGATools._TYPE_GREY:
  5565. use_grey = true;
  5566. break;
  5567. }
  5568. var pixel_data;
  5569. var numAlphaBits = header.flags & 0xf;
  5570. var pixel_size = header.pixel_size >> 3;
  5571. var pixel_total = header.width * header.height * pixel_size;
  5572. // Read palettes
  5573. var palettes;
  5574. if (use_pal) {
  5575. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5576. }
  5577. // Read LRE
  5578. if (use_rle) {
  5579. pixel_data = new Uint8Array(pixel_total);
  5580. var c, count, i;
  5581. var localOffset = 0;
  5582. var pixels = new Uint8Array(pixel_size);
  5583. while (offset < pixel_total && localOffset < pixel_total) {
  5584. c = data[offset++];
  5585. count = (c & 0x7f) + 1;
  5586. // RLE pixels
  5587. if (c & 0x80) {
  5588. // Bind pixel tmp array
  5589. for (i = 0; i < pixel_size; ++i) {
  5590. pixels[i] = data[offset++];
  5591. }
  5592. // Copy pixel array
  5593. for (i = 0; i < count; ++i) {
  5594. pixel_data.set(pixels, localOffset + i * pixel_size);
  5595. }
  5596. localOffset += pixel_size * count;
  5597. }
  5598. else {
  5599. count *= pixel_size;
  5600. for (i = 0; i < count; ++i) {
  5601. pixel_data[localOffset + i] = data[offset++];
  5602. }
  5603. localOffset += count;
  5604. }
  5605. }
  5606. }
  5607. else {
  5608. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5609. }
  5610. // Load to texture
  5611. var x_start, y_start, x_step, y_step, y_end, x_end;
  5612. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5613. default:
  5614. case TGATools._ORIGIN_UL:
  5615. x_start = 0;
  5616. x_step = 1;
  5617. x_end = header.width;
  5618. y_start = 0;
  5619. y_step = 1;
  5620. y_end = header.height;
  5621. break;
  5622. case TGATools._ORIGIN_BL:
  5623. x_start = 0;
  5624. x_step = 1;
  5625. x_end = header.width;
  5626. y_start = header.height - 1;
  5627. y_step = -1;
  5628. y_end = -1;
  5629. break;
  5630. case TGATools._ORIGIN_UR:
  5631. x_start = header.width - 1;
  5632. x_step = -1;
  5633. x_end = -1;
  5634. y_start = 0;
  5635. y_step = 1;
  5636. y_end = header.height;
  5637. break;
  5638. case TGATools._ORIGIN_BR:
  5639. x_start = header.width - 1;
  5640. x_step = -1;
  5641. x_end = -1;
  5642. y_start = header.height - 1;
  5643. y_step = -1;
  5644. y_end = -1;
  5645. break;
  5646. }
  5647. // Load the specify method
  5648. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5649. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5650. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5651. };
  5652. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5653. var image = pixel_data, colormap = palettes;
  5654. var width = header.width, height = header.height;
  5655. var color, i = 0, x, y;
  5656. var imageData = new Uint8Array(width * height * 4);
  5657. for (y = y_start; y !== y_end; y += y_step) {
  5658. for (x = x_start; x !== x_end; x += x_step, i++) {
  5659. color = image[i];
  5660. imageData[(x + width * y) * 4 + 3] = 255;
  5661. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5662. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5663. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5664. }
  5665. }
  5666. return imageData;
  5667. };
  5668. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5669. var image = pixel_data;
  5670. var width = header.width, height = header.height;
  5671. var color, i = 0, x, y;
  5672. var imageData = new Uint8Array(width * height * 4);
  5673. for (y = y_start; y !== y_end; y += y_step) {
  5674. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5675. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5676. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5677. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5678. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5679. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5680. }
  5681. }
  5682. return imageData;
  5683. };
  5684. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5685. var image = pixel_data;
  5686. var width = header.width, height = header.height;
  5687. var i = 0, x, y;
  5688. var imageData = new Uint8Array(width * height * 4);
  5689. for (y = y_start; y !== y_end; y += y_step) {
  5690. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5691. imageData[(x + width * y) * 4 + 3] = 255;
  5692. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5693. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5694. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5695. }
  5696. }
  5697. return imageData;
  5698. };
  5699. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5700. var image = pixel_data;
  5701. var width = header.width, height = header.height;
  5702. var i = 0, x, y;
  5703. var imageData = new Uint8Array(width * height * 4);
  5704. for (y = y_start; y !== y_end; y += y_step) {
  5705. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5706. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5707. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5708. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5709. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5710. }
  5711. }
  5712. return imageData;
  5713. };
  5714. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5715. var image = pixel_data;
  5716. var width = header.width, height = header.height;
  5717. var color, i = 0, x, y;
  5718. var imageData = new Uint8Array(width * height * 4);
  5719. for (y = y_start; y !== y_end; y += y_step) {
  5720. for (x = x_start; x !== x_end; x += x_step, i++) {
  5721. color = image[i];
  5722. imageData[(x + width * y) * 4 + 0] = color;
  5723. imageData[(x + width * y) * 4 + 1] = color;
  5724. imageData[(x + width * y) * 4 + 2] = color;
  5725. imageData[(x + width * y) * 4 + 3] = 255;
  5726. }
  5727. }
  5728. return imageData;
  5729. };
  5730. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5731. var image = pixel_data;
  5732. var width = header.width, height = header.height;
  5733. var i = 0, x, y;
  5734. var imageData = new Uint8Array(width * height * 4);
  5735. for (y = y_start; y !== y_end; y += y_step) {
  5736. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5737. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5738. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5739. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5740. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5741. }
  5742. }
  5743. return imageData;
  5744. };
  5745. return TGATools;
  5746. }());
  5747. TGATools._TYPE_NO_DATA = 0;
  5748. TGATools._TYPE_INDEXED = 1;
  5749. TGATools._TYPE_RGB = 2;
  5750. TGATools._TYPE_GREY = 3;
  5751. TGATools._TYPE_RLE_INDEXED = 9;
  5752. TGATools._TYPE_RLE_RGB = 10;
  5753. TGATools._TYPE_RLE_GREY = 11;
  5754. TGATools._ORIGIN_MASK = 0x30;
  5755. TGATools._ORIGIN_SHIFT = 0x04;
  5756. TGATools._ORIGIN_BL = 0x00;
  5757. TGATools._ORIGIN_BR = 0x01;
  5758. TGATools._ORIGIN_UL = 0x02;
  5759. TGATools._ORIGIN_UR = 0x03;
  5760. Internals.TGATools = TGATools;
  5761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5762. })(BABYLON || (BABYLON = {}));
  5763. //# sourceMappingURL=babylon.tools.tga.js.map
  5764. var BABYLON;
  5765. (function (BABYLON) {
  5766. var SmartArray = (function () {
  5767. function SmartArray(capacity) {
  5768. this.length = 0;
  5769. this._duplicateId = 0;
  5770. this.data = new Array(capacity);
  5771. this._id = SmartArray._GlobalId++;
  5772. }
  5773. SmartArray.prototype.push = function (value) {
  5774. this.data[this.length++] = value;
  5775. if (this.length > this.data.length) {
  5776. this.data.length *= 2;
  5777. }
  5778. if (!value.__smartArrayFlags) {
  5779. value.__smartArrayFlags = {};
  5780. }
  5781. value.__smartArrayFlags[this._id] = this._duplicateId;
  5782. };
  5783. SmartArray.prototype.forEach = function (func) {
  5784. for (var index = 0; index < this.length; index++) {
  5785. func(this.data[index]);
  5786. }
  5787. };
  5788. SmartArray.prototype.pushNoDuplicate = function (value) {
  5789. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5790. return false;
  5791. }
  5792. this.push(value);
  5793. return true;
  5794. };
  5795. SmartArray.prototype.sort = function (compareFn) {
  5796. this.data.sort(compareFn);
  5797. };
  5798. SmartArray.prototype.reset = function () {
  5799. this.length = 0;
  5800. this._duplicateId++;
  5801. };
  5802. SmartArray.prototype.dispose = function () {
  5803. this.reset();
  5804. this.data.length = 0;
  5805. };
  5806. SmartArray.prototype.concat = function (array) {
  5807. if (array.length === 0) {
  5808. return;
  5809. }
  5810. if (this.length + array.length > this.data.length) {
  5811. this.data.length = (this.length + array.length) * 2;
  5812. }
  5813. for (var index = 0; index < array.length; index++) {
  5814. this.data[this.length++] = (array.data || array)[index];
  5815. }
  5816. };
  5817. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5818. if (array.length === 0) {
  5819. return;
  5820. }
  5821. if (this.length + array.length > this.data.length) {
  5822. this.data.length = (this.length + array.length) * 2;
  5823. }
  5824. for (var index = 0; index < array.length; index++) {
  5825. var item = (array.data || array)[index];
  5826. this.pushNoDuplicate(item);
  5827. }
  5828. };
  5829. SmartArray.prototype.indexOf = function (value) {
  5830. var position = this.data.indexOf(value);
  5831. if (position >= this.length) {
  5832. return -1;
  5833. }
  5834. return position;
  5835. };
  5836. return SmartArray;
  5837. }());
  5838. // Statics
  5839. SmartArray._GlobalId = 0;
  5840. BABYLON.SmartArray = SmartArray;
  5841. })(BABYLON || (BABYLON = {}));
  5842. //# sourceMappingURL=babylon.smartArray.js.map
  5843. var BABYLON;
  5844. (function (BABYLON) {
  5845. /**
  5846. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5847. * The underlying implementation relies on an associative array to ensure the best performances.
  5848. * The value can be anything including 'null' but except 'undefined'
  5849. */
  5850. var StringDictionary = (function () {
  5851. function StringDictionary() {
  5852. this._count = 0;
  5853. this._data = {};
  5854. }
  5855. /**
  5856. * This will clear this dictionary and copy the content from the 'source' one.
  5857. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5858. * @param source the dictionary to take the content from and copy to this dictionary
  5859. */
  5860. StringDictionary.prototype.copyFrom = function (source) {
  5861. var _this = this;
  5862. this.clear();
  5863. source.forEach(function (t, v) { return _this.add(t, v); });
  5864. };
  5865. /**
  5866. * Get a value based from its key
  5867. * @param key the given key to get the matching value from
  5868. * @return the value if found, otherwise undefined is returned
  5869. */
  5870. StringDictionary.prototype.get = function (key) {
  5871. var val = this._data[key];
  5872. if (val !== undefined) {
  5873. return val;
  5874. }
  5875. return undefined;
  5876. };
  5877. /**
  5878. * Get a value from its key or add it if it doesn't exist.
  5879. * This method will ensure you that a given key/data will be present in the dictionary.
  5880. * @param key the given key to get the matching value from
  5881. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5882. * The factory will only be invoked if there's no data for the given key.
  5883. * @return the value corresponding to the key.
  5884. */
  5885. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5886. var val = this.get(key);
  5887. if (val !== undefined) {
  5888. return val;
  5889. }
  5890. val = factory(key);
  5891. if (val) {
  5892. this.add(key, val);
  5893. }
  5894. return val;
  5895. };
  5896. /**
  5897. * Get a value from its key if present in the dictionary otherwise add it
  5898. * @param key the key to get the value from
  5899. * @param val if there's no such key/value pair in the dictionary add it with this value
  5900. * @return the value corresponding to the key
  5901. */
  5902. StringDictionary.prototype.getOrAdd = function (key, val) {
  5903. var curVal = this.get(key);
  5904. if (curVal !== undefined) {
  5905. return curVal;
  5906. }
  5907. this.add(key, val);
  5908. return val;
  5909. };
  5910. /**
  5911. * Check if there's a given key in the dictionary
  5912. * @param key the key to check for
  5913. * @return true if the key is present, false otherwise
  5914. */
  5915. StringDictionary.prototype.contains = function (key) {
  5916. return this._data[key] !== undefined;
  5917. };
  5918. /**
  5919. * Add a new key and its corresponding value
  5920. * @param key the key to add
  5921. * @param value the value corresponding to the key
  5922. * @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
  5923. */
  5924. StringDictionary.prototype.add = function (key, value) {
  5925. if (this._data[key] !== undefined) {
  5926. return false;
  5927. }
  5928. this._data[key] = value;
  5929. ++this._count;
  5930. return true;
  5931. };
  5932. StringDictionary.prototype.set = function (key, value) {
  5933. if (this._data[key] === undefined) {
  5934. return false;
  5935. }
  5936. this._data[key] = value;
  5937. return true;
  5938. };
  5939. /**
  5940. * Get the element of the given key and remove it from the dictionary
  5941. * @param key
  5942. */
  5943. StringDictionary.prototype.getAndRemove = function (key) {
  5944. var val = this.get(key);
  5945. if (val !== undefined) {
  5946. delete this._data[key];
  5947. --this._count;
  5948. return val;
  5949. }
  5950. return null;
  5951. };
  5952. /**
  5953. * Remove a key/value from the dictionary.
  5954. * @param key the key to remove
  5955. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5956. */
  5957. StringDictionary.prototype.remove = function (key) {
  5958. if (this.contains(key)) {
  5959. delete this._data[key];
  5960. --this._count;
  5961. return true;
  5962. }
  5963. return false;
  5964. };
  5965. /**
  5966. * Clear the whole content of the dictionary
  5967. */
  5968. StringDictionary.prototype.clear = function () {
  5969. this._data = {};
  5970. this._count = 0;
  5971. };
  5972. Object.defineProperty(StringDictionary.prototype, "count", {
  5973. get: function () {
  5974. return this._count;
  5975. },
  5976. enumerable: true,
  5977. configurable: true
  5978. });
  5979. /**
  5980. * Execute a callback on each key/val of the dictionary.
  5981. * Note that you can remove any element in this dictionary in the callback implementation
  5982. * @param callback the callback to execute on a given key/value pair
  5983. */
  5984. StringDictionary.prototype.forEach = function (callback) {
  5985. for (var cur in this._data) {
  5986. var val = this._data[cur];
  5987. callback(cur, val);
  5988. }
  5989. };
  5990. /**
  5991. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5992. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5993. * Note that you can remove any element in this dictionary in the callback implementation
  5994. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5995. */
  5996. StringDictionary.prototype.first = function (callback) {
  5997. for (var cur in this._data) {
  5998. var val = this._data[cur];
  5999. var res = callback(cur, val);
  6000. if (res) {
  6001. return res;
  6002. }
  6003. }
  6004. return null;
  6005. };
  6006. return StringDictionary;
  6007. }());
  6008. BABYLON.StringDictionary = StringDictionary;
  6009. })(BABYLON || (BABYLON = {}));
  6010. //# sourceMappingURL=babylon.stringDictionary.js.map
  6011. var BABYLON;
  6012. (function (BABYLON) {
  6013. // Screenshots
  6014. var screenshotCanvas;
  6015. var cloneValue = function (source, destinationObject) {
  6016. if (!source)
  6017. return null;
  6018. if (source instanceof BABYLON.Mesh) {
  6019. return null;
  6020. }
  6021. if (source instanceof BABYLON.SubMesh) {
  6022. return source.clone(destinationObject);
  6023. }
  6024. else if (source.clone) {
  6025. return source.clone();
  6026. }
  6027. return null;
  6028. };
  6029. var Tools = (function () {
  6030. function Tools() {
  6031. }
  6032. ;
  6033. Tools.Instantiate = function (className) {
  6034. var arr = className.split(".");
  6035. var fn = (window || this);
  6036. for (var i = 0, len = arr.length; i < len; i++) {
  6037. fn = fn[arr[i]];
  6038. }
  6039. if (typeof fn !== "function") {
  6040. return null;
  6041. }
  6042. return fn;
  6043. };
  6044. Tools.SetImmediate = function (action) {
  6045. if (window.setImmediate) {
  6046. window.setImmediate(action);
  6047. }
  6048. else {
  6049. setTimeout(action, 1);
  6050. }
  6051. };
  6052. Tools.IsExponentOfTwo = function (value) {
  6053. var count = 1;
  6054. do {
  6055. count *= 2;
  6056. } while (count < value);
  6057. return count === value;
  6058. };
  6059. Tools.GetExponentOfTwo = function (value, max) {
  6060. var count = 1;
  6061. do {
  6062. count *= 2;
  6063. } while (count < value);
  6064. if (count > max)
  6065. count = max;
  6066. return count;
  6067. };
  6068. Tools.GetFilename = function (path) {
  6069. var index = path.lastIndexOf("/");
  6070. if (index < 0)
  6071. return path;
  6072. return path.substring(index + 1);
  6073. };
  6074. Tools.GetDOMTextContent = function (element) {
  6075. var result = "";
  6076. var child = element.firstChild;
  6077. while (child) {
  6078. if (child.nodeType === 3) {
  6079. result += child.textContent;
  6080. }
  6081. child = child.nextSibling;
  6082. }
  6083. return result;
  6084. };
  6085. Tools.ToDegrees = function (angle) {
  6086. return angle * 180 / Math.PI;
  6087. };
  6088. Tools.ToRadians = function (angle) {
  6089. return angle * Math.PI / 180;
  6090. };
  6091. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6092. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6093. var output = "";
  6094. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6095. var i = 0;
  6096. var bytes = new Uint8Array(buffer);
  6097. while (i < bytes.length) {
  6098. chr1 = bytes[i++];
  6099. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6100. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6101. enc1 = chr1 >> 2;
  6102. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6103. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6104. enc4 = chr3 & 63;
  6105. if (isNaN(chr2)) {
  6106. enc3 = enc4 = 64;
  6107. }
  6108. else if (isNaN(chr3)) {
  6109. enc4 = 64;
  6110. }
  6111. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6112. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6113. }
  6114. return "data:image/png;base64," + output;
  6115. };
  6116. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6117. if (bias === void 0) { bias = null; }
  6118. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6119. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6120. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6121. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6122. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6123. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6124. }
  6125. if (bias) {
  6126. minimum.x -= minimum.x * bias.x + bias.y;
  6127. minimum.y -= minimum.y * bias.x + bias.y;
  6128. minimum.z -= minimum.z * bias.x + bias.y;
  6129. maximum.x += maximum.x * bias.x + bias.y;
  6130. maximum.y += maximum.y * bias.x + bias.y;
  6131. maximum.z += maximum.z * bias.x + bias.y;
  6132. }
  6133. return {
  6134. minimum: minimum,
  6135. maximum: maximum
  6136. };
  6137. };
  6138. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6139. if (bias === void 0) { bias = null; }
  6140. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6141. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6142. if (!stride) {
  6143. stride = 3;
  6144. }
  6145. for (var index = start; index < start + count; index++) {
  6146. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6147. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6148. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6149. }
  6150. if (bias) {
  6151. minimum.x -= minimum.x * bias.x + bias.y;
  6152. minimum.y -= minimum.y * bias.x + bias.y;
  6153. minimum.z -= minimum.z * bias.x + bias.y;
  6154. maximum.x += maximum.x * bias.x + bias.y;
  6155. maximum.y += maximum.y * bias.x + bias.y;
  6156. maximum.z += maximum.z * bias.x + bias.y;
  6157. }
  6158. return {
  6159. minimum: minimum,
  6160. maximum: maximum
  6161. };
  6162. };
  6163. Tools.Vector2ArrayFeeder = function (array) {
  6164. return function (index) {
  6165. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6166. var length = isFloatArray ? array.length / 2 : array.length;
  6167. if (index >= length) {
  6168. return null;
  6169. }
  6170. if (isFloatArray) {
  6171. var fa = array;
  6172. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6173. }
  6174. var a = array;
  6175. return a[index];
  6176. };
  6177. };
  6178. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6179. if (bias === void 0) { bias = null; }
  6180. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6181. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6182. var i = 0;
  6183. var cur = feeder(i++);
  6184. while (cur) {
  6185. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6186. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6187. cur = feeder(i++);
  6188. }
  6189. if (bias) {
  6190. minimum.x -= minimum.x * bias.x + bias.y;
  6191. minimum.y -= minimum.y * bias.x + bias.y;
  6192. maximum.x += maximum.x * bias.x + bias.y;
  6193. maximum.y += maximum.y * bias.x + bias.y;
  6194. }
  6195. return {
  6196. minimum: minimum,
  6197. maximum: maximum
  6198. };
  6199. };
  6200. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6201. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6202. return undefined;
  6203. return Array.isArray(obj) ? obj : [obj];
  6204. };
  6205. // Misc.
  6206. Tools.GetPointerPrefix = function () {
  6207. var eventPrefix = "pointer";
  6208. // Check if pointer events are supported
  6209. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6210. eventPrefix = "mouse";
  6211. }
  6212. return eventPrefix;
  6213. };
  6214. /**
  6215. * @param func - the function to be called
  6216. * @param requester - the object that will request the next frame. Falls back to window.
  6217. */
  6218. Tools.QueueNewFrame = function (func, requester) {
  6219. if (requester === void 0) { requester = window; }
  6220. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6221. /*if(requester.isPresenting) {
  6222. return;
  6223. } else*/ if (requester.requestAnimationFrame)
  6224. requester.requestAnimationFrame(func);
  6225. else if (requester.msRequestAnimationFrame)
  6226. requester.msRequestAnimationFrame(func);
  6227. else if (requester.webkitRequestAnimationFrame)
  6228. requester.webkitRequestAnimationFrame(func);
  6229. else if (requester.mozRequestAnimationFrame)
  6230. requester.mozRequestAnimationFrame(func);
  6231. else if (requester.oRequestAnimationFrame)
  6232. requester.oRequestAnimationFrame(func);
  6233. else {
  6234. window.setTimeout(func, 16);
  6235. }
  6236. };
  6237. Tools.RequestFullscreen = function (element) {
  6238. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6239. if (!requestFunction)
  6240. return;
  6241. requestFunction.call(element);
  6242. };
  6243. Tools.ExitFullscreen = function () {
  6244. if (document.exitFullscreen) {
  6245. document.exitFullscreen();
  6246. }
  6247. else if (document.mozCancelFullScreen) {
  6248. document.mozCancelFullScreen();
  6249. }
  6250. else if (document.webkitCancelFullScreen) {
  6251. document.webkitCancelFullScreen();
  6252. }
  6253. else if (document.msCancelFullScreen) {
  6254. document.msCancelFullScreen();
  6255. }
  6256. };
  6257. Tools.SetCorsBehavior = function (url, img) {
  6258. if (Tools.CorsBehavior) {
  6259. switch (typeof (Tools.CorsBehavior)) {
  6260. case "function":
  6261. var result = Tools.CorsBehavior(url);
  6262. if (result) {
  6263. img.crossOrigin = result;
  6264. }
  6265. break;
  6266. case "string":
  6267. default:
  6268. img.crossOrigin = Tools.CorsBehavior;
  6269. break;
  6270. }
  6271. }
  6272. };
  6273. // External files
  6274. Tools.CleanUrl = function (url) {
  6275. url = url.replace(/#/mg, "%23");
  6276. return url;
  6277. };
  6278. Tools.LoadImage = function (url, onload, onerror, database) {
  6279. if (url instanceof ArrayBuffer) {
  6280. url = Tools.EncodeArrayBufferTobase64(url);
  6281. }
  6282. url = Tools.CleanUrl(url);
  6283. var img = new Image();
  6284. if (url.substr(0, 5) !== "data:") {
  6285. Tools.SetCorsBehavior(url, img);
  6286. }
  6287. img.onload = function () {
  6288. onload(img);
  6289. };
  6290. img.onerror = function (err) {
  6291. Tools.Error("Error while trying to load image: " + url);
  6292. if (Tools.UseFallbackTexture) {
  6293. img.src = Tools.fallbackTexture;
  6294. onload(img);
  6295. }
  6296. else {
  6297. onerror();
  6298. }
  6299. };
  6300. var noIndexedDB = function () {
  6301. img.src = url;
  6302. };
  6303. var loadFromIndexedDB = function () {
  6304. database.loadImageFromDB(url, img);
  6305. };
  6306. //ANY database to do!
  6307. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6308. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6309. }
  6310. else {
  6311. if (url.indexOf("file:") === -1) {
  6312. noIndexedDB();
  6313. }
  6314. else {
  6315. var textureName = url.substring(5).toLowerCase();
  6316. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6317. try {
  6318. var blobURL;
  6319. try {
  6320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6321. }
  6322. catch (ex) {
  6323. // Chrome doesn't support oneTimeOnly parameter
  6324. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6325. }
  6326. img.src = blobURL;
  6327. }
  6328. catch (e) {
  6329. img.src = null;
  6330. }
  6331. }
  6332. else {
  6333. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6334. img.src = Tools.fallbackTexture;
  6335. }
  6336. }
  6337. }
  6338. return img;
  6339. };
  6340. //ANY
  6341. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6342. url = Tools.CleanUrl(url);
  6343. var noIndexedDB = function () {
  6344. var request = new XMLHttpRequest();
  6345. var loadUrl = Tools.BaseUrl + url;
  6346. request.open('GET', loadUrl, true);
  6347. if (useArrayBuffer) {
  6348. request.responseType = "arraybuffer";
  6349. }
  6350. request.onprogress = progressCallBack;
  6351. request.onreadystatechange = function () {
  6352. if (request.readyState === 4) {
  6353. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6354. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6355. callback(!useArrayBuffer ? request.responseText : request.response);
  6356. }
  6357. else {
  6358. if (onError) {
  6359. onError();
  6360. }
  6361. else {
  6362. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6363. }
  6364. }
  6365. }
  6366. };
  6367. request.send(null);
  6368. };
  6369. var loadFromIndexedDB = function () {
  6370. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6371. };
  6372. if (url.indexOf("file:") !== -1) {
  6373. var fileName = url.substring(5).toLowerCase();
  6374. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6375. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6376. }
  6377. else {
  6378. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6379. }
  6380. }
  6381. else {
  6382. // Caching all files
  6383. if (database && database.enableSceneOffline) {
  6384. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6385. }
  6386. else {
  6387. noIndexedDB();
  6388. }
  6389. }
  6390. };
  6391. /**
  6392. * Load a script (identified by an url). When the url returns, the
  6393. * content of this file is added into a new script element, attached to the DOM (body element)
  6394. */
  6395. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6396. var head = document.getElementsByTagName('head')[0];
  6397. var script = document.createElement('script');
  6398. script.type = 'text/javascript';
  6399. script.src = scriptUrl;
  6400. var self = this;
  6401. script.onload = function () {
  6402. if (onSuccess) {
  6403. onSuccess();
  6404. }
  6405. };
  6406. script.onerror = function () {
  6407. if (onError) {
  6408. onError();
  6409. }
  6410. };
  6411. head.appendChild(script);
  6412. };
  6413. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6414. var reader = new FileReader();
  6415. reader.onload = function (e) {
  6416. //target doesn't have result from ts 1.3
  6417. callback(e.target['result']);
  6418. };
  6419. reader.onprogress = progressCallback;
  6420. reader.readAsDataURL(fileToLoad);
  6421. };
  6422. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6423. var reader = new FileReader();
  6424. reader.onerror = function (e) {
  6425. Tools.Log("Error while reading file: " + fileToLoad.name);
  6426. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6427. };
  6428. reader.onload = function (e) {
  6429. //target doesn't have result from ts 1.3
  6430. callback(e.target['result']);
  6431. };
  6432. reader.onprogress = progressCallBack;
  6433. if (!useArrayBuffer) {
  6434. // Asynchronous read
  6435. reader.readAsText(fileToLoad);
  6436. }
  6437. else {
  6438. reader.readAsArrayBuffer(fileToLoad);
  6439. }
  6440. };
  6441. //returns a downloadable url to a file content.
  6442. Tools.FileAsURL = function (content) {
  6443. var fileBlob = new Blob([content]);
  6444. var url = window.URL || window.webkitURL;
  6445. var link = url.createObjectURL(fileBlob);
  6446. return link;
  6447. };
  6448. // Misc.
  6449. Tools.Format = function (value, decimals) {
  6450. if (decimals === void 0) { decimals = 2; }
  6451. return value.toFixed(decimals);
  6452. };
  6453. Tools.CheckExtends = function (v, min, max) {
  6454. if (v.x < min.x)
  6455. min.x = v.x;
  6456. if (v.y < min.y)
  6457. min.y = v.y;
  6458. if (v.z < min.z)
  6459. min.z = v.z;
  6460. if (v.x > max.x)
  6461. max.x = v.x;
  6462. if (v.y > max.y)
  6463. max.y = v.y;
  6464. if (v.z > max.z)
  6465. max.z = v.z;
  6466. };
  6467. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6468. for (var prop in source) {
  6469. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6470. continue;
  6471. }
  6472. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6473. continue;
  6474. }
  6475. var sourceValue = source[prop];
  6476. var typeOfSourceValue = typeof sourceValue;
  6477. if (typeOfSourceValue === "function") {
  6478. continue;
  6479. }
  6480. if (typeOfSourceValue === "object") {
  6481. if (sourceValue instanceof Array) {
  6482. destination[prop] = [];
  6483. if (sourceValue.length > 0) {
  6484. if (typeof sourceValue[0] == "object") {
  6485. for (var index = 0; index < sourceValue.length; index++) {
  6486. var clonedValue = cloneValue(sourceValue[index], destination);
  6487. if (destination[prop].indexOf(clonedValue) === -1) {
  6488. destination[prop].push(clonedValue);
  6489. }
  6490. }
  6491. }
  6492. else {
  6493. destination[prop] = sourceValue.slice(0);
  6494. }
  6495. }
  6496. }
  6497. else {
  6498. destination[prop] = cloneValue(sourceValue, destination);
  6499. }
  6500. }
  6501. else {
  6502. destination[prop] = sourceValue;
  6503. }
  6504. }
  6505. };
  6506. Tools.IsEmpty = function (obj) {
  6507. for (var i in obj) {
  6508. return false;
  6509. }
  6510. return true;
  6511. };
  6512. Tools.RegisterTopRootEvents = function (events) {
  6513. for (var index = 0; index < events.length; index++) {
  6514. var event = events[index];
  6515. window.addEventListener(event.name, event.handler, false);
  6516. try {
  6517. if (window.parent) {
  6518. window.parent.addEventListener(event.name, event.handler, false);
  6519. }
  6520. }
  6521. catch (e) {
  6522. // Silently fails...
  6523. }
  6524. }
  6525. };
  6526. Tools.UnregisterTopRootEvents = function (events) {
  6527. for (var index = 0; index < events.length; index++) {
  6528. var event = events[index];
  6529. window.removeEventListener(event.name, event.handler);
  6530. try {
  6531. if (window.parent) {
  6532. window.parent.removeEventListener(event.name, event.handler);
  6533. }
  6534. }
  6535. catch (e) {
  6536. // Silently fails...
  6537. }
  6538. }
  6539. };
  6540. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6541. if (mimeType === void 0) { mimeType = "image/png"; }
  6542. // Read the contents of the framebuffer
  6543. var numberOfChannelsByLine = width * 4;
  6544. var halfHeight = height / 2;
  6545. //Reading datas from WebGL
  6546. var data = engine.readPixels(0, 0, width, height);
  6547. //To flip image on Y axis.
  6548. for (var i = 0; i < halfHeight; i++) {
  6549. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6550. var currentCell = j + i * numberOfChannelsByLine;
  6551. var targetLine = height - i - 1;
  6552. var targetCell = j + targetLine * numberOfChannelsByLine;
  6553. var temp = data[currentCell];
  6554. data[currentCell] = data[targetCell];
  6555. data[targetCell] = temp;
  6556. }
  6557. }
  6558. // Create a 2D canvas to store the result
  6559. if (!screenshotCanvas) {
  6560. screenshotCanvas = document.createElement('canvas');
  6561. }
  6562. screenshotCanvas.width = width;
  6563. screenshotCanvas.height = height;
  6564. var context = screenshotCanvas.getContext('2d');
  6565. // Copy the pixels to a 2D canvas
  6566. var imageData = context.createImageData(width, height);
  6567. var castData = (imageData.data);
  6568. castData.set(data);
  6569. context.putImageData(imageData, 0, 0);
  6570. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6571. };
  6572. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6573. if (mimeType === void 0) { mimeType = "image/png"; }
  6574. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6575. if (successCallback) {
  6576. successCallback(base64Image);
  6577. }
  6578. else {
  6579. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6580. if (("download" in document.createElement("a"))) {
  6581. var a = window.document.createElement("a");
  6582. a.href = base64Image;
  6583. var date = new Date();
  6584. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6585. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6586. window.document.body.appendChild(a);
  6587. a.addEventListener("click", function () {
  6588. a.parentElement.removeChild(a);
  6589. });
  6590. a.click();
  6591. //Or opening a new tab with the image if it is not possible to automatically start download.
  6592. }
  6593. else {
  6594. var newWindow = window.open("");
  6595. var img = newWindow.document.createElement("img");
  6596. img.src = base64Image;
  6597. newWindow.document.body.appendChild(img);
  6598. }
  6599. }
  6600. };
  6601. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6602. if (mimeType === void 0) { mimeType = "image/png"; }
  6603. var width;
  6604. var height;
  6605. // If a precision value is specified
  6606. if (size.precision) {
  6607. width = Math.round(engine.getRenderWidth() * size.precision);
  6608. height = Math.round(width / engine.getAspectRatio(camera));
  6609. }
  6610. else if (size.width && size.height) {
  6611. width = size.width;
  6612. height = size.height;
  6613. }
  6614. else if (size.width && !size.height) {
  6615. width = size.width;
  6616. height = Math.round(width / engine.getAspectRatio(camera));
  6617. }
  6618. else if (size.height && !size.width) {
  6619. height = size.height;
  6620. width = Math.round(height * engine.getAspectRatio(camera));
  6621. }
  6622. else if (!isNaN(size)) {
  6623. height = size;
  6624. width = size;
  6625. }
  6626. else {
  6627. Tools.Error("Invalid 'size' parameter !");
  6628. return;
  6629. }
  6630. if (!screenshotCanvas) {
  6631. screenshotCanvas = document.createElement('canvas');
  6632. }
  6633. screenshotCanvas.width = width;
  6634. screenshotCanvas.height = height;
  6635. var renderContext = screenshotCanvas.getContext("2d");
  6636. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6637. var newWidth = width;
  6638. var newHeight = newWidth / ratio;
  6639. if (newHeight > height) {
  6640. newHeight = height;
  6641. newWidth = newHeight * ratio;
  6642. }
  6643. var offsetX = Math.max(0, width - newWidth) / 2;
  6644. var offsetY = Math.max(0, height - newHeight) / 2;
  6645. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6646. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6647. };
  6648. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6649. if (mimeType === void 0) { mimeType = "image/png"; }
  6650. if (samples === void 0) { samples = 1; }
  6651. var width;
  6652. var height;
  6653. //If a precision value is specified
  6654. if (size.precision) {
  6655. width = Math.round(engine.getRenderWidth() * size.precision);
  6656. height = Math.round(width / engine.getAspectRatio(camera));
  6657. size = { width: width, height: height };
  6658. }
  6659. else if (size.width && size.height) {
  6660. width = size.width;
  6661. height = size.height;
  6662. }
  6663. else if (size.width && !size.height) {
  6664. width = size.width;
  6665. height = Math.round(width / engine.getAspectRatio(camera));
  6666. size = { width: width, height: height };
  6667. }
  6668. else if (size.height && !size.width) {
  6669. height = size.height;
  6670. width = Math.round(height * engine.getAspectRatio(camera));
  6671. size = { width: width, height: height };
  6672. }
  6673. else if (!isNaN(size)) {
  6674. height = size;
  6675. width = size;
  6676. }
  6677. else {
  6678. Tools.Error("Invalid 'size' parameter !");
  6679. return;
  6680. }
  6681. var scene = camera.getScene();
  6682. var previousCamera = null;
  6683. if (scene.activeCamera !== camera) {
  6684. previousCamera = scene.activeCamera;
  6685. scene.activeCamera = camera;
  6686. }
  6687. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6688. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6689. texture.renderList = scene.meshes;
  6690. texture.samples = samples;
  6691. texture.onAfterRenderObservable.add(function () {
  6692. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6693. });
  6694. scene.incrementRenderId();
  6695. scene.resetCachedMaterial();
  6696. texture.render(true);
  6697. texture.dispose();
  6698. if (previousCamera) {
  6699. scene.activeCamera = previousCamera;
  6700. }
  6701. camera.getProjectionMatrix(true); // Force cache refresh;
  6702. };
  6703. // XHR response validator for local file scenario
  6704. Tools.ValidateXHRData = function (xhr, dataType) {
  6705. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6706. if (dataType === void 0) { dataType = 7; }
  6707. try {
  6708. if (dataType & 1) {
  6709. if (xhr.responseText && xhr.responseText.length > 0) {
  6710. return true;
  6711. }
  6712. else if (dataType === 1) {
  6713. return false;
  6714. }
  6715. }
  6716. if (dataType & 2) {
  6717. // Check header width and height since there is no "TGA" magic number
  6718. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6719. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6720. return true;
  6721. }
  6722. else if (dataType === 2) {
  6723. return false;
  6724. }
  6725. }
  6726. if (dataType & 4) {
  6727. // Check for the "DDS" magic number
  6728. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6729. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6730. return true;
  6731. }
  6732. else {
  6733. return false;
  6734. }
  6735. }
  6736. }
  6737. catch (e) {
  6738. // Global protection
  6739. }
  6740. return false;
  6741. };
  6742. /**
  6743. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6744. * Be aware Math.random() could cause collisions, but:
  6745. * "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"
  6746. */
  6747. Tools.RandomId = function () {
  6748. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6749. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6750. return v.toString(16);
  6751. });
  6752. };
  6753. Object.defineProperty(Tools, "NoneLogLevel", {
  6754. get: function () {
  6755. return Tools._NoneLogLevel;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(Tools, "MessageLogLevel", {
  6761. get: function () {
  6762. return Tools._MessageLogLevel;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(Tools, "WarningLogLevel", {
  6768. get: function () {
  6769. return Tools._WarningLogLevel;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(Tools, "ErrorLogLevel", {
  6775. get: function () {
  6776. return Tools._ErrorLogLevel;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(Tools, "AllLogLevel", {
  6782. get: function () {
  6783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Tools._AddLogEntry = function (entry) {
  6789. Tools._LogCache = entry + Tools._LogCache;
  6790. if (Tools.OnNewCacheEntry) {
  6791. Tools.OnNewCacheEntry(entry);
  6792. }
  6793. };
  6794. Tools._FormatMessage = function (message) {
  6795. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6796. var date = new Date();
  6797. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6798. };
  6799. Tools._LogDisabled = function (message) {
  6800. // nothing to do
  6801. };
  6802. Tools._LogEnabled = function (message) {
  6803. var formattedMessage = Tools._FormatMessage(message);
  6804. console.log("BJS - " + formattedMessage);
  6805. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6806. Tools._AddLogEntry(entry);
  6807. };
  6808. Tools._WarnDisabled = function (message) {
  6809. // nothing to do
  6810. };
  6811. Tools._WarnEnabled = function (message) {
  6812. var formattedMessage = Tools._FormatMessage(message);
  6813. console.warn("BJS - " + formattedMessage);
  6814. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6815. Tools._AddLogEntry(entry);
  6816. };
  6817. Tools._ErrorDisabled = function (message) {
  6818. // nothing to do
  6819. };
  6820. Tools._ErrorEnabled = function (message) {
  6821. Tools.errorsCount++;
  6822. var formattedMessage = Tools._FormatMessage(message);
  6823. console.error("BJS - " + formattedMessage);
  6824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6825. Tools._AddLogEntry(entry);
  6826. };
  6827. Object.defineProperty(Tools, "LogCache", {
  6828. get: function () {
  6829. return Tools._LogCache;
  6830. },
  6831. enumerable: true,
  6832. configurable: true
  6833. });
  6834. Tools.ClearLogCache = function () {
  6835. Tools._LogCache = "";
  6836. Tools.errorsCount = 0;
  6837. };
  6838. Object.defineProperty(Tools, "LogLevels", {
  6839. set: function (level) {
  6840. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6841. Tools.Log = Tools._LogEnabled;
  6842. }
  6843. else {
  6844. Tools.Log = Tools._LogDisabled;
  6845. }
  6846. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6847. Tools.Warn = Tools._WarnEnabled;
  6848. }
  6849. else {
  6850. Tools.Warn = Tools._WarnDisabled;
  6851. }
  6852. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6853. Tools.Error = Tools._ErrorEnabled;
  6854. }
  6855. else {
  6856. Tools.Error = Tools._ErrorDisabled;
  6857. }
  6858. },
  6859. enumerable: true,
  6860. configurable: true
  6861. });
  6862. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6863. get: function () {
  6864. return Tools._PerformanceNoneLogLevel;
  6865. },
  6866. enumerable: true,
  6867. configurable: true
  6868. });
  6869. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6870. get: function () {
  6871. return Tools._PerformanceUserMarkLogLevel;
  6872. },
  6873. enumerable: true,
  6874. configurable: true
  6875. });
  6876. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6877. get: function () {
  6878. return Tools._PerformanceConsoleLogLevel;
  6879. },
  6880. enumerable: true,
  6881. configurable: true
  6882. });
  6883. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6884. set: function (level) {
  6885. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6886. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6887. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6888. return;
  6889. }
  6890. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6891. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6892. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6893. return;
  6894. }
  6895. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6896. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6902. };
  6903. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6904. };
  6905. Tools._StartUserMark = function (counterName, condition) {
  6906. if (condition === void 0) { condition = true; }
  6907. if (!condition || !Tools._performance.mark) {
  6908. return;
  6909. }
  6910. Tools._performance.mark(counterName + "-Begin");
  6911. };
  6912. Tools._EndUserMark = function (counterName, condition) {
  6913. if (condition === void 0) { condition = true; }
  6914. if (!condition || !Tools._performance.mark) {
  6915. return;
  6916. }
  6917. Tools._performance.mark(counterName + "-End");
  6918. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6919. };
  6920. Tools._StartPerformanceConsole = function (counterName, condition) {
  6921. if (condition === void 0) { condition = true; }
  6922. if (!condition) {
  6923. return;
  6924. }
  6925. Tools._StartUserMark(counterName, condition);
  6926. if (console.time) {
  6927. console.time(counterName);
  6928. }
  6929. };
  6930. Tools._EndPerformanceConsole = function (counterName, condition) {
  6931. if (condition === void 0) { condition = true; }
  6932. if (!condition) {
  6933. return;
  6934. }
  6935. Tools._EndUserMark(counterName, condition);
  6936. if (console.time) {
  6937. console.timeEnd(counterName);
  6938. }
  6939. };
  6940. Object.defineProperty(Tools, "Now", {
  6941. get: function () {
  6942. if (window.performance && window.performance.now) {
  6943. return window.performance.now();
  6944. }
  6945. return new Date().getTime();
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. /**
  6951. * This method will return the name of the class used to create the instance of the given object.
  6952. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6953. * @param object the object to get the class name from
  6954. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6955. */
  6956. Tools.getClassName = function (object, isType) {
  6957. if (isType === void 0) { isType = false; }
  6958. var name = null;
  6959. if (!isType && object.getClassName) {
  6960. name = object.getClassName();
  6961. }
  6962. else {
  6963. if (object instanceof Object) {
  6964. var classObj = isType ? object : Object.getPrototypeOf(object);
  6965. name = classObj.constructor["__bjsclassName__"];
  6966. }
  6967. if (!name) {
  6968. name = typeof object;
  6969. }
  6970. }
  6971. return name;
  6972. };
  6973. Tools.first = function (array, predicate) {
  6974. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6975. var el = array_1[_i];
  6976. if (predicate(el)) {
  6977. return el;
  6978. }
  6979. }
  6980. };
  6981. /**
  6982. * This method will return the name of the full name of the class, including its owning module (if any).
  6983. * 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).
  6984. * @param object the object to get the class name from
  6985. * @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.
  6986. */
  6987. Tools.getFullClassName = function (object, isType) {
  6988. if (isType === void 0) { isType = false; }
  6989. var className = null;
  6990. var moduleName = null;
  6991. if (!isType && object.getClassName) {
  6992. className = object.getClassName();
  6993. }
  6994. else {
  6995. if (object instanceof Object) {
  6996. var classObj = isType ? object : Object.getPrototypeOf(object);
  6997. className = classObj.constructor["__bjsclassName__"];
  6998. moduleName = classObj.constructor["__bjsmoduleName__"];
  6999. }
  7000. if (!className) {
  7001. className = typeof object;
  7002. }
  7003. }
  7004. if (!className) {
  7005. return null;
  7006. }
  7007. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7008. };
  7009. /**
  7010. * 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.
  7011. * @param array
  7012. */
  7013. Tools.arrayOrStringFeeder = function (array) {
  7014. return function (index) {
  7015. if (index >= array.length) {
  7016. return null;
  7017. }
  7018. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7019. if (val && val.getHashCode) {
  7020. val = val.getHashCode();
  7021. }
  7022. if (typeof val === "string") {
  7023. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7024. }
  7025. return val;
  7026. };
  7027. };
  7028. /**
  7029. * Compute the hashCode of a stream of number
  7030. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7031. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7032. * @return the hash code computed
  7033. */
  7034. Tools.hashCodeFromStream = function (feeder) {
  7035. // Based from here: http://stackoverflow.com/a/7616484/802124
  7036. var hash = 0;
  7037. var index = 0;
  7038. var chr = feeder(index++);
  7039. while (chr != null) {
  7040. hash = ((hash << 5) - hash) + chr;
  7041. hash |= 0; // Convert to 32bit integer
  7042. chr = feeder(index++);
  7043. }
  7044. return hash;
  7045. };
  7046. return Tools;
  7047. }());
  7048. Tools.BaseUrl = "";
  7049. Tools.CorsBehavior = "anonymous";
  7050. Tools.UseFallbackTexture = true;
  7051. // Used in case of a texture loading problem
  7052. 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";
  7053. // Logs
  7054. Tools._NoneLogLevel = 0;
  7055. Tools._MessageLogLevel = 1;
  7056. Tools._WarningLogLevel = 2;
  7057. Tools._ErrorLogLevel = 4;
  7058. Tools._LogCache = "";
  7059. Tools.errorsCount = 0;
  7060. Tools.Log = Tools._LogEnabled;
  7061. Tools.Warn = Tools._WarnEnabled;
  7062. Tools.Error = Tools._ErrorEnabled;
  7063. // Performances
  7064. Tools._PerformanceNoneLogLevel = 0;
  7065. Tools._PerformanceUserMarkLogLevel = 1;
  7066. Tools._PerformanceConsoleLogLevel = 2;
  7067. Tools._performance = window.performance;
  7068. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7069. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7070. BABYLON.Tools = Tools;
  7071. /**
  7072. * This class is used to track a performance counter which is number based.
  7073. * The user has access to many properties which give statistics of different nature
  7074. *
  7075. * The implementer can track two kinds of Performance Counter: time and count
  7076. * 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.
  7077. * 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.
  7078. */
  7079. var PerfCounter = (function () {
  7080. function PerfCounter() {
  7081. this._startMonitoringTime = 0;
  7082. this._min = 0;
  7083. this._max = 0;
  7084. this._average = 0;
  7085. this._lastSecAverage = 0;
  7086. this._current = 0;
  7087. this._totalValueCount = 0;
  7088. this._totalAccumulated = 0;
  7089. this._lastSecAccumulated = 0;
  7090. this._lastSecTime = 0;
  7091. this._lastSecValueCount = 0;
  7092. }
  7093. Object.defineProperty(PerfCounter.prototype, "min", {
  7094. /**
  7095. * Returns the smallest value ever
  7096. */
  7097. get: function () {
  7098. return this._min;
  7099. },
  7100. enumerable: true,
  7101. configurable: true
  7102. });
  7103. Object.defineProperty(PerfCounter.prototype, "max", {
  7104. /**
  7105. * Returns the biggest value ever
  7106. */
  7107. get: function () {
  7108. return this._max;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(PerfCounter.prototype, "average", {
  7114. /**
  7115. * Returns the average value since the performance counter is running
  7116. */
  7117. get: function () {
  7118. return this._average;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7124. /**
  7125. * Returns the average value of the last second the counter was monitored
  7126. */
  7127. get: function () {
  7128. return this._lastSecAverage;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(PerfCounter.prototype, "current", {
  7134. /**
  7135. * Returns the current value
  7136. */
  7137. get: function () {
  7138. return this._current;
  7139. },
  7140. enumerable: true,
  7141. configurable: true
  7142. });
  7143. Object.defineProperty(PerfCounter.prototype, "total", {
  7144. get: function () {
  7145. return this._totalAccumulated;
  7146. },
  7147. enumerable: true,
  7148. configurable: true
  7149. });
  7150. /**
  7151. * Call this method to start monitoring a new frame.
  7152. * 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.
  7153. */
  7154. PerfCounter.prototype.fetchNewFrame = function () {
  7155. this._totalValueCount++;
  7156. this._current = 0;
  7157. this._lastSecValueCount++;
  7158. };
  7159. /**
  7160. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7161. * @param newCount the count value to add to the monitored count
  7162. * @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.
  7163. */
  7164. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7165. if (!PerfCounter.Enabled) {
  7166. return;
  7167. }
  7168. this._current += newCount;
  7169. if (fetchResult) {
  7170. this._fetchResult();
  7171. }
  7172. };
  7173. /**
  7174. * Start monitoring this performance counter
  7175. */
  7176. PerfCounter.prototype.beginMonitoring = function () {
  7177. if (!PerfCounter.Enabled) {
  7178. return;
  7179. }
  7180. this._startMonitoringTime = Tools.Now;
  7181. };
  7182. /**
  7183. * Compute the time lapsed since the previous beginMonitoring() call.
  7184. * @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
  7185. */
  7186. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7187. if (newFrame === void 0) { newFrame = true; }
  7188. if (!PerfCounter.Enabled) {
  7189. return;
  7190. }
  7191. if (newFrame) {
  7192. this.fetchNewFrame();
  7193. }
  7194. var currentTime = Tools.Now;
  7195. this._current = currentTime - this._startMonitoringTime;
  7196. if (newFrame) {
  7197. this._fetchResult();
  7198. }
  7199. };
  7200. PerfCounter.prototype._fetchResult = function () {
  7201. this._totalAccumulated += this._current;
  7202. this._lastSecAccumulated += this._current;
  7203. // Min/Max update
  7204. this._min = Math.min(this._min, this._current);
  7205. this._max = Math.max(this._max, this._current);
  7206. this._average = this._totalAccumulated / this._totalValueCount;
  7207. // Reset last sec?
  7208. var now = Tools.Now;
  7209. if ((now - this._lastSecTime) > 1000) {
  7210. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7211. this._lastSecTime = now;
  7212. this._lastSecAccumulated = 0;
  7213. this._lastSecValueCount = 0;
  7214. }
  7215. };
  7216. return PerfCounter;
  7217. }());
  7218. PerfCounter.Enabled = true;
  7219. BABYLON.PerfCounter = PerfCounter;
  7220. /**
  7221. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7222. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7223. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7224. * @param name The name of the class, case should be preserved
  7225. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7226. */
  7227. function className(name, module) {
  7228. return function (target) {
  7229. target["__bjsclassName__"] = name;
  7230. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7231. };
  7232. }
  7233. BABYLON.className = className;
  7234. /**
  7235. * An implementation of a loop for asynchronous functions.
  7236. */
  7237. var AsyncLoop = (function () {
  7238. /**
  7239. * Constroctor.
  7240. * @param iterations the number of iterations.
  7241. * @param _fn the function to run each iteration
  7242. * @param _successCallback the callback that will be called upon succesful execution
  7243. * @param offset starting offset.
  7244. */
  7245. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7246. if (offset === void 0) { offset = 0; }
  7247. this.iterations = iterations;
  7248. this._fn = _fn;
  7249. this._successCallback = _successCallback;
  7250. this.index = offset - 1;
  7251. this._done = false;
  7252. }
  7253. /**
  7254. * Execute the next iteration. Must be called after the last iteration was finished.
  7255. */
  7256. AsyncLoop.prototype.executeNext = function () {
  7257. if (!this._done) {
  7258. if (this.index + 1 < this.iterations) {
  7259. ++this.index;
  7260. this._fn(this);
  7261. }
  7262. else {
  7263. this.breakLoop();
  7264. }
  7265. }
  7266. };
  7267. /**
  7268. * Break the loop and run the success callback.
  7269. */
  7270. AsyncLoop.prototype.breakLoop = function () {
  7271. this._done = true;
  7272. this._successCallback();
  7273. };
  7274. /**
  7275. * Helper function
  7276. */
  7277. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7278. if (offset === void 0) { offset = 0; }
  7279. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7280. loop.executeNext();
  7281. return loop;
  7282. };
  7283. /**
  7284. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7285. * @param iterations total number of iterations
  7286. * @param syncedIterations number of synchronous iterations in each async iteration.
  7287. * @param fn the function to call each iteration.
  7288. * @param callback a success call back that will be called when iterating stops.
  7289. * @param breakFunction a break condition (optional)
  7290. * @param timeout timeout settings for the setTimeout function. default - 0.
  7291. * @constructor
  7292. */
  7293. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7294. if (timeout === void 0) { timeout = 0; }
  7295. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7296. if (breakFunction && breakFunction())
  7297. loop.breakLoop();
  7298. else {
  7299. setTimeout(function () {
  7300. for (var i = 0; i < syncedIterations; ++i) {
  7301. var iteration = (loop.index * syncedIterations) + i;
  7302. if (iteration >= iterations)
  7303. break;
  7304. fn(iteration);
  7305. if (breakFunction && breakFunction()) {
  7306. loop.breakLoop();
  7307. break;
  7308. }
  7309. }
  7310. loop.executeNext();
  7311. }, timeout);
  7312. }
  7313. }, callback);
  7314. };
  7315. return AsyncLoop;
  7316. }());
  7317. BABYLON.AsyncLoop = AsyncLoop;
  7318. })(BABYLON || (BABYLON = {}));
  7319. //# sourceMappingURL=babylon.tools.js.map
  7320. var BABYLON;
  7321. (function (BABYLON) {
  7322. var Internals;
  7323. (function (Internals) {
  7324. var _AlphaState = (function () {
  7325. /**
  7326. * Initializes the state.
  7327. */
  7328. function _AlphaState() {
  7329. this._isAlphaBlendDirty = false;
  7330. this._isBlendFunctionParametersDirty = false;
  7331. this._alphaBlend = false;
  7332. this._blendFunctionParameters = new Array(4);
  7333. this.reset();
  7334. }
  7335. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7336. get: function () {
  7337. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7343. get: function () {
  7344. return this._alphaBlend;
  7345. },
  7346. set: function (value) {
  7347. if (this._alphaBlend === value) {
  7348. return;
  7349. }
  7350. this._alphaBlend = value;
  7351. this._isAlphaBlendDirty = true;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7357. if (this._blendFunctionParameters[0] === value0 &&
  7358. this._blendFunctionParameters[1] === value1 &&
  7359. this._blendFunctionParameters[2] === value2 &&
  7360. this._blendFunctionParameters[3] === value3) {
  7361. return;
  7362. }
  7363. this._blendFunctionParameters[0] = value0;
  7364. this._blendFunctionParameters[1] = value1;
  7365. this._blendFunctionParameters[2] = value2;
  7366. this._blendFunctionParameters[3] = value3;
  7367. this._isBlendFunctionParametersDirty = true;
  7368. };
  7369. _AlphaState.prototype.reset = function () {
  7370. this._alphaBlend = false;
  7371. this._blendFunctionParameters[0] = null;
  7372. this._blendFunctionParameters[1] = null;
  7373. this._blendFunctionParameters[2] = null;
  7374. this._blendFunctionParameters[3] = null;
  7375. this._isAlphaBlendDirty = true;
  7376. this._isBlendFunctionParametersDirty = false;
  7377. };
  7378. _AlphaState.prototype.apply = function (gl) {
  7379. if (!this.isDirty) {
  7380. return;
  7381. }
  7382. // Alpha blend
  7383. if (this._isAlphaBlendDirty) {
  7384. if (this._alphaBlend) {
  7385. gl.enable(gl.BLEND);
  7386. }
  7387. else {
  7388. gl.disable(gl.BLEND);
  7389. }
  7390. this._isAlphaBlendDirty = false;
  7391. }
  7392. // Alpha function
  7393. if (this._isBlendFunctionParametersDirty) {
  7394. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7395. this._isBlendFunctionParametersDirty = false;
  7396. }
  7397. };
  7398. return _AlphaState;
  7399. }());
  7400. Internals._AlphaState = _AlphaState;
  7401. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7402. })(BABYLON || (BABYLON = {}));
  7403. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7404. var BABYLON;
  7405. (function (BABYLON) {
  7406. var Internals;
  7407. (function (Internals) {
  7408. var _DepthCullingState = (function () {
  7409. /**
  7410. * Initializes the state.
  7411. */
  7412. function _DepthCullingState() {
  7413. this._isDepthTestDirty = false;
  7414. this._isDepthMaskDirty = false;
  7415. this._isDepthFuncDirty = false;
  7416. this._isCullFaceDirty = false;
  7417. this._isCullDirty = false;
  7418. this._isZOffsetDirty = false;
  7419. this.reset();
  7420. }
  7421. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7422. get: function () {
  7423. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7429. get: function () {
  7430. return this._zOffset;
  7431. },
  7432. set: function (value) {
  7433. if (this._zOffset === value) {
  7434. return;
  7435. }
  7436. this._zOffset = value;
  7437. this._isZOffsetDirty = true;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7443. get: function () {
  7444. return this._cullFace;
  7445. },
  7446. set: function (value) {
  7447. if (this._cullFace === value) {
  7448. return;
  7449. }
  7450. this._cullFace = value;
  7451. this._isCullFaceDirty = true;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7457. get: function () {
  7458. return this._cull;
  7459. },
  7460. set: function (value) {
  7461. if (this._cull === value) {
  7462. return;
  7463. }
  7464. this._cull = value;
  7465. this._isCullDirty = true;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7471. get: function () {
  7472. return this._depthFunc;
  7473. },
  7474. set: function (value) {
  7475. if (this._depthFunc === value) {
  7476. return;
  7477. }
  7478. this._depthFunc = value;
  7479. this._isDepthFuncDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7485. get: function () {
  7486. return this._depthMask;
  7487. },
  7488. set: function (value) {
  7489. if (this._depthMask === value) {
  7490. return;
  7491. }
  7492. this._depthMask = value;
  7493. this._isDepthMaskDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7499. get: function () {
  7500. return this._depthTest;
  7501. },
  7502. set: function (value) {
  7503. if (this._depthTest === value) {
  7504. return;
  7505. }
  7506. this._depthTest = value;
  7507. this._isDepthTestDirty = true;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. _DepthCullingState.prototype.reset = function () {
  7513. this._depthMask = true;
  7514. this._depthTest = true;
  7515. this._depthFunc = null;
  7516. this._cullFace = null;
  7517. this._cull = null;
  7518. this._zOffset = 0;
  7519. this._isDepthTestDirty = true;
  7520. this._isDepthMaskDirty = true;
  7521. this._isDepthFuncDirty = false;
  7522. this._isCullFaceDirty = false;
  7523. this._isCullDirty = false;
  7524. this._isZOffsetDirty = false;
  7525. };
  7526. _DepthCullingState.prototype.apply = function (gl) {
  7527. if (!this.isDirty) {
  7528. return;
  7529. }
  7530. // Cull
  7531. if (this._isCullDirty) {
  7532. if (this.cull) {
  7533. gl.enable(gl.CULL_FACE);
  7534. }
  7535. else {
  7536. gl.disable(gl.CULL_FACE);
  7537. }
  7538. this._isCullDirty = false;
  7539. }
  7540. // Cull face
  7541. if (this._isCullFaceDirty) {
  7542. gl.cullFace(this.cullFace);
  7543. this._isCullFaceDirty = false;
  7544. }
  7545. // Depth mask
  7546. if (this._isDepthMaskDirty) {
  7547. gl.depthMask(this.depthMask);
  7548. this._isDepthMaskDirty = false;
  7549. }
  7550. // Depth test
  7551. if (this._isDepthTestDirty) {
  7552. if (this.depthTest) {
  7553. gl.enable(gl.DEPTH_TEST);
  7554. }
  7555. else {
  7556. gl.disable(gl.DEPTH_TEST);
  7557. }
  7558. this._isDepthTestDirty = false;
  7559. }
  7560. // Depth func
  7561. if (this._isDepthFuncDirty) {
  7562. gl.depthFunc(this.depthFunc);
  7563. this._isDepthFuncDirty = false;
  7564. }
  7565. // zOffset
  7566. if (this._isZOffsetDirty) {
  7567. if (this.zOffset) {
  7568. gl.enable(gl.POLYGON_OFFSET_FILL);
  7569. gl.polygonOffset(this.zOffset, 0);
  7570. }
  7571. else {
  7572. gl.disable(gl.POLYGON_OFFSET_FILL);
  7573. }
  7574. this._isZOffsetDirty = false;
  7575. }
  7576. };
  7577. return _DepthCullingState;
  7578. }());
  7579. Internals._DepthCullingState = _DepthCullingState;
  7580. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7581. })(BABYLON || (BABYLON = {}));
  7582. //# sourceMappingURL=babylon.depthCullingState.js.map
  7583. var BABYLON;
  7584. (function (BABYLON) {
  7585. var Internals;
  7586. (function (Internals) {
  7587. var _StencilState = (function () {
  7588. function _StencilState() {
  7589. this._isStencilTestDirty = false;
  7590. this._isStencilMaskDirty = false;
  7591. this._isStencilFuncDirty = false;
  7592. this._isStencilOpDirty = false;
  7593. this.reset();
  7594. }
  7595. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7596. get: function () {
  7597. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7603. get: function () {
  7604. return this._stencilFunc;
  7605. },
  7606. set: function (value) {
  7607. if (this._stencilFunc === value) {
  7608. return;
  7609. }
  7610. this._stencilFunc = value;
  7611. this._isStencilFuncDirty = true;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7617. get: function () {
  7618. return this._stencilFuncRef;
  7619. },
  7620. set: function (value) {
  7621. if (this._stencilFuncRef === value) {
  7622. return;
  7623. }
  7624. this._stencilFuncRef = value;
  7625. this._isStencilFuncDirty = true;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7631. get: function () {
  7632. return this._stencilFuncMask;
  7633. },
  7634. set: function (value) {
  7635. if (this._stencilFuncMask === value) {
  7636. return;
  7637. }
  7638. this._stencilFuncMask = value;
  7639. this._isStencilFuncDirty = true;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7645. get: function () {
  7646. return this._stencilOpStencilFail;
  7647. },
  7648. set: function (value) {
  7649. if (this._stencilOpStencilFail === value) {
  7650. return;
  7651. }
  7652. this._stencilOpStencilFail = value;
  7653. this._isStencilOpDirty = true;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7659. get: function () {
  7660. return this._stencilOpDepthFail;
  7661. },
  7662. set: function (value) {
  7663. if (this._stencilOpDepthFail === value) {
  7664. return;
  7665. }
  7666. this._stencilOpDepthFail = value;
  7667. this._isStencilOpDirty = true;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7673. get: function () {
  7674. return this._stencilOpStencilDepthPass;
  7675. },
  7676. set: function (value) {
  7677. if (this._stencilOpStencilDepthPass === value) {
  7678. return;
  7679. }
  7680. this._stencilOpStencilDepthPass = value;
  7681. this._isStencilOpDirty = true;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7687. get: function () {
  7688. return this._stencilMask;
  7689. },
  7690. set: function (value) {
  7691. if (this._stencilMask === value) {
  7692. return;
  7693. }
  7694. this._stencilMask = value;
  7695. this._isStencilMaskDirty = true;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7701. get: function () {
  7702. return this._stencilTest;
  7703. },
  7704. set: function (value) {
  7705. if (this._stencilTest === value) {
  7706. return;
  7707. }
  7708. this._stencilTest = value;
  7709. this._isStencilTestDirty = true;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. _StencilState.prototype.reset = function () {
  7715. this._stencilTest = false;
  7716. this._stencilMask = 0xFF;
  7717. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7718. this._stencilFuncRef = 1;
  7719. this._stencilFuncMask = 0xFF;
  7720. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7721. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7722. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7723. this._isStencilTestDirty = true;
  7724. this._isStencilMaskDirty = true;
  7725. this._isStencilFuncDirty = true;
  7726. this._isStencilOpDirty = true;
  7727. };
  7728. _StencilState.prototype.apply = function (gl) {
  7729. if (!this.isDirty) {
  7730. return;
  7731. }
  7732. // Stencil test
  7733. if (this._isStencilTestDirty) {
  7734. if (this.stencilTest) {
  7735. gl.enable(gl.STENCIL_TEST);
  7736. }
  7737. else {
  7738. gl.disable(gl.STENCIL_TEST);
  7739. }
  7740. this._isStencilTestDirty = false;
  7741. }
  7742. // Stencil mask
  7743. if (this._isStencilMaskDirty) {
  7744. gl.stencilMask(this.stencilMask);
  7745. this._isStencilMaskDirty = false;
  7746. }
  7747. // Stencil func
  7748. if (this._isStencilFuncDirty) {
  7749. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7750. this._isStencilFuncDirty = false;
  7751. }
  7752. // Stencil op
  7753. if (this._isStencilOpDirty) {
  7754. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7755. this._isStencilOpDirty = false;
  7756. }
  7757. };
  7758. return _StencilState;
  7759. }());
  7760. Internals._StencilState = _StencilState;
  7761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7762. })(BABYLON || (BABYLON = {}));
  7763. //# sourceMappingURL=babylon.stencilState.js.map
  7764. var BABYLON;
  7765. (function (BABYLON) {
  7766. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7767. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7768. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7769. gl.compileShader(shader);
  7770. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7771. throw new Error(gl.getShaderInfoLog(shader));
  7772. }
  7773. return shader;
  7774. };
  7775. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7776. var magFilter = gl.NEAREST;
  7777. var minFilter = gl.NEAREST;
  7778. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7779. magFilter = gl.LINEAR;
  7780. if (generateMipMaps) {
  7781. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7782. }
  7783. else {
  7784. minFilter = gl.LINEAR;
  7785. }
  7786. }
  7787. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7788. magFilter = gl.LINEAR;
  7789. if (generateMipMaps) {
  7790. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7791. }
  7792. else {
  7793. minFilter = gl.LINEAR;
  7794. }
  7795. }
  7796. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7797. magFilter = gl.NEAREST;
  7798. if (generateMipMaps) {
  7799. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7800. }
  7801. else {
  7802. minFilter = gl.NEAREST;
  7803. }
  7804. }
  7805. return {
  7806. min: minFilter,
  7807. mag: magFilter
  7808. };
  7809. };
  7810. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7812. var engine = scene.getEngine();
  7813. if (!engine) {
  7814. return;
  7815. }
  7816. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7817. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7818. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7819. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7820. texture._baseWidth = width;
  7821. texture._baseHeight = height;
  7822. texture._width = potWidth;
  7823. texture._height = potHeight;
  7824. texture.isReady = true;
  7825. processFunction(potWidth, potHeight);
  7826. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7829. if (!noMipmap && !isCompressed) {
  7830. gl.generateMipmap(gl.TEXTURE_2D);
  7831. }
  7832. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7833. engine.resetTextureCache();
  7834. scene._removePendingData(texture);
  7835. texture.onLoadedCallbacks.forEach(function (callback) {
  7836. callback();
  7837. });
  7838. texture.onLoadedCallbacks = [];
  7839. };
  7840. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7841. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7842. var img;
  7843. var onload = function () {
  7844. loadedImages[index] = img;
  7845. loadedImages._internalCount++;
  7846. scene._removePendingData(img);
  7847. if (loadedImages._internalCount === 6) {
  7848. onfinish(loadedImages);
  7849. }
  7850. };
  7851. var onerror = function () {
  7852. scene._removePendingData(img);
  7853. if (onErrorCallBack) {
  7854. onErrorCallBack();
  7855. }
  7856. };
  7857. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7858. scene._addPendingData(img);
  7859. };
  7860. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7861. if (onError === void 0) { onError = null; }
  7862. var loadedImages = [];
  7863. loadedImages._internalCount = 0;
  7864. for (var index = 0; index < 6; index++) {
  7865. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7866. }
  7867. };
  7868. var InstancingAttributeInfo = (function () {
  7869. function InstancingAttributeInfo() {
  7870. }
  7871. return InstancingAttributeInfo;
  7872. }());
  7873. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7874. var EngineCapabilities = (function () {
  7875. function EngineCapabilities() {
  7876. }
  7877. return EngineCapabilities;
  7878. }());
  7879. BABYLON.EngineCapabilities = EngineCapabilities;
  7880. /**
  7881. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7882. */
  7883. var Engine = (function () {
  7884. /**
  7885. * @constructor
  7886. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7887. * @param {boolean} [antialias] - enable antialias
  7888. * @param options - further options to be sent to the getContext function
  7889. */
  7890. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7891. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7892. var _this = this;
  7893. // Public members
  7894. this.isFullscreen = false;
  7895. this.isPointerLock = false;
  7896. this.cullBackFaces = true;
  7897. this.renderEvenInBackground = true;
  7898. this.preventCacheWipeBetweenFrames = false;
  7899. // To enable/disable IDB support and avoid XHR on .manifest
  7900. this.enableOfflineSupport = true;
  7901. this.scenes = new Array();
  7902. this._windowIsBackground = false;
  7903. this._webGLVersion = 1.0;
  7904. this._badOS = false;
  7905. this._drawCalls = new BABYLON.PerfCounter();
  7906. this._renderingQueueLaunched = false;
  7907. this._activeRenderLoops = [];
  7908. // FPS
  7909. this.fpsRange = 60;
  7910. this.previousFramesDuration = [];
  7911. this.fps = 60;
  7912. this.deltaTime = 0;
  7913. // States
  7914. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7915. this._stencilState = new BABYLON.Internals._StencilState();
  7916. this._alphaState = new BABYLON.Internals._AlphaState();
  7917. this._alphaMode = Engine.ALPHA_DISABLE;
  7918. // Cache
  7919. this._loadedTexturesCache = new Array();
  7920. this._maxTextureChannels = 16;
  7921. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7922. this._compiledEffects = {};
  7923. this._vertexAttribArraysEnabled = [];
  7924. this._uintIndicesCurrentlySet = false;
  7925. this._currentBoundBuffer = new Array();
  7926. this._currentBufferPointers = [];
  7927. this._currentInstanceLocations = new Array();
  7928. this._currentInstanceBuffers = new Array();
  7929. this._vaoRecordInProgress = false;
  7930. this._mustWipeVertexAttributes = false;
  7931. // Hardware supported Compressed Textures
  7932. this._texturesSupported = new Array();
  7933. this._onVRFullScreenTriggered = function () {
  7934. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7935. //get the old size before we change
  7936. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7937. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7938. //get the width and height, change the render size
  7939. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7940. var width, height;
  7941. _this.setHardwareScalingLevel(1);
  7942. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7943. }
  7944. else {
  7945. //When the specs are implemented, need to uncomment this.
  7946. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7947. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7948. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7949. _this._vrDisplayEnabled = undefined;
  7950. }
  7951. };
  7952. this._renderingCanvas = canvas;
  7953. Engine.Instances.push(this);
  7954. this._externalData = new BABYLON.StringDictionary();
  7955. options = options || {};
  7956. if (antialias != null) {
  7957. options.antialias = antialias;
  7958. }
  7959. if (options.preserveDrawingBuffer === undefined) {
  7960. options.preserveDrawingBuffer = false;
  7961. }
  7962. if (options.audioEngine === undefined) {
  7963. options.audioEngine = true;
  7964. }
  7965. if (options.stencil === undefined) {
  7966. options.stencil = true;
  7967. }
  7968. // GL
  7969. if (!options.disableWebGL2Support) {
  7970. try {
  7971. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7972. if (this._gl) {
  7973. this._webGLVersion = 2.0;
  7974. }
  7975. }
  7976. catch (e) {
  7977. // Do nothing
  7978. }
  7979. }
  7980. if (!this._gl) {
  7981. if (!canvas) {
  7982. throw new Error("The provided canvas is null or undefined.");
  7983. }
  7984. try {
  7985. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7986. }
  7987. catch (e) {
  7988. throw new Error("WebGL not supported");
  7989. }
  7990. }
  7991. if (!this._gl) {
  7992. throw new Error("WebGL not supported");
  7993. }
  7994. this._onBlur = function () {
  7995. _this._windowIsBackground = true;
  7996. };
  7997. this._onFocus = function () {
  7998. _this._windowIsBackground = false;
  7999. };
  8000. window.addEventListener("blur", this._onBlur);
  8001. window.addEventListener("focus", this._onFocus);
  8002. // Viewport
  8003. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8004. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8005. this.resize();
  8006. // Caps
  8007. this._isStencilEnable = options.stencil;
  8008. this._caps = new EngineCapabilities();
  8009. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8010. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8011. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8012. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8013. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8014. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8015. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8016. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8017. // Infos
  8018. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8019. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8020. if (rendererInfo != null) {
  8021. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8022. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8023. }
  8024. if (!this._glVendor) {
  8025. this._glVendor = "Unknown vendor";
  8026. }
  8027. if (!this._glRenderer) {
  8028. this._glRenderer = "Unknown renderer";
  8029. }
  8030. // Extensions
  8031. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8032. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8033. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8034. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8035. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8036. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8037. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8038. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  8039. 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');
  8040. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8041. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8042. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8043. this._caps.highPrecisionShaderSupported = true;
  8044. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8045. // Checks if some of the format renders first to allow the use of webgl inspector.
  8046. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8047. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8048. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8049. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8050. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8051. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8052. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8053. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8054. // Vertex array object
  8055. if (this._webGLVersion > 1) {
  8056. this._caps.vertexArrayObject = true;
  8057. }
  8058. else {
  8059. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8060. if (vertexArrayObjectExtension != null) {
  8061. this._caps.vertexArrayObject = true;
  8062. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8063. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8064. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8065. }
  8066. else {
  8067. this._caps.vertexArrayObject = false;
  8068. }
  8069. }
  8070. // Instances count
  8071. if (this._webGLVersion > 1) {
  8072. this._caps.instancedArrays = true;
  8073. }
  8074. else {
  8075. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8076. if (instanceExtension != null) {
  8077. this._caps.instancedArrays = true;
  8078. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8079. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8080. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8081. }
  8082. else {
  8083. this._caps.instancedArrays = false;
  8084. }
  8085. }
  8086. // Intelligently add supported compressed formats in order to check for.
  8087. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8088. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8089. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8090. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8091. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8092. if (this._caps.astc)
  8093. this.texturesSupported.push('-astc.ktx');
  8094. if (this._caps.s3tc)
  8095. this.texturesSupported.push('-dxt.ktx');
  8096. if (this._caps.pvrtc)
  8097. this.texturesSupported.push('-pvrtc.ktx');
  8098. if (this._caps.etc2)
  8099. this.texturesSupported.push('-etc2.ktx');
  8100. if (this._caps.atc)
  8101. this.texturesSupported.push('-atc.ktx');
  8102. if (this._caps.etc1)
  8103. this.texturesSupported.push('-etc1.ktx');
  8104. if (this._gl.getShaderPrecisionFormat) {
  8105. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8106. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8107. }
  8108. // Depth buffer
  8109. this.setDepthBuffer(true);
  8110. this.setDepthFunctionToLessOrEqual();
  8111. this.setDepthWrite(true);
  8112. // Fullscreen
  8113. this._onFullscreenChange = function () {
  8114. if (document.fullscreen !== undefined) {
  8115. _this.isFullscreen = document.fullscreen;
  8116. }
  8117. else if (document.mozFullScreen !== undefined) {
  8118. _this.isFullscreen = document.mozFullScreen;
  8119. }
  8120. else if (document.webkitIsFullScreen !== undefined) {
  8121. _this.isFullscreen = document.webkitIsFullScreen;
  8122. }
  8123. else if (document.msIsFullScreen !== undefined) {
  8124. _this.isFullscreen = document.msIsFullScreen;
  8125. }
  8126. // Pointer lock
  8127. if (_this.isFullscreen && _this._pointerLockRequested) {
  8128. canvas.requestPointerLock = canvas.requestPointerLock ||
  8129. canvas.msRequestPointerLock ||
  8130. canvas.mozRequestPointerLock ||
  8131. canvas.webkitRequestPointerLock;
  8132. if (canvas.requestPointerLock) {
  8133. canvas.requestPointerLock();
  8134. }
  8135. }
  8136. };
  8137. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8138. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8139. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8140. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8141. // Pointer lock
  8142. this._onPointerLockChange = function () {
  8143. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8144. document.webkitPointerLockElement === canvas ||
  8145. document.msPointerLockElement === canvas ||
  8146. document.pointerLockElement === canvas);
  8147. };
  8148. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8149. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8150. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8151. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8152. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8153. Engine.audioEngine = new BABYLON.AudioEngine();
  8154. }
  8155. //default loading screen
  8156. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8157. //Load WebVR Devices
  8158. if (options.autoEnableWebVR) {
  8159. this.initWebVR();
  8160. }
  8161. //Detect if we are running on a faulty buggy OS.
  8162. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8163. //ua sniffing is the tool of the devil.
  8164. this._badOS = regexp.test(navigator.userAgent);
  8165. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8166. }
  8167. Object.defineProperty(Engine, "LastCreatedEngine", {
  8168. get: function () {
  8169. if (Engine.Instances.length === 0) {
  8170. return null;
  8171. }
  8172. return Engine.Instances[Engine.Instances.length - 1];
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "LastCreatedScene", {
  8178. get: function () {
  8179. var lastCreatedEngine = Engine.LastCreatedEngine;
  8180. if (!lastCreatedEngine) {
  8181. return null;
  8182. }
  8183. if (lastCreatedEngine.scenes.length === 0) {
  8184. return null;
  8185. }
  8186. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "NEVER", {
  8192. get: function () {
  8193. return Engine._NEVER;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "ALWAYS", {
  8199. get: function () {
  8200. return Engine._ALWAYS;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "LESS", {
  8206. get: function () {
  8207. return Engine._LESS;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "EQUAL", {
  8213. get: function () {
  8214. return Engine._EQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "LEQUAL", {
  8220. get: function () {
  8221. return Engine._LEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "GREATER", {
  8227. get: function () {
  8228. return Engine._GREATER;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "GEQUAL", {
  8234. get: function () {
  8235. return Engine._GEQUAL;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "NOTEQUAL", {
  8241. get: function () {
  8242. return Engine._NOTEQUAL;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "KEEP", {
  8248. get: function () {
  8249. return Engine._KEEP;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "REPLACE", {
  8255. get: function () {
  8256. return Engine._REPLACE;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR", {
  8262. get: function () {
  8263. return Engine._INCR;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR", {
  8269. get: function () {
  8270. return Engine._DECR;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "INVERT", {
  8276. get: function () {
  8277. return Engine._INVERT;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "INCR_WRAP", {
  8283. get: function () {
  8284. return Engine._INCR_WRAP;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "DECR_WRAP", {
  8290. get: function () {
  8291. return Engine._DECR_WRAP;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8297. get: function () {
  8298. return Engine._ALPHA_DISABLE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8304. get: function () {
  8305. return Engine._ALPHA_ONEONE;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_ADD", {
  8311. get: function () {
  8312. return Engine._ALPHA_ADD;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8318. get: function () {
  8319. return Engine._ALPHA_COMBINE;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8325. get: function () {
  8326. return Engine._ALPHA_SUBTRACT;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8332. get: function () {
  8333. return Engine._ALPHA_MULTIPLY;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8339. get: function () {
  8340. return Engine._ALPHA_MAXIMIZED;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8346. get: function () {
  8347. return Engine._ALPHA_PREMULTIPLIED;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "Version", {
  8437. get: function () {
  8438. return "3.0-alpha";
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8444. get: function () {
  8445. return this._texturesSupported;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8451. get: function () {
  8452. return this._textureFormatInUse;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8458. get: function () {
  8459. return this._webGLVersion;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8465. /**
  8466. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8467. */
  8468. get: function () {
  8469. return this._isStencilEnable;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Engine.prototype._prepareWorkingCanvas = function () {
  8475. if (this._workingCanvas) {
  8476. return;
  8477. }
  8478. this._workingCanvas = document.createElement("canvas");
  8479. this._workingContext = this._workingCanvas.getContext("2d");
  8480. };
  8481. Engine.prototype.resetTextureCache = function () {
  8482. for (var index = 0; index < this._maxTextureChannels; index++) {
  8483. this._activeTexturesCache[index] = null;
  8484. }
  8485. };
  8486. Engine.prototype.getGlInfo = function () {
  8487. return {
  8488. vendor: this._glVendor,
  8489. renderer: this._glRenderer,
  8490. version: this._glVersion
  8491. };
  8492. };
  8493. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. var viewport = camera.viewport;
  8496. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8497. };
  8498. Engine.prototype.getRenderWidth = function (useScreen) {
  8499. if (useScreen === void 0) { useScreen = false; }
  8500. if (!useScreen && this._currentRenderTarget) {
  8501. return this._currentRenderTarget._width;
  8502. }
  8503. return this._renderingCanvas.width;
  8504. };
  8505. Engine.prototype.getRenderHeight = function (useScreen) {
  8506. if (useScreen === void 0) { useScreen = false; }
  8507. if (!useScreen && this._currentRenderTarget) {
  8508. return this._currentRenderTarget._height;
  8509. }
  8510. return this._renderingCanvas.height;
  8511. };
  8512. Engine.prototype.getRenderingCanvas = function () {
  8513. return this._renderingCanvas;
  8514. };
  8515. Engine.prototype.getRenderingCanvasClientRect = function () {
  8516. return this._renderingCanvas.getBoundingClientRect();
  8517. };
  8518. Engine.prototype.setHardwareScalingLevel = function (level) {
  8519. this._hardwareScalingLevel = level;
  8520. this.resize();
  8521. };
  8522. Engine.prototype.getHardwareScalingLevel = function () {
  8523. return this._hardwareScalingLevel;
  8524. };
  8525. Engine.prototype.getLoadedTexturesCache = function () {
  8526. return this._loadedTexturesCache;
  8527. };
  8528. Engine.prototype.getCaps = function () {
  8529. return this._caps;
  8530. };
  8531. Object.defineProperty(Engine.prototype, "drawCalls", {
  8532. get: function () {
  8533. return this._drawCalls.current;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8539. get: function () {
  8540. return this._drawCalls;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Engine.prototype.getDepthFunction = function () {
  8546. return this._depthCullingState.depthFunc;
  8547. };
  8548. Engine.prototype.setDepthFunction = function (depthFunc) {
  8549. this._depthCullingState.depthFunc = depthFunc;
  8550. };
  8551. Engine.prototype.setDepthFunctionToGreater = function () {
  8552. this._depthCullingState.depthFunc = this._gl.GREATER;
  8553. };
  8554. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8555. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8556. };
  8557. Engine.prototype.setDepthFunctionToLess = function () {
  8558. this._depthCullingState.depthFunc = this._gl.LESS;
  8559. };
  8560. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8561. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8562. };
  8563. Engine.prototype.getStencilBuffer = function () {
  8564. return this._stencilState.stencilTest;
  8565. };
  8566. Engine.prototype.setStencilBuffer = function (enable) {
  8567. this._stencilState.stencilTest = enable;
  8568. };
  8569. Engine.prototype.getStencilMask = function () {
  8570. return this._stencilState.stencilMask;
  8571. };
  8572. Engine.prototype.setStencilMask = function (mask) {
  8573. this._stencilState.stencilMask = mask;
  8574. };
  8575. Engine.prototype.getStencilFunction = function () {
  8576. return this._stencilState.stencilFunc;
  8577. };
  8578. Engine.prototype.getStencilFunctionReference = function () {
  8579. return this._stencilState.stencilFuncRef;
  8580. };
  8581. Engine.prototype.getStencilFunctionMask = function () {
  8582. return this._stencilState.stencilFuncMask;
  8583. };
  8584. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8585. this._stencilState.stencilFunc = stencilFunc;
  8586. };
  8587. Engine.prototype.setStencilFunctionReference = function (reference) {
  8588. this._stencilState.stencilFuncRef = reference;
  8589. };
  8590. Engine.prototype.setStencilFunctionMask = function (mask) {
  8591. this._stencilState.stencilFuncMask = mask;
  8592. };
  8593. Engine.prototype.getStencilOperationFail = function () {
  8594. return this._stencilState.stencilOpStencilFail;
  8595. };
  8596. Engine.prototype.getStencilOperationDepthFail = function () {
  8597. return this._stencilState.stencilOpDepthFail;
  8598. };
  8599. Engine.prototype.getStencilOperationPass = function () {
  8600. return this._stencilState.stencilOpStencilDepthPass;
  8601. };
  8602. Engine.prototype.setStencilOperationFail = function (operation) {
  8603. this._stencilState.stencilOpStencilFail = operation;
  8604. };
  8605. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8606. this._stencilState.stencilOpDepthFail = operation;
  8607. };
  8608. Engine.prototype.setStencilOperationPass = function (operation) {
  8609. this._stencilState.stencilOpStencilDepthPass = operation;
  8610. };
  8611. /**
  8612. * stop executing a render loop function and remove it from the execution array
  8613. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8614. */
  8615. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8616. if (!renderFunction) {
  8617. this._activeRenderLoops = [];
  8618. return;
  8619. }
  8620. var index = this._activeRenderLoops.indexOf(renderFunction);
  8621. if (index >= 0) {
  8622. this._activeRenderLoops.splice(index, 1);
  8623. }
  8624. };
  8625. Engine.prototype._renderLoop = function () {
  8626. var shouldRender = true;
  8627. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8628. shouldRender = false;
  8629. }
  8630. if (shouldRender) {
  8631. // Start new frame
  8632. this.beginFrame();
  8633. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8634. var renderFunction = this._activeRenderLoops[index];
  8635. renderFunction();
  8636. }
  8637. // Present
  8638. this.endFrame();
  8639. }
  8640. if (this._activeRenderLoops.length > 0) {
  8641. // Register new frame
  8642. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8643. }
  8644. else {
  8645. this._renderingQueueLaunched = false;
  8646. }
  8647. };
  8648. /**
  8649. * Register and execute a render loop. The engine can have more than one render function.
  8650. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8651. * @example
  8652. * engine.runRenderLoop(function () {
  8653. * scene.render()
  8654. * })
  8655. */
  8656. Engine.prototype.runRenderLoop = function (renderFunction) {
  8657. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8658. return;
  8659. }
  8660. this._activeRenderLoops.push(renderFunction);
  8661. if (!this._renderingQueueLaunched) {
  8662. this._renderingQueueLaunched = true;
  8663. this._bindedRenderFunction = this._renderLoop.bind(this);
  8664. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8665. }
  8666. };
  8667. /**
  8668. * Toggle full screen mode.
  8669. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8670. * @param {any} options - an options object to be sent to the requestFullscreen function
  8671. */
  8672. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8673. if (this.isFullscreen) {
  8674. BABYLON.Tools.ExitFullscreen();
  8675. }
  8676. else {
  8677. this._pointerLockRequested = requestPointerLock;
  8678. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8679. }
  8680. };
  8681. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8682. if (stencil === void 0) { stencil = false; }
  8683. this.applyStates();
  8684. var mode = 0;
  8685. if (backBuffer && color) {
  8686. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8687. mode |= this._gl.COLOR_BUFFER_BIT;
  8688. }
  8689. if (depth) {
  8690. this._gl.clearDepth(1.0);
  8691. mode |= this._gl.DEPTH_BUFFER_BIT;
  8692. }
  8693. if (stencil) {
  8694. this._gl.clearStencil(0);
  8695. mode |= this._gl.STENCIL_BUFFER_BIT;
  8696. }
  8697. this._gl.clear(mode);
  8698. };
  8699. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8700. var gl = this._gl;
  8701. // Save state
  8702. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8703. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8704. // Change state
  8705. gl.enable(gl.SCISSOR_TEST);
  8706. gl.scissor(x, y, width, height);
  8707. // Clear
  8708. this.clear(clearColor, true, true, true);
  8709. // Restore state
  8710. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8711. if (curScissor === true) {
  8712. gl.enable(gl.SCISSOR_TEST);
  8713. }
  8714. else {
  8715. gl.disable(gl.SCISSOR_TEST);
  8716. }
  8717. };
  8718. /**
  8719. * Set the WebGL's viewport
  8720. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8721. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8722. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8723. */
  8724. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8725. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8726. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8727. var x = viewport.x || 0;
  8728. var y = viewport.y || 0;
  8729. this._cachedViewport = viewport;
  8730. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8731. };
  8732. /**
  8733. * Directly set the WebGL Viewport
  8734. * The x, y, width & height are directly passed to the WebGL call
  8735. * @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.
  8736. */
  8737. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8738. var currentViewport = this._cachedViewport;
  8739. this._cachedViewport = null;
  8740. this._gl.viewport(x, y, width, height);
  8741. return currentViewport;
  8742. };
  8743. Engine.prototype.beginFrame = function () {
  8744. this._measureFps();
  8745. };
  8746. Engine.prototype.endFrame = function () {
  8747. //force a flush in case we are using a bad OS.
  8748. if (this._badOS) {
  8749. this.flushFramebuffer();
  8750. }
  8751. //submit frame to the vr device, if enabled
  8752. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8753. this._vrDisplayEnabled.submitFrame();
  8754. }
  8755. };
  8756. /**
  8757. * resize the view according to the canvas' size.
  8758. * @example
  8759. * window.addEventListener("resize", function () {
  8760. * engine.resize();
  8761. * });
  8762. */
  8763. Engine.prototype.resize = function () {
  8764. // We're not resizing the size of the canvas while in VR mode & presenting
  8765. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8766. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8767. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8768. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8769. }
  8770. };
  8771. /**
  8772. * force a specific size of the canvas
  8773. * @param {number} width - the new canvas' width
  8774. * @param {number} height - the new canvas' height
  8775. */
  8776. Engine.prototype.setSize = function (width, height) {
  8777. this._renderingCanvas.width = width;
  8778. this._renderingCanvas.height = height;
  8779. for (var index = 0; index < this.scenes.length; index++) {
  8780. var scene = this.scenes[index];
  8781. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8782. var cam = scene.cameras[camIndex];
  8783. cam._currentRenderId = 0;
  8784. }
  8785. }
  8786. };
  8787. //WebVR functions
  8788. Engine.prototype.initWebVR = function () {
  8789. if (!this.vrDisplaysPromise) {
  8790. this._getVRDisplays();
  8791. }
  8792. };
  8793. Engine.prototype.enableVR = function (vrDevice) {
  8794. this._vrDisplayEnabled = vrDevice;
  8795. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8796. };
  8797. Engine.prototype.disableVR = function () {
  8798. if (this._vrDisplayEnabled) {
  8799. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8800. }
  8801. };
  8802. Engine.prototype._getVRDisplays = function () {
  8803. var _this = this;
  8804. var getWebVRDevices = function (devices) {
  8805. var size = devices.length;
  8806. var i = 0;
  8807. _this._vrDisplays = devices.filter(function (device) {
  8808. return devices[i] instanceof VRDisplay;
  8809. });
  8810. return _this._vrDisplays;
  8811. };
  8812. //using a key due to typescript
  8813. if (navigator.getVRDisplays) {
  8814. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8815. }
  8816. };
  8817. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8818. this._currentRenderTarget = texture;
  8819. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8820. var gl = this._gl;
  8821. if (texture.isCube) {
  8822. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8823. }
  8824. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8825. this.wipeCaches();
  8826. };
  8827. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8828. if (this._currentFramebuffer !== framebuffer) {
  8829. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8830. this._currentFramebuffer = framebuffer;
  8831. }
  8832. };
  8833. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8834. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8835. this._currentRenderTarget = null;
  8836. // If MSAA, we need to bitblt back to main texture
  8837. var gl = this._gl;
  8838. if (texture._MSAAFramebuffer) {
  8839. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8840. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8841. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8842. }
  8843. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8844. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8845. gl.generateMipmap(gl.TEXTURE_2D);
  8846. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8847. }
  8848. if (onBeforeUnbind) {
  8849. if (texture._MSAAFramebuffer) {
  8850. // Bind the correct framebuffer
  8851. this.bindUnboundFramebuffer(texture._framebuffer);
  8852. }
  8853. onBeforeUnbind();
  8854. }
  8855. this.bindUnboundFramebuffer(null);
  8856. };
  8857. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8858. if (texture.generateMipMaps) {
  8859. var gl = this._gl;
  8860. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8861. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8862. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8863. }
  8864. };
  8865. Engine.prototype.flushFramebuffer = function () {
  8866. this._gl.flush();
  8867. };
  8868. Engine.prototype.restoreDefaultFramebuffer = function () {
  8869. this._currentRenderTarget = null;
  8870. this.bindUnboundFramebuffer(null);
  8871. this.setViewport(this._cachedViewport);
  8872. this.wipeCaches();
  8873. };
  8874. // VBOs
  8875. Engine.prototype._resetVertexBufferBinding = function () {
  8876. this.bindArrayBuffer(null);
  8877. this._cachedVertexBuffers = null;
  8878. };
  8879. Engine.prototype.createVertexBuffer = function (vertices) {
  8880. var vbo = this._gl.createBuffer();
  8881. this.bindArrayBuffer(vbo);
  8882. if (vertices instanceof Float32Array) {
  8883. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8884. }
  8885. else {
  8886. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8887. }
  8888. this._resetVertexBufferBinding();
  8889. vbo.references = 1;
  8890. return vbo;
  8891. };
  8892. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8893. var vbo = this._gl.createBuffer();
  8894. this.bindArrayBuffer(vbo);
  8895. if (vertices instanceof Float32Array) {
  8896. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8897. }
  8898. else {
  8899. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8900. }
  8901. this._resetVertexBufferBinding();
  8902. vbo.references = 1;
  8903. return vbo;
  8904. };
  8905. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8906. this.bindArrayBuffer(vertexBuffer);
  8907. if (offset === undefined) {
  8908. offset = 0;
  8909. }
  8910. if (count === undefined) {
  8911. if (vertices instanceof Float32Array) {
  8912. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8913. }
  8914. else {
  8915. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8916. }
  8917. }
  8918. else {
  8919. if (vertices instanceof Float32Array) {
  8920. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8921. }
  8922. else {
  8923. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8924. }
  8925. }
  8926. this._resetVertexBufferBinding();
  8927. };
  8928. Engine.prototype._resetIndexBufferBinding = function () {
  8929. this.bindIndexBuffer(null);
  8930. this._cachedIndexBuffer = null;
  8931. };
  8932. Engine.prototype.createIndexBuffer = function (indices) {
  8933. var vbo = this._gl.createBuffer();
  8934. this.bindIndexBuffer(vbo);
  8935. // Check for 32 bits indices
  8936. var arrayBuffer;
  8937. var need32Bits = false;
  8938. if (indices instanceof Uint16Array) {
  8939. arrayBuffer = indices;
  8940. }
  8941. else {
  8942. //check 32 bit support
  8943. if (this._caps.uintIndices) {
  8944. if (indices instanceof Uint32Array) {
  8945. arrayBuffer = indices;
  8946. need32Bits = true;
  8947. }
  8948. else {
  8949. //number[] or Int32Array, check if 32 bit is necessary
  8950. for (var index = 0; index < indices.length; index++) {
  8951. if (indices[index] > 65535) {
  8952. need32Bits = true;
  8953. break;
  8954. }
  8955. }
  8956. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8957. }
  8958. }
  8959. else {
  8960. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8961. arrayBuffer = new Uint16Array(indices);
  8962. }
  8963. }
  8964. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8965. this._resetIndexBufferBinding();
  8966. vbo.references = 1;
  8967. vbo.is32Bits = need32Bits;
  8968. return vbo;
  8969. };
  8970. Engine.prototype.bindArrayBuffer = function (buffer) {
  8971. if (!this._vaoRecordInProgress) {
  8972. this._unBindVertexArrayObject();
  8973. }
  8974. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8975. };
  8976. Engine.prototype.bindIndexBuffer = function (buffer) {
  8977. if (!this._vaoRecordInProgress) {
  8978. this._unBindVertexArrayObject();
  8979. }
  8980. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8981. };
  8982. Engine.prototype.bindBuffer = function (buffer, target) {
  8983. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8984. this._gl.bindBuffer(target, buffer);
  8985. this._currentBoundBuffer[target] = buffer;
  8986. }
  8987. };
  8988. Engine.prototype.updateArrayBuffer = function (data) {
  8989. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8990. };
  8991. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8992. var pointer = this._currentBufferPointers[indx];
  8993. var changed = false;
  8994. if (!pointer) {
  8995. changed = true;
  8996. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8997. }
  8998. else {
  8999. if (pointer.buffer !== buffer) {
  9000. pointer.buffer = buffer;
  9001. changed = true;
  9002. }
  9003. if (pointer.size !== size) {
  9004. pointer.size = size;
  9005. changed = true;
  9006. }
  9007. if (pointer.type !== type) {
  9008. pointer.type = type;
  9009. changed = true;
  9010. }
  9011. if (pointer.normalized !== normalized) {
  9012. pointer.normalized = normalized;
  9013. changed = true;
  9014. }
  9015. if (pointer.stride !== stride) {
  9016. pointer.stride = stride;
  9017. changed = true;
  9018. }
  9019. if (pointer.offset !== offset) {
  9020. pointer.offset = offset;
  9021. changed = true;
  9022. }
  9023. }
  9024. if (changed || this._vaoRecordInProgress) {
  9025. this.bindArrayBuffer(buffer);
  9026. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9027. }
  9028. };
  9029. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9030. if (indexBuffer == null) {
  9031. return;
  9032. }
  9033. if (this._cachedIndexBuffer !== indexBuffer) {
  9034. this._cachedIndexBuffer = indexBuffer;
  9035. this.bindIndexBuffer(indexBuffer);
  9036. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9037. }
  9038. };
  9039. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9040. var attributes = effect.getAttributesNames();
  9041. if (!this._vaoRecordInProgress) {
  9042. this._unBindVertexArrayObject();
  9043. }
  9044. this.unbindAllAttributes();
  9045. for (var index = 0; index < attributes.length; index++) {
  9046. var order = effect.getAttributeLocation(index);
  9047. if (order >= 0) {
  9048. var vertexBuffer = vertexBuffers[attributes[index]];
  9049. if (!vertexBuffer) {
  9050. continue;
  9051. }
  9052. this._gl.enableVertexAttribArray(order);
  9053. if (!this._vaoRecordInProgress) {
  9054. this._vertexAttribArraysEnabled[order] = true;
  9055. }
  9056. var buffer = vertexBuffer.getBuffer();
  9057. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9058. if (vertexBuffer.getIsInstanced()) {
  9059. this._gl.vertexAttribDivisor(order, 1);
  9060. if (!this._vaoRecordInProgress) {
  9061. this._currentInstanceLocations.push(order);
  9062. this._currentInstanceBuffers.push(buffer);
  9063. }
  9064. }
  9065. }
  9066. }
  9067. };
  9068. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9069. var vao = this._gl.createVertexArray();
  9070. this._vaoRecordInProgress = true;
  9071. this._gl.bindVertexArray(vao);
  9072. this._mustWipeVertexAttributes = true;
  9073. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9074. this.bindIndexBuffer(indexBuffer);
  9075. this._vaoRecordInProgress = false;
  9076. this._gl.bindVertexArray(null);
  9077. return vao;
  9078. };
  9079. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9080. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9081. this._cachedVertexArrayObject = vertexArrayObject;
  9082. this._gl.bindVertexArray(vertexArrayObject);
  9083. this._cachedVertexBuffers = null;
  9084. this._cachedIndexBuffer = null;
  9085. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9086. this._mustWipeVertexAttributes = true;
  9087. }
  9088. };
  9089. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9090. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9091. this._cachedVertexBuffers = vertexBuffer;
  9092. this._cachedEffectForVertexBuffers = effect;
  9093. var attributesCount = effect.getAttributesCount();
  9094. this._unBindVertexArrayObject();
  9095. this.unbindAllAttributes();
  9096. var offset = 0;
  9097. for (var index = 0; index < attributesCount; index++) {
  9098. if (index < vertexDeclaration.length) {
  9099. var order = effect.getAttributeLocation(index);
  9100. if (order >= 0) {
  9101. this._gl.enableVertexAttribArray(order);
  9102. this._vertexAttribArraysEnabled[order] = true;
  9103. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9104. }
  9105. offset += vertexDeclaration[index] * 4;
  9106. }
  9107. }
  9108. }
  9109. this._bindIndexBufferWithCache(indexBuffer);
  9110. };
  9111. Engine.prototype._unBindVertexArrayObject = function () {
  9112. if (!this._cachedVertexArrayObject) {
  9113. return;
  9114. }
  9115. this._cachedVertexArrayObject = null;
  9116. this._gl.bindVertexArray(null);
  9117. };
  9118. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9119. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9120. this._cachedVertexBuffers = vertexBuffers;
  9121. this._cachedEffectForVertexBuffers = effect;
  9122. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9123. }
  9124. this._bindIndexBufferWithCache(indexBuffer);
  9125. };
  9126. Engine.prototype.unbindInstanceAttributes = function () {
  9127. var boundBuffer;
  9128. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9129. var instancesBuffer = this._currentInstanceBuffers[i];
  9130. if (boundBuffer != instancesBuffer) {
  9131. boundBuffer = instancesBuffer;
  9132. this.bindArrayBuffer(instancesBuffer);
  9133. }
  9134. var offsetLocation = this._currentInstanceLocations[i];
  9135. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9136. }
  9137. this._currentInstanceBuffers.length = 0;
  9138. this._currentInstanceLocations.length = 0;
  9139. };
  9140. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9141. this._gl.deleteVertexArray(vao);
  9142. };
  9143. Engine.prototype._releaseBuffer = function (buffer) {
  9144. buffer.references--;
  9145. if (buffer.references === 0) {
  9146. this._gl.deleteBuffer(buffer);
  9147. return true;
  9148. }
  9149. return false;
  9150. };
  9151. Engine.prototype.createInstancesBuffer = function (capacity) {
  9152. var buffer = this._gl.createBuffer();
  9153. buffer.capacity = capacity;
  9154. this.bindArrayBuffer(buffer);
  9155. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9156. return buffer;
  9157. };
  9158. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9159. this._gl.deleteBuffer(buffer);
  9160. };
  9161. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9162. this.bindArrayBuffer(instancesBuffer);
  9163. if (data) {
  9164. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9165. }
  9166. if (offsetLocations[0].index !== undefined) {
  9167. var stride = 0;
  9168. for (var i = 0; i < offsetLocations.length; i++) {
  9169. var ai = offsetLocations[i];
  9170. stride += ai.attributeSize * 4;
  9171. }
  9172. for (var i = 0; i < offsetLocations.length; i++) {
  9173. var ai = offsetLocations[i];
  9174. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9175. this._gl.enableVertexAttribArray(ai.index);
  9176. this._vertexAttribArraysEnabled[ai.index] = true;
  9177. }
  9178. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9179. this._gl.vertexAttribDivisor(ai.index, 1);
  9180. this._currentInstanceLocations.push(ai.index);
  9181. this._currentInstanceBuffers.push(instancesBuffer);
  9182. }
  9183. }
  9184. else {
  9185. for (var index = 0; index < 4; index++) {
  9186. var offsetLocation = offsetLocations[index];
  9187. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9188. this._gl.enableVertexAttribArray(offsetLocation);
  9189. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9190. }
  9191. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9192. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9193. this._currentInstanceLocations.push(offsetLocation);
  9194. this._currentInstanceBuffers.push(instancesBuffer);
  9195. }
  9196. }
  9197. };
  9198. Engine.prototype.applyStates = function () {
  9199. this._depthCullingState.apply(this._gl);
  9200. this._stencilState.apply(this._gl);
  9201. this._alphaState.apply(this._gl);
  9202. };
  9203. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9204. // Apply states
  9205. this.applyStates();
  9206. this._drawCalls.addCount(1, false);
  9207. // Render
  9208. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9209. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9210. if (instancesCount) {
  9211. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9212. return;
  9213. }
  9214. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9215. };
  9216. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9217. // Apply states
  9218. this.applyStates();
  9219. this._drawCalls.addCount(1, false);
  9220. if (instancesCount) {
  9221. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9222. return;
  9223. }
  9224. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9225. };
  9226. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9227. // Apply states
  9228. this.applyStates();
  9229. this._drawCalls.addCount(1, false);
  9230. if (instancesCount) {
  9231. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9232. return;
  9233. }
  9234. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9235. };
  9236. // Shaders
  9237. Engine.prototype._releaseEffect = function (effect) {
  9238. if (this._compiledEffects[effect._key]) {
  9239. delete this._compiledEffects[effect._key];
  9240. if (effect.getProgram()) {
  9241. this._gl.deleteProgram(effect.getProgram());
  9242. }
  9243. }
  9244. };
  9245. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9246. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9247. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9248. var name = vertex + "+" + fragment + "@" + defines;
  9249. if (this._compiledEffects[name]) {
  9250. return this._compiledEffects[name];
  9251. }
  9252. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9253. effect._key = name;
  9254. this._compiledEffects[name] = effect;
  9255. return effect;
  9256. };
  9257. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9258. if (uniformsNames === void 0) { uniformsNames = []; }
  9259. if (samplers === void 0) { samplers = []; }
  9260. if (defines === void 0) { defines = ""; }
  9261. return this.createEffect({
  9262. vertex: "particles",
  9263. fragmentElement: fragmentName
  9264. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9265. };
  9266. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9267. context = context || this._gl;
  9268. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9269. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9270. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9271. var shaderProgram = context.createProgram();
  9272. context.attachShader(shaderProgram, vertexShader);
  9273. context.attachShader(shaderProgram, fragmentShader);
  9274. context.linkProgram(shaderProgram);
  9275. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9276. if (!linked) {
  9277. var error = context.getProgramInfoLog(shaderProgram);
  9278. if (error) {
  9279. throw new Error(error);
  9280. }
  9281. }
  9282. context.deleteShader(vertexShader);
  9283. context.deleteShader(fragmentShader);
  9284. return shaderProgram;
  9285. };
  9286. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9287. var results = [];
  9288. for (var index = 0; index < uniformsNames.length; index++) {
  9289. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9290. }
  9291. return results;
  9292. };
  9293. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9294. var results = [];
  9295. for (var index = 0; index < attributesNames.length; index++) {
  9296. try {
  9297. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9298. }
  9299. catch (e) {
  9300. results.push(-1);
  9301. }
  9302. }
  9303. return results;
  9304. };
  9305. Engine.prototype.enableEffect = function (effect) {
  9306. // Use program
  9307. this.setProgram(effect.getProgram());
  9308. this._currentEffect = effect;
  9309. if (effect.onBind) {
  9310. effect.onBind(effect);
  9311. }
  9312. };
  9313. Engine.prototype.setIntArray = function (uniform, array) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform1iv(uniform, array);
  9317. };
  9318. Engine.prototype.setIntArray2 = function (uniform, array) {
  9319. if (!uniform || array.length % 2 !== 0)
  9320. return;
  9321. this._gl.uniform2iv(uniform, array);
  9322. };
  9323. Engine.prototype.setIntArray3 = function (uniform, array) {
  9324. if (!uniform || array.length % 3 !== 0)
  9325. return;
  9326. this._gl.uniform3iv(uniform, array);
  9327. };
  9328. Engine.prototype.setIntArray4 = function (uniform, array) {
  9329. if (!uniform || array.length % 4 !== 0)
  9330. return;
  9331. this._gl.uniform4iv(uniform, array);
  9332. };
  9333. Engine.prototype.setFloatArray = function (uniform, array) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform1fv(uniform, array);
  9337. };
  9338. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9339. if (!uniform || array.length % 2 !== 0)
  9340. return;
  9341. this._gl.uniform2fv(uniform, array);
  9342. };
  9343. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9344. if (!uniform || array.length % 3 !== 0)
  9345. return;
  9346. this._gl.uniform3fv(uniform, array);
  9347. };
  9348. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9349. if (!uniform || array.length % 4 !== 0)
  9350. return;
  9351. this._gl.uniform4fv(uniform, array);
  9352. };
  9353. Engine.prototype.setArray = function (uniform, array) {
  9354. if (!uniform)
  9355. return;
  9356. this._gl.uniform1fv(uniform, array);
  9357. };
  9358. Engine.prototype.setArray2 = function (uniform, array) {
  9359. if (!uniform || array.length % 2 !== 0)
  9360. return;
  9361. this._gl.uniform2fv(uniform, array);
  9362. };
  9363. Engine.prototype.setArray3 = function (uniform, array) {
  9364. if (!uniform || array.length % 3 !== 0)
  9365. return;
  9366. this._gl.uniform3fv(uniform, array);
  9367. };
  9368. Engine.prototype.setArray4 = function (uniform, array) {
  9369. if (!uniform || array.length % 4 !== 0)
  9370. return;
  9371. this._gl.uniform4fv(uniform, array);
  9372. };
  9373. Engine.prototype.setMatrices = function (uniform, matrices) {
  9374. if (!uniform)
  9375. return;
  9376. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9377. };
  9378. Engine.prototype.setMatrix = function (uniform, matrix) {
  9379. if (!uniform)
  9380. return;
  9381. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9382. };
  9383. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9384. if (!uniform)
  9385. return;
  9386. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9387. };
  9388. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9389. if (!uniform)
  9390. return;
  9391. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9392. };
  9393. Engine.prototype.setFloat = function (uniform, value) {
  9394. if (!uniform)
  9395. return;
  9396. this._gl.uniform1f(uniform, value);
  9397. };
  9398. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9399. if (!uniform)
  9400. return;
  9401. this._gl.uniform2f(uniform, x, y);
  9402. };
  9403. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9404. if (!uniform)
  9405. return;
  9406. this._gl.uniform3f(uniform, x, y, z);
  9407. };
  9408. Engine.prototype.setBool = function (uniform, bool) {
  9409. if (!uniform)
  9410. return;
  9411. this._gl.uniform1i(uniform, bool);
  9412. };
  9413. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9414. if (!uniform)
  9415. return;
  9416. this._gl.uniform4f(uniform, x, y, z, w);
  9417. };
  9418. Engine.prototype.setColor3 = function (uniform, color3) {
  9419. if (!uniform)
  9420. return;
  9421. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9422. };
  9423. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9427. };
  9428. // States
  9429. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9430. if (zOffset === void 0) { zOffset = 0; }
  9431. if (reverseSide === void 0) { reverseSide = false; }
  9432. // Culling
  9433. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9434. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9435. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9436. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9437. if (culling) {
  9438. this._depthCullingState.cullFace = cullFace;
  9439. this._depthCullingState.cull = true;
  9440. }
  9441. else {
  9442. this._depthCullingState.cull = false;
  9443. }
  9444. }
  9445. // Z offset
  9446. this._depthCullingState.zOffset = zOffset;
  9447. };
  9448. Engine.prototype.setDepthBuffer = function (enable) {
  9449. this._depthCullingState.depthTest = enable;
  9450. };
  9451. Engine.prototype.getDepthWrite = function () {
  9452. return this._depthCullingState.depthMask;
  9453. };
  9454. Engine.prototype.setDepthWrite = function (enable) {
  9455. this._depthCullingState.depthMask = enable;
  9456. };
  9457. Engine.prototype.setColorWrite = function (enable) {
  9458. this._gl.colorMask(enable, enable, enable, enable);
  9459. };
  9460. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9461. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9462. if (this._alphaMode === mode) {
  9463. return;
  9464. }
  9465. switch (mode) {
  9466. case Engine.ALPHA_DISABLE:
  9467. this._alphaState.alphaBlend = false;
  9468. break;
  9469. case Engine.ALPHA_PREMULTIPLIED:
  9470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9471. this._alphaState.alphaBlend = true;
  9472. break;
  9473. case Engine.ALPHA_COMBINE:
  9474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9475. this._alphaState.alphaBlend = true;
  9476. break;
  9477. case Engine.ALPHA_ONEONE:
  9478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9479. this._alphaState.alphaBlend = true;
  9480. break;
  9481. case Engine.ALPHA_ADD:
  9482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9483. this._alphaState.alphaBlend = true;
  9484. break;
  9485. case Engine.ALPHA_SUBTRACT:
  9486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9487. this._alphaState.alphaBlend = true;
  9488. break;
  9489. case Engine.ALPHA_MULTIPLY:
  9490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9491. this._alphaState.alphaBlend = true;
  9492. break;
  9493. case Engine.ALPHA_MAXIMIZED:
  9494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9495. this._alphaState.alphaBlend = true;
  9496. break;
  9497. }
  9498. if (!noDepthWriteChange) {
  9499. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9500. }
  9501. this._alphaMode = mode;
  9502. };
  9503. Engine.prototype.getAlphaMode = function () {
  9504. return this._alphaMode;
  9505. };
  9506. Engine.prototype.setAlphaTesting = function (enable) {
  9507. this._alphaTest = enable;
  9508. };
  9509. Engine.prototype.getAlphaTesting = function () {
  9510. return this._alphaTest;
  9511. };
  9512. // Textures
  9513. Engine.prototype.wipeCaches = function () {
  9514. if (this.preventCacheWipeBetweenFrames) {
  9515. return;
  9516. }
  9517. this.resetTextureCache();
  9518. this._currentEffect = null;
  9519. this._stencilState.reset();
  9520. this._depthCullingState.reset();
  9521. this.setDepthFunctionToLessOrEqual();
  9522. this._alphaState.reset();
  9523. this._cachedVertexBuffers = null;
  9524. this._cachedIndexBuffer = null;
  9525. this._cachedEffectForVertexBuffers = null;
  9526. this._unBindVertexArrayObject();
  9527. this.bindIndexBuffer(null);
  9528. this.bindArrayBuffer(null);
  9529. };
  9530. /**
  9531. * Set the compressed texture format to use, based on the formats you have, and the formats
  9532. * supported by the hardware / browser.
  9533. *
  9534. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9535. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9536. * to API arguments needed to compressed textures. This puts the burden on the container
  9537. * generator to house the arcane code for determining these for current & future formats.
  9538. *
  9539. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9540. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9541. *
  9542. * Note: The result of this call is not taken into account when a texture is base64.
  9543. *
  9544. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9545. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9546. *
  9547. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9548. * @returns The extension selected.
  9549. */
  9550. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9551. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9552. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9553. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9554. return this._textureFormatInUse = this._texturesSupported[i];
  9555. }
  9556. }
  9557. }
  9558. // actively set format to nothing, to allow this to be called more than once
  9559. // and possibly fail the 2nd time
  9560. return this._textureFormatInUse = null;
  9561. };
  9562. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9563. var _this = this;
  9564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9565. if (onLoad === void 0) { onLoad = null; }
  9566. if (onError === void 0) { onError = null; }
  9567. if (buffer === void 0) { buffer = null; }
  9568. var texture = fallBack ? fallBack : this._gl.createTexture();
  9569. var extension;
  9570. var isKTX = false;
  9571. var fromData = false;
  9572. var url = String(urlArg);
  9573. if (url.substr(0, 5) === "data:") {
  9574. fromData = true;
  9575. }
  9576. if (!fromData) {
  9577. var lastDot = url.lastIndexOf('.');
  9578. extension = url.substring(lastDot).toLowerCase();
  9579. if (this._textureFormatInUse && !fromData && !fallBack) {
  9580. extension = this._textureFormatInUse;
  9581. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9582. isKTX = true;
  9583. }
  9584. }
  9585. else {
  9586. var oldUrl = url;
  9587. fromData = oldUrl.split(':');
  9588. url = oldUrl;
  9589. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9590. }
  9591. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9592. var isTGA = (extension === ".tga");
  9593. scene._addPendingData(texture);
  9594. texture.url = url;
  9595. texture.noMipmap = noMipmap;
  9596. texture.references = 1;
  9597. texture.samplingMode = samplingMode;
  9598. texture.onLoadedCallbacks = [];
  9599. if (onLoad) {
  9600. texture.onLoadedCallbacks.push(onLoad);
  9601. }
  9602. if (!fallBack)
  9603. this._loadedTexturesCache.push(texture);
  9604. var onerror = function () {
  9605. scene._removePendingData(texture);
  9606. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9607. if (isKTX) {
  9608. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9609. }
  9610. else if (onError) {
  9611. onError();
  9612. }
  9613. };
  9614. var callback;
  9615. if (isKTX || isTGA || isDDS) {
  9616. if (isKTX) {
  9617. callback = function (data) {
  9618. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9619. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9620. ktx.uploadLevels(_this._gl, !noMipmap);
  9621. }, samplingMode);
  9622. };
  9623. }
  9624. else if (isTGA) {
  9625. callback = function (arrayBuffer) {
  9626. var data = new Uint8Array(arrayBuffer);
  9627. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9628. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9629. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9630. }, samplingMode);
  9631. };
  9632. }
  9633. else if (isDDS) {
  9634. callback = function (data) {
  9635. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9636. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9637. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9638. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9639. }, samplingMode);
  9640. };
  9641. }
  9642. if (!(fromData instanceof Array))
  9643. BABYLON.Tools.LoadFile(url, function (data) {
  9644. callback(data);
  9645. }, null, scene.database, true, onerror);
  9646. else
  9647. callback(buffer);
  9648. }
  9649. else {
  9650. var onload = function (img) {
  9651. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9652. var isPot = (img.width === potWidth && img.height === potHeight);
  9653. if (!isPot) {
  9654. _this._prepareWorkingCanvas();
  9655. _this._workingCanvas.width = potWidth;
  9656. _this._workingCanvas.height = potHeight;
  9657. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9658. _this._workingContext.imageSmoothingEnabled = false;
  9659. _this._workingContext.mozImageSmoothingEnabled = false;
  9660. _this._workingContext.oImageSmoothingEnabled = false;
  9661. _this._workingContext.webkitImageSmoothingEnabled = false;
  9662. _this._workingContext.msImageSmoothingEnabled = false;
  9663. }
  9664. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9665. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9666. _this._workingContext.imageSmoothingEnabled = true;
  9667. _this._workingContext.mozImageSmoothingEnabled = true;
  9668. _this._workingContext.oImageSmoothingEnabled = true;
  9669. _this._workingContext.webkitImageSmoothingEnabled = true;
  9670. _this._workingContext.msImageSmoothingEnabled = true;
  9671. }
  9672. }
  9673. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9674. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9675. }, samplingMode);
  9676. };
  9677. if (!(fromData instanceof Array))
  9678. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9679. else
  9680. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9681. }
  9682. return texture;
  9683. };
  9684. Engine.prototype._getInternalFormat = function (format) {
  9685. var internalFormat = this._gl.RGBA;
  9686. switch (format) {
  9687. case Engine.TEXTUREFORMAT_ALPHA:
  9688. internalFormat = this._gl.ALPHA;
  9689. break;
  9690. case Engine.TEXTUREFORMAT_LUMINANCE:
  9691. internalFormat = this._gl.LUMINANCE;
  9692. break;
  9693. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9694. internalFormat = this._gl.LUMINANCE_ALPHA;
  9695. break;
  9696. case Engine.TEXTUREFORMAT_RGB:
  9697. internalFormat = this._gl.RGB;
  9698. break;
  9699. case Engine.TEXTUREFORMAT_RGBA:
  9700. internalFormat = this._gl.RGBA;
  9701. break;
  9702. }
  9703. return internalFormat;
  9704. };
  9705. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9706. if (compression === void 0) { compression = null; }
  9707. var internalFormat = this._getInternalFormat(format);
  9708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9709. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9710. if (texture._width % 4 !== 0) {
  9711. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9712. }
  9713. if (compression) {
  9714. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9715. }
  9716. else {
  9717. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9718. }
  9719. if (texture.generateMipMaps) {
  9720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9721. }
  9722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9723. this.resetTextureCache();
  9724. texture.isReady = true;
  9725. };
  9726. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9727. if (compression === void 0) { compression = null; }
  9728. var texture = this._gl.createTexture();
  9729. texture._baseWidth = width;
  9730. texture._baseHeight = height;
  9731. texture._width = width;
  9732. texture._height = height;
  9733. texture.references = 1;
  9734. this.updateRawTexture(texture, data, format, invertY, compression);
  9735. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9736. // Filters
  9737. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9738. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9739. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9740. if (generateMipMaps) {
  9741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9742. }
  9743. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9744. texture.samplingMode = samplingMode;
  9745. this._loadedTexturesCache.push(texture);
  9746. return texture;
  9747. };
  9748. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9749. var texture = this._gl.createTexture();
  9750. texture._baseWidth = width;
  9751. texture._baseHeight = height;
  9752. if (generateMipMaps) {
  9753. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9754. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9755. }
  9756. this.resetTextureCache();
  9757. texture._width = width;
  9758. texture._height = height;
  9759. texture.isReady = false;
  9760. texture.generateMipMaps = generateMipMaps;
  9761. texture.references = 1;
  9762. texture.samplingMode = samplingMode;
  9763. this.updateTextureSamplingMode(samplingMode, texture);
  9764. this._loadedTexturesCache.push(texture);
  9765. return texture;
  9766. };
  9767. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9768. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9769. if (texture.isCube) {
  9770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9771. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9772. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9773. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9774. }
  9775. else {
  9776. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9778. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9779. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9780. }
  9781. texture.samplingMode = samplingMode;
  9782. };
  9783. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9784. if (premulAlpha === void 0) { premulAlpha = false; }
  9785. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9786. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9787. if (premulAlpha) {
  9788. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9789. }
  9790. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9791. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9792. if (texture.generateMipMaps) {
  9793. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9794. }
  9795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9796. if (premulAlpha) {
  9797. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9798. }
  9799. this.resetTextureCache();
  9800. texture.isReady = true;
  9801. };
  9802. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9803. if (texture._isDisabled) {
  9804. return;
  9805. }
  9806. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9807. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9808. try {
  9809. // Testing video texture support
  9810. if (this._videoTextureSupported === undefined) {
  9811. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9812. if (this._gl.getError() !== 0) {
  9813. this._videoTextureSupported = false;
  9814. }
  9815. else {
  9816. this._videoTextureSupported = true;
  9817. }
  9818. }
  9819. // Copy video through the current working canvas if video texture is not supported
  9820. if (!this._videoTextureSupported) {
  9821. if (!texture._workingCanvas) {
  9822. texture._workingCanvas = document.createElement("canvas");
  9823. texture._workingContext = texture._workingCanvas.getContext("2d");
  9824. texture._workingCanvas.width = texture._width;
  9825. texture._workingCanvas.height = texture._height;
  9826. }
  9827. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9828. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9829. }
  9830. else {
  9831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9832. }
  9833. if (texture.generateMipMaps) {
  9834. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9835. }
  9836. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9837. this.resetTextureCache();
  9838. texture.isReady = true;
  9839. }
  9840. catch (ex) {
  9841. // Something unexpected
  9842. // Let's disable the texture
  9843. texture._isDisabled = true;
  9844. }
  9845. };
  9846. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9847. // old version had a "generateMipMaps" arg instead of options.
  9848. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9849. // in the same way, generateDepthBuffer is defaulted to true
  9850. var generateMipMaps = false;
  9851. var generateDepthBuffer = true;
  9852. var generateStencilBuffer = false;
  9853. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9854. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9855. if (options !== undefined) {
  9856. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9857. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9858. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9859. type = options.type === undefined ? type : options.type;
  9860. if (options.samplingMode !== undefined) {
  9861. samplingMode = options.samplingMode;
  9862. }
  9863. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9864. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9865. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9866. }
  9867. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9868. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9869. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9870. }
  9871. }
  9872. var gl = this._gl;
  9873. var texture = gl.createTexture();
  9874. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9875. var width = size.width || size;
  9876. var height = size.height || size;
  9877. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9878. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9879. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9880. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9881. }
  9882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9886. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9887. // Create the framebuffer
  9888. var framebuffer = gl.createFramebuffer();
  9889. this.bindUnboundFramebuffer(framebuffer);
  9890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9891. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9892. if (generateMipMaps) {
  9893. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9894. }
  9895. // Unbind
  9896. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9897. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9898. this.bindUnboundFramebuffer(null);
  9899. texture._framebuffer = framebuffer;
  9900. texture._baseWidth = width;
  9901. texture._baseHeight = height;
  9902. texture._width = width;
  9903. texture._height = height;
  9904. texture.isReady = true;
  9905. texture.samples = 1;
  9906. texture.generateMipMaps = generateMipMaps;
  9907. texture.references = 1;
  9908. texture.samplingMode = samplingMode;
  9909. texture.type = type;
  9910. texture._generateDepthBuffer = generateDepthBuffer;
  9911. texture._generateStencilBuffer = generateStencilBuffer;
  9912. this.resetTextureCache();
  9913. this._loadedTexturesCache.push(texture);
  9914. return texture;
  9915. };
  9916. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9917. if (samples === void 0) { samples = 1; }
  9918. var depthStencilBuffer = null;
  9919. var gl = this._gl;
  9920. // Create the depth/stencil buffer
  9921. if (generateStencilBuffer) {
  9922. depthStencilBuffer = gl.createRenderbuffer();
  9923. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9924. if (samples > 1) {
  9925. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9926. }
  9927. else {
  9928. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9929. }
  9930. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9931. }
  9932. else if (generateDepthBuffer) {
  9933. depthStencilBuffer = gl.createRenderbuffer();
  9934. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9935. if (samples > 1) {
  9936. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9937. }
  9938. else {
  9939. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9940. }
  9941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9942. }
  9943. return depthStencilBuffer;
  9944. };
  9945. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9946. if (this.webGLVersion < 2) {
  9947. return 1;
  9948. }
  9949. if (texture.samples === samples) {
  9950. return samples;
  9951. }
  9952. var gl = this._gl;
  9953. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9954. // Dispose previous render buffers
  9955. if (texture._depthStencilBuffer) {
  9956. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9957. }
  9958. if (texture._MSAAFramebuffer) {
  9959. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9960. }
  9961. if (texture._MSAARenderBuffer) {
  9962. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9963. }
  9964. if (samples > 1) {
  9965. texture._MSAAFramebuffer = gl.createFramebuffer();
  9966. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9967. var colorRenderbuffer = gl.createRenderbuffer();
  9968. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9969. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9970. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9971. texture._MSAARenderBuffer = colorRenderbuffer;
  9972. }
  9973. else {
  9974. this.bindUnboundFramebuffer(texture._framebuffer);
  9975. }
  9976. texture.samples = samples;
  9977. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9978. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9979. this.bindUnboundFramebuffer(null);
  9980. return samples;
  9981. };
  9982. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9983. var gl = this._gl;
  9984. var texture = gl.createTexture();
  9985. var generateMipMaps = true;
  9986. var generateDepthBuffer = true;
  9987. var generateStencilBuffer = false;
  9988. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9989. if (options !== undefined) {
  9990. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9991. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9992. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9993. if (options.samplingMode !== undefined) {
  9994. samplingMode = options.samplingMode;
  9995. }
  9996. }
  9997. texture.isCube = true;
  9998. texture.references = 1;
  9999. texture.generateMipMaps = generateMipMaps;
  10000. texture.references = 1;
  10001. texture.samples = 1;
  10002. texture.samplingMode = samplingMode;
  10003. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10005. for (var face = 0; face < 6; face++) {
  10006. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10007. }
  10008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10009. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10012. // Create the framebuffer
  10013. var framebuffer = gl.createFramebuffer();
  10014. this.bindUnboundFramebuffer(framebuffer);
  10015. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10016. // Mipmaps
  10017. if (texture.generateMipMaps) {
  10018. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10019. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10020. }
  10021. // Unbind
  10022. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10023. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10024. this.bindUnboundFramebuffer(null);
  10025. texture._framebuffer = framebuffer;
  10026. texture._width = size;
  10027. texture._height = size;
  10028. texture.isReady = true;
  10029. this.resetTextureCache();
  10030. this._loadedTexturesCache.push(texture);
  10031. return texture;
  10032. };
  10033. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10034. var _this = this;
  10035. if (onLoad === void 0) { onLoad = null; }
  10036. if (onError === void 0) { onError = null; }
  10037. var gl = this._gl;
  10038. var texture = gl.createTexture();
  10039. texture.isCube = true;
  10040. texture.url = rootUrl;
  10041. texture.references = 1;
  10042. texture.onLoadedCallbacks = [];
  10043. var isKTX = false;
  10044. var lastDot = rootUrl.lastIndexOf('.');
  10045. var extension = rootUrl.substring(lastDot).toLowerCase();
  10046. if (this._textureFormatInUse) {
  10047. extension = this._textureFormatInUse;
  10048. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10049. isKTX = true;
  10050. }
  10051. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10052. if (isKTX) {
  10053. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10054. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10055. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10057. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10058. ktx.uploadLevels(_this._gl, !noMipmap);
  10059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10064. _this.resetTextureCache();
  10065. texture._width = ktx.pixelWidth;
  10066. texture._height = ktx.pixelHeight;
  10067. texture.isReady = true;
  10068. }, null, null, true, onError);
  10069. }
  10070. else if (isDDS) {
  10071. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10072. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10073. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10074. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10075. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10076. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10077. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10078. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10079. }
  10080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10084. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10085. _this.resetTextureCache();
  10086. texture._width = info.width;
  10087. texture._height = info.height;
  10088. texture.isReady = true;
  10089. }, null, null, true, onError);
  10090. }
  10091. else {
  10092. cascadeLoad(rootUrl, scene, function (imgs) {
  10093. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10094. var height = width;
  10095. _this._prepareWorkingCanvas();
  10096. _this._workingCanvas.width = width;
  10097. _this._workingCanvas.height = height;
  10098. var faces = [
  10099. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10100. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10101. ];
  10102. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10104. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10105. for (var index = 0; index < faces.length; index++) {
  10106. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10107. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10108. }
  10109. if (!noMipmap) {
  10110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10111. }
  10112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10116. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10117. _this.resetTextureCache();
  10118. texture._width = width;
  10119. texture._height = height;
  10120. texture.isReady = true;
  10121. texture.onLoadedCallbacks.forEach(function (callback) {
  10122. callback();
  10123. });
  10124. if (onLoad) {
  10125. onLoad();
  10126. }
  10127. }, files, onError);
  10128. }
  10129. this._loadedTexturesCache.push(texture);
  10130. return texture;
  10131. };
  10132. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10133. texture._width = width;
  10134. texture._height = height;
  10135. texture._size = width * height;
  10136. texture._baseWidth = width;
  10137. texture._baseHeight = height;
  10138. };
  10139. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10140. var _this = this;
  10141. if (onLoad === void 0) { onLoad = null; }
  10142. if (onError === void 0) { onError = null; }
  10143. var gl = this._gl;
  10144. var texture = gl.createTexture();
  10145. scene._addPendingData(texture);
  10146. texture.isCube = true;
  10147. texture.references = 1;
  10148. texture.url = url;
  10149. var textureType = gl.UNSIGNED_BYTE;
  10150. if (type === Engine.TEXTURETYPE_FLOAT) {
  10151. textureType = gl.FLOAT;
  10152. }
  10153. var internalFormat = this._getInternalFormat(format);
  10154. var needConversion = false;
  10155. if (internalFormat === gl.RGB) {
  10156. internalFormat = gl.RGBA;
  10157. needConversion = true;
  10158. }
  10159. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10160. var width = size;
  10161. var height = width;
  10162. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10163. texture._width = width;
  10164. texture._height = height;
  10165. var onerror = function () {
  10166. scene._removePendingData(texture);
  10167. if (onError) {
  10168. onError();
  10169. }
  10170. };
  10171. var internalCallback = function (data) {
  10172. var rgbeDataArrays = callback(data);
  10173. var facesIndex = [
  10174. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10175. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10176. ];
  10177. width = texture._width;
  10178. height = texture._height;
  10179. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10180. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10182. if (mipmmapGenerator) {
  10183. var arrayTemp = [];
  10184. // Data are known to be in +X +Y +Z -X -Y -Z
  10185. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10186. arrayTemp.push(rgbeDataArrays[0]); // +X
  10187. arrayTemp.push(rgbeDataArrays[3]); // -X
  10188. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10189. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10190. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10191. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10192. var mipData = mipmmapGenerator(arrayTemp);
  10193. // mipData is order in +X -X +Y -Y +Z -Z
  10194. var mipFaces = [0, 2, 4, 1, 3, 5];
  10195. for (var level = 0; level < mipData.length; level++) {
  10196. var mipSize = width >> level;
  10197. for (var mipIndex in mipFaces) {
  10198. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10199. if (needConversion) {
  10200. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10201. }
  10202. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10203. }
  10204. }
  10205. }
  10206. else {
  10207. // Data are known to be in +X +Y +Z -X -Y -Z
  10208. for (var index = 0; index < facesIndex.length; index++) {
  10209. var faceData = rgbeDataArrays[index];
  10210. if (needConversion) {
  10211. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10212. }
  10213. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10214. }
  10215. if (!noMipmap && isPot) {
  10216. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10217. }
  10218. else {
  10219. noMipmap = true;
  10220. }
  10221. }
  10222. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10225. }
  10226. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10229. }
  10230. else {
  10231. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10233. }
  10234. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10237. texture.isReady = true;
  10238. _this.resetTextureCache();
  10239. scene._removePendingData(texture);
  10240. if (onLoad) {
  10241. onLoad();
  10242. }
  10243. };
  10244. BABYLON.Tools.LoadFile(url, function (data) {
  10245. internalCallback(data);
  10246. }, onerror, scene.database, true);
  10247. return texture;
  10248. };
  10249. ;
  10250. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10251. // Create new RGBA data container.
  10252. var rgbaData;
  10253. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10254. rgbaData = new Float32Array(width * height * 4);
  10255. }
  10256. else {
  10257. rgbaData = new Uint32Array(width * height * 4);
  10258. }
  10259. // Convert each pixel.
  10260. for (var x = 0; x < width; x++) {
  10261. for (var y = 0; y < height; y++) {
  10262. var index = (y * width + x) * 3;
  10263. var newIndex = (y * width + x) * 4;
  10264. // Map Old Value to new value.
  10265. rgbaData[newIndex + 0] = rgbData[index + 0];
  10266. rgbaData[newIndex + 1] = rgbData[index + 1];
  10267. rgbaData[newIndex + 2] = rgbData[index + 2];
  10268. // Add fully opaque alpha channel.
  10269. rgbaData[newIndex + 3] = 1;
  10270. }
  10271. }
  10272. return rgbaData;
  10273. };
  10274. Engine.prototype._releaseTexture = function (texture) {
  10275. var gl = this._gl;
  10276. if (texture._framebuffer) {
  10277. gl.deleteFramebuffer(texture._framebuffer);
  10278. }
  10279. if (texture._depthStencilBuffer) {
  10280. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10281. }
  10282. if (texture._MSAAFramebuffer) {
  10283. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10284. }
  10285. if (texture._MSAARenderBuffer) {
  10286. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10287. }
  10288. gl.deleteTexture(texture);
  10289. // Unbind channels
  10290. this.unbindAllTextures();
  10291. var index = this._loadedTexturesCache.indexOf(texture);
  10292. if (index !== -1) {
  10293. this._loadedTexturesCache.splice(index, 1);
  10294. }
  10295. };
  10296. Engine.prototype.setProgram = function (program) {
  10297. if (this._currentProgram !== program) {
  10298. this._gl.useProgram(program);
  10299. this._currentProgram = program;
  10300. }
  10301. };
  10302. Engine.prototype.bindSamplers = function (effect) {
  10303. this.setProgram(effect.getProgram());
  10304. var samplers = effect.getSamplers();
  10305. for (var index = 0; index < samplers.length; index++) {
  10306. var uniform = effect.getUniform(samplers[index]);
  10307. this._gl.uniform1i(uniform, index);
  10308. }
  10309. this._currentEffect = null;
  10310. };
  10311. Engine.prototype.activateTexture = function (texture) {
  10312. if (this._activeTexture !== texture) {
  10313. this._gl.activeTexture(texture);
  10314. this._activeTexture = texture;
  10315. }
  10316. };
  10317. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10318. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10319. this._gl.bindTexture(target, texture);
  10320. this._activeTexturesCache[this._activeTexture] = texture;
  10321. }
  10322. };
  10323. Engine.prototype._bindTexture = function (channel, texture) {
  10324. if (channel < 0) {
  10325. return;
  10326. }
  10327. this.activateTexture(this._gl.TEXTURE0 + channel);
  10328. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10329. };
  10330. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10331. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10332. };
  10333. Engine.prototype.unbindAllTextures = function () {
  10334. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10335. this.activateTexture(this._gl["TEXTURE" + channel]);
  10336. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10337. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10338. }
  10339. };
  10340. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10341. if (channel < 0) {
  10342. return;
  10343. }
  10344. this._gl.uniform1i(uniform, channel);
  10345. this._setTexture(channel, texture);
  10346. };
  10347. Engine.prototype._setTexture = function (channel, texture) {
  10348. // Not ready?
  10349. if (!texture || !texture.isReady()) {
  10350. if (this._activeTexturesCache[channel] != null) {
  10351. this.activateTexture(this._gl["TEXTURE" + channel]);
  10352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10353. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10354. }
  10355. return;
  10356. }
  10357. // Video
  10358. var alreadyActivated = false;
  10359. if (texture instanceof BABYLON.VideoTexture) {
  10360. this.activateTexture(this._gl["TEXTURE" + channel]);
  10361. alreadyActivated = true;
  10362. texture.update();
  10363. }
  10364. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10365. texture.delayLoad();
  10366. return;
  10367. }
  10368. var internalTexture = texture.getInternalTexture();
  10369. if (this._activeTexturesCache[channel] === internalTexture) {
  10370. return;
  10371. }
  10372. if (!alreadyActivated) {
  10373. this.activateTexture(this._gl["TEXTURE" + channel]);
  10374. }
  10375. if (internalTexture.isCube) {
  10376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10377. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10378. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10379. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10380. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10381. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10383. }
  10384. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10385. }
  10386. else {
  10387. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10388. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10389. internalTexture._cachedWrapU = texture.wrapU;
  10390. switch (texture.wrapU) {
  10391. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10393. break;
  10394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10396. break;
  10397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10399. break;
  10400. }
  10401. }
  10402. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10403. internalTexture._cachedWrapV = texture.wrapV;
  10404. switch (texture.wrapV) {
  10405. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10407. break;
  10408. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10410. break;
  10411. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10413. break;
  10414. }
  10415. }
  10416. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10417. }
  10418. };
  10419. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10420. if (channel < 0) {
  10421. return;
  10422. }
  10423. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10424. this._textureUnits = new Int32Array(textures.length);
  10425. }
  10426. for (var i = 0; i < textures.length; i++) {
  10427. this._textureUnits[i] = channel + i;
  10428. }
  10429. this._gl.uniform1iv(uniform, this._textureUnits);
  10430. for (var index = 0; index < textures.length; index++) {
  10431. this._setTexture(channel + index, textures[index]);
  10432. }
  10433. };
  10434. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10435. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10436. var value = texture.anisotropicFilteringLevel;
  10437. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10438. value = 1;
  10439. }
  10440. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10441. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10442. texture._cachedAnisotropicFilteringLevel = value;
  10443. }
  10444. };
  10445. Engine.prototype.readPixels = function (x, y, width, height) {
  10446. var data = new Uint8Array(height * width * 4);
  10447. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10448. return data;
  10449. };
  10450. /**
  10451. * Add an externaly attached data from its key.
  10452. * This method call will fail and return false, if such key already exists.
  10453. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10454. * @param key the unique key that identifies the data
  10455. * @param data the data object to associate to the key for this Engine instance
  10456. * @return true if no such key were already present and the data was added successfully, false otherwise
  10457. */
  10458. Engine.prototype.addExternalData = function (key, data) {
  10459. return this._externalData.add(key, data);
  10460. };
  10461. /**
  10462. * Get an externaly attached data from its key
  10463. * @param key the unique key that identifies the data
  10464. * @return the associated data, if present (can be null), or undefined if not present
  10465. */
  10466. Engine.prototype.getExternalData = function (key) {
  10467. return this._externalData.get(key);
  10468. };
  10469. /**
  10470. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10471. * @param key the unique key that identifies the data
  10472. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10473. * @return the associated data, can be null if the factory returned null.
  10474. */
  10475. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10476. return this._externalData.getOrAddWithFactory(key, factory);
  10477. };
  10478. /**
  10479. * Remove an externaly attached data from the Engine instance
  10480. * @param key the unique key that identifies the data
  10481. * @return true if the data was successfully removed, false if it doesn't exist
  10482. */
  10483. Engine.prototype.removeExternalData = function (key) {
  10484. return this._externalData.remove(key);
  10485. };
  10486. Engine.prototype.releaseInternalTexture = function (texture) {
  10487. if (!texture) {
  10488. return;
  10489. }
  10490. texture.references--;
  10491. // Final reference ?
  10492. if (texture.references === 0) {
  10493. var texturesCache = this.getLoadedTexturesCache();
  10494. var index = texturesCache.indexOf(texture);
  10495. if (index > -1) {
  10496. texturesCache.splice(index, 1);
  10497. }
  10498. this._releaseTexture(texture);
  10499. }
  10500. };
  10501. Engine.prototype.unbindAllAttributes = function () {
  10502. if (this._mustWipeVertexAttributes) {
  10503. this._mustWipeVertexAttributes = false;
  10504. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10505. this._gl.disableVertexAttribArray(i);
  10506. this._vertexAttribArraysEnabled[i] = false;
  10507. this._currentBufferPointers[i] = null;
  10508. }
  10509. return;
  10510. }
  10511. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10512. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10513. continue;
  10514. }
  10515. this._gl.disableVertexAttribArray(i);
  10516. this._vertexAttribArraysEnabled[i] = false;
  10517. this._currentBufferPointers[i] = null;
  10518. }
  10519. };
  10520. // Dispose
  10521. Engine.prototype.dispose = function () {
  10522. this.hideLoadingUI();
  10523. this.stopRenderLoop();
  10524. // Release scenes
  10525. while (this.scenes.length) {
  10526. this.scenes[0].dispose();
  10527. }
  10528. // Release audio engine
  10529. Engine.audioEngine.dispose();
  10530. // Release effects
  10531. for (var name in this._compiledEffects) {
  10532. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10533. }
  10534. // Unbind
  10535. this.unbindAllAttributes();
  10536. this._gl = null;
  10537. //WebVR
  10538. this.disableVR();
  10539. // Events
  10540. window.removeEventListener("blur", this._onBlur);
  10541. window.removeEventListener("focus", this._onFocus);
  10542. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10543. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10544. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10545. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10546. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10547. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10548. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10549. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10550. // Remove from Instances
  10551. var index = Engine.Instances.indexOf(this);
  10552. if (index >= 0) {
  10553. Engine.Instances.splice(index, 1);
  10554. }
  10555. };
  10556. // Loading screen
  10557. Engine.prototype.displayLoadingUI = function () {
  10558. this._loadingScreen.displayLoadingUI();
  10559. };
  10560. Engine.prototype.hideLoadingUI = function () {
  10561. this._loadingScreen.hideLoadingUI();
  10562. };
  10563. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10564. get: function () {
  10565. return this._loadingScreen;
  10566. },
  10567. set: function (loadingScreen) {
  10568. this._loadingScreen = loadingScreen;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10574. set: function (text) {
  10575. this._loadingScreen.loadingUIText = text;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10581. set: function (color) {
  10582. this._loadingScreen.loadingUIBackgroundColor = color;
  10583. },
  10584. enumerable: true,
  10585. configurable: true
  10586. });
  10587. Engine.prototype.attachContextLostEvent = function (callback) {
  10588. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10589. };
  10590. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10591. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10592. };
  10593. Engine.prototype.getVertexShaderSource = function (program) {
  10594. var shaders = this._gl.getAttachedShaders(program);
  10595. return this._gl.getShaderSource(shaders[0]);
  10596. };
  10597. Engine.prototype.getFragmentShaderSource = function (program) {
  10598. var shaders = this._gl.getAttachedShaders(program);
  10599. return this._gl.getShaderSource(shaders[1]);
  10600. };
  10601. // FPS
  10602. Engine.prototype.getFps = function () {
  10603. return this.fps;
  10604. };
  10605. Engine.prototype.getDeltaTime = function () {
  10606. return this.deltaTime;
  10607. };
  10608. Engine.prototype._measureFps = function () {
  10609. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10610. var length = this.previousFramesDuration.length;
  10611. if (length >= 2) {
  10612. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10613. }
  10614. if (length >= this.fpsRange) {
  10615. if (length > this.fpsRange) {
  10616. this.previousFramesDuration.splice(0, 1);
  10617. length = this.previousFramesDuration.length;
  10618. }
  10619. var sum = 0;
  10620. for (var id = 0; id < length - 1; id++) {
  10621. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10622. }
  10623. this.fps = 1000.0 / (sum / (length - 1));
  10624. }
  10625. };
  10626. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10627. if (this._webGLVersion > 1) {
  10628. return this._caps.colorBufferFloat;
  10629. }
  10630. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10631. };
  10632. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10633. if (this._webGLVersion > 1) {
  10634. return this._caps.colorBufferFloat;
  10635. }
  10636. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10637. };
  10638. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10639. Engine.prototype._canRenderToFramebuffer = function (type) {
  10640. var gl = this._gl;
  10641. //clear existing errors
  10642. while (gl.getError() !== gl.NO_ERROR) { }
  10643. var successful = true;
  10644. var texture = gl.createTexture();
  10645. gl.bindTexture(gl.TEXTURE_2D, texture);
  10646. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10649. var fb = gl.createFramebuffer();
  10650. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10652. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10653. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10654. successful = successful && (gl.getError() === gl.NO_ERROR);
  10655. //try render by clearing frame buffer's color buffer
  10656. if (successful) {
  10657. gl.clear(gl.COLOR_BUFFER_BIT);
  10658. successful = successful && (gl.getError() === gl.NO_ERROR);
  10659. }
  10660. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10661. if (successful) {
  10662. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10663. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10664. var readFormat = gl.RGBA;
  10665. var readType = gl.UNSIGNED_BYTE;
  10666. var buffer = new Uint8Array(4);
  10667. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10668. successful = successful && (gl.getError() === gl.NO_ERROR);
  10669. }
  10670. //clean up
  10671. gl.deleteTexture(texture);
  10672. gl.deleteFramebuffer(fb);
  10673. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10674. //clear accumulated errors
  10675. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10676. return successful;
  10677. };
  10678. Engine.prototype._getWebGLTextureType = function (type) {
  10679. if (type === Engine.TEXTURETYPE_FLOAT) {
  10680. return this._gl.FLOAT;
  10681. }
  10682. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10683. // Add Half Float Constant.
  10684. return Engine.HALF_FLOAT_OES;
  10685. }
  10686. return this._gl.UNSIGNED_BYTE;
  10687. };
  10688. ;
  10689. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10690. if (this._webGLVersion === 1) {
  10691. return this._gl.RGBA;
  10692. }
  10693. if (type === Engine.TEXTURETYPE_FLOAT) {
  10694. return Engine.RGBA32F;
  10695. }
  10696. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10697. return Engine.RGBA16F;
  10698. }
  10699. return this._gl.RGBA;
  10700. };
  10701. ;
  10702. // Statics
  10703. Engine.isSupported = function () {
  10704. try {
  10705. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10706. if (navigator.isCocoonJS) {
  10707. return true;
  10708. }
  10709. var tempcanvas = document.createElement("canvas");
  10710. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10711. return gl != null && !!window.WebGLRenderingContext;
  10712. }
  10713. catch (e) {
  10714. return false;
  10715. }
  10716. };
  10717. return Engine;
  10718. }());
  10719. Engine.Instances = new Array();
  10720. // Const statics
  10721. Engine._ALPHA_DISABLE = 0;
  10722. Engine._ALPHA_ADD = 1;
  10723. Engine._ALPHA_COMBINE = 2;
  10724. Engine._ALPHA_SUBTRACT = 3;
  10725. Engine._ALPHA_MULTIPLY = 4;
  10726. Engine._ALPHA_MAXIMIZED = 5;
  10727. Engine._ALPHA_ONEONE = 6;
  10728. Engine._ALPHA_PREMULTIPLIED = 7;
  10729. Engine._DELAYLOADSTATE_NONE = 0;
  10730. Engine._DELAYLOADSTATE_LOADED = 1;
  10731. Engine._DELAYLOADSTATE_LOADING = 2;
  10732. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10733. Engine._TEXTUREFORMAT_ALPHA = 0;
  10734. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10735. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10736. Engine._TEXTUREFORMAT_RGB = 4;
  10737. Engine._TEXTUREFORMAT_RGBA = 5;
  10738. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10739. Engine._TEXTURETYPE_FLOAT = 1;
  10740. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10741. // Depht or Stencil test Constants.
  10742. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10743. 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.
  10744. 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.
  10745. 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.
  10746. 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.
  10747. 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.
  10748. 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.
  10749. 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.
  10750. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10751. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10752. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10753. // Stencil Actions Constants.
  10754. Engine._KEEP = 0x1E00;
  10755. Engine._REPLACE = 0x1E01;
  10756. Engine._INCR = 0x1E02;
  10757. Engine._DECR = 0x1E03;
  10758. Engine._INVERT = 0x150A;
  10759. Engine._INCR_WRAP = 0x8507;
  10760. Engine._DECR_WRAP = 0x8508;
  10761. // Updatable statics so stick with vars here
  10762. Engine.CollisionsEpsilon = 0.001;
  10763. Engine.CodeRepository = "src/";
  10764. Engine.ShadersRepository = "src/Shaders/";
  10765. BABYLON.Engine = Engine;
  10766. })(BABYLON || (BABYLON = {}));
  10767. //# sourceMappingURL=babylon.engine.js.map
  10768. /// <reference path="Tools\babylon.decorators.ts" />
  10769. var BABYLON;
  10770. (function (BABYLON) {
  10771. /**
  10772. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10773. */
  10774. var Node = (function () {
  10775. /**
  10776. * @constructor
  10777. * @param {string} name - the name and id to be given to this node
  10778. * @param {BABYLON.Scene} the scene this node will be added to
  10779. */
  10780. function Node(name, scene) {
  10781. this.state = "";
  10782. this.metadata = null;
  10783. this.doNotSerialize = false;
  10784. this.animations = new Array();
  10785. this._ranges = {};
  10786. this._childrenFlag = -1;
  10787. this._isEnabled = true;
  10788. this._isReady = true;
  10789. this._currentRenderId = -1;
  10790. this._parentRenderId = -1;
  10791. /**
  10792. * An event triggered when the mesh is disposed.
  10793. * @type {BABYLON.Observable}
  10794. */
  10795. this.onDisposeObservable = new BABYLON.Observable();
  10796. this.name = name;
  10797. this.id = name;
  10798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10799. this._initCache();
  10800. }
  10801. Object.defineProperty(Node.prototype, "parent", {
  10802. get: function () {
  10803. return this._parentNode;
  10804. },
  10805. set: function (parent) {
  10806. if (this._parentNode === parent) {
  10807. return;
  10808. }
  10809. if (this._parentNode) {
  10810. var index = this._parentNode._children.indexOf(this);
  10811. if (index !== -1) {
  10812. this._parentNode._children.splice(index, 1);
  10813. }
  10814. }
  10815. this._parentNode = parent;
  10816. if (this._parentNode) {
  10817. if (!this._parentNode._children) {
  10818. this._parentNode._children = new Array();
  10819. }
  10820. this._parentNode._children.push(this);
  10821. }
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Node.prototype.getClassName = function () {
  10827. return "Node";
  10828. };
  10829. Object.defineProperty(Node.prototype, "onDispose", {
  10830. set: function (callback) {
  10831. if (this._onDisposeObserver) {
  10832. this.onDisposeObservable.remove(this._onDisposeObserver);
  10833. }
  10834. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Node.prototype.getScene = function () {
  10840. return this._scene;
  10841. };
  10842. Node.prototype.getEngine = function () {
  10843. return this._scene.getEngine();
  10844. };
  10845. // override it in derived class
  10846. Node.prototype.getWorldMatrix = function () {
  10847. return BABYLON.Matrix.Identity();
  10848. };
  10849. // override it in derived class if you add new variables to the cache
  10850. // and call the parent class method
  10851. Node.prototype._initCache = function () {
  10852. this._cache = {};
  10853. this._cache.parent = undefined;
  10854. };
  10855. Node.prototype.updateCache = function (force) {
  10856. if (!force && this.isSynchronized())
  10857. return;
  10858. this._cache.parent = this.parent;
  10859. this._updateCache();
  10860. };
  10861. // override it in derived class if you add new variables to the cache
  10862. // and call the parent class method if !ignoreParentClass
  10863. Node.prototype._updateCache = function (ignoreParentClass) {
  10864. };
  10865. // override it in derived class if you add new variables to the cache
  10866. Node.prototype._isSynchronized = function () {
  10867. return true;
  10868. };
  10869. Node.prototype._markSyncedWithParent = function () {
  10870. this._parentRenderId = this.parent._currentRenderId;
  10871. };
  10872. Node.prototype.isSynchronizedWithParent = function () {
  10873. if (!this.parent) {
  10874. return true;
  10875. }
  10876. if (this._parentRenderId !== this.parent._currentRenderId) {
  10877. return false;
  10878. }
  10879. return this.parent.isSynchronized();
  10880. };
  10881. Node.prototype.isSynchronized = function (updateCache) {
  10882. var check = this.hasNewParent();
  10883. check = check || !this.isSynchronizedWithParent();
  10884. check = check || !this._isSynchronized();
  10885. if (updateCache)
  10886. this.updateCache(true);
  10887. return !check;
  10888. };
  10889. Node.prototype.hasNewParent = function (update) {
  10890. if (this._cache.parent === this.parent)
  10891. return false;
  10892. if (update)
  10893. this._cache.parent = this.parent;
  10894. return true;
  10895. };
  10896. /**
  10897. * Is this node ready to be used/rendered
  10898. * @return {boolean} is it ready
  10899. */
  10900. Node.prototype.isReady = function () {
  10901. return this._isReady;
  10902. };
  10903. /**
  10904. * Is this node enabled.
  10905. * If the node has a parent and is enabled, the parent will be inspected as well.
  10906. * @return {boolean} whether this node (and its parent) is enabled.
  10907. * @see setEnabled
  10908. */
  10909. Node.prototype.isEnabled = function () {
  10910. if (!this._isEnabled) {
  10911. return false;
  10912. }
  10913. if (this.parent) {
  10914. return this.parent.isEnabled();
  10915. }
  10916. return true;
  10917. };
  10918. /**
  10919. * Set the enabled state of this node.
  10920. * @param {boolean} value - the new enabled state
  10921. * @see isEnabled
  10922. */
  10923. Node.prototype.setEnabled = function (value) {
  10924. this._isEnabled = value;
  10925. };
  10926. /**
  10927. * Is this node a descendant of the given node.
  10928. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10929. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10930. * @see parent
  10931. */
  10932. Node.prototype.isDescendantOf = function (ancestor) {
  10933. if (this.parent) {
  10934. if (this.parent === ancestor) {
  10935. return true;
  10936. }
  10937. return this.parent.isDescendantOf(ancestor);
  10938. }
  10939. return false;
  10940. };
  10941. /**
  10942. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10943. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10944. * @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.
  10945. * @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.
  10946. */
  10947. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10948. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10949. if (!this._children) {
  10950. return;
  10951. }
  10952. for (var index = 0; index < this._children.length; index++) {
  10953. var item = this._children[index];
  10954. if (!predicate || predicate(item)) {
  10955. results.push(item);
  10956. }
  10957. if (!directDescendantsOnly) {
  10958. item._getDescendants(results, false, predicate);
  10959. }
  10960. }
  10961. };
  10962. /**
  10963. * Will return all nodes that have this node as ascendant.
  10964. * @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.
  10965. * @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.
  10966. * @return {BABYLON.Node[]} all children nodes of all types.
  10967. */
  10968. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10969. var results = [];
  10970. this._getDescendants(results, directDescendantsOnly, predicate);
  10971. return results;
  10972. };
  10973. /**
  10974. * Get all child-meshes of this node.
  10975. */
  10976. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10977. var results = [];
  10978. this._getDescendants(results, directDecendantsOnly, function (node) {
  10979. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10980. });
  10981. return results;
  10982. };
  10983. /**
  10984. * Get all direct children of this node.
  10985. */
  10986. Node.prototype.getChildren = function (predicate) {
  10987. return this.getDescendants(true, predicate);
  10988. };
  10989. Node.prototype._setReady = function (state) {
  10990. if (state === this._isReady) {
  10991. return;
  10992. }
  10993. if (!state) {
  10994. this._isReady = false;
  10995. return;
  10996. }
  10997. this._isReady = true;
  10998. if (this.onReady) {
  10999. this.onReady(this);
  11000. }
  11001. };
  11002. Node.prototype.getAnimationByName = function (name) {
  11003. for (var i = 0; i < this.animations.length; i++) {
  11004. var animation = this.animations[i];
  11005. if (animation.name === name) {
  11006. return animation;
  11007. }
  11008. }
  11009. return null;
  11010. };
  11011. Node.prototype.createAnimationRange = function (name, from, to) {
  11012. // check name not already in use
  11013. if (!this._ranges[name]) {
  11014. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11015. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11016. if (this.animations[i]) {
  11017. this.animations[i].createRange(name, from, to);
  11018. }
  11019. }
  11020. }
  11021. };
  11022. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11023. if (deleteFrames === void 0) { deleteFrames = true; }
  11024. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11025. if (this.animations[i]) {
  11026. this.animations[i].deleteRange(name, deleteFrames);
  11027. }
  11028. }
  11029. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11030. };
  11031. Node.prototype.getAnimationRange = function (name) {
  11032. return this._ranges[name];
  11033. };
  11034. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11035. var range = this.getAnimationRange(name);
  11036. if (!range) {
  11037. return null;
  11038. }
  11039. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11040. };
  11041. Node.prototype.serializeAnimationRanges = function () {
  11042. var serializationRanges = [];
  11043. for (var name in this._ranges) {
  11044. var range = {};
  11045. range.name = name;
  11046. range.from = this._ranges[name].from;
  11047. range.to = this._ranges[name].to;
  11048. serializationRanges.push(range);
  11049. }
  11050. return serializationRanges;
  11051. };
  11052. Node.prototype.dispose = function () {
  11053. this.parent = null;
  11054. // Callback
  11055. this.onDisposeObservable.notifyObservers(this);
  11056. this.onDisposeObservable.clear();
  11057. };
  11058. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11059. if (parsedNode.ranges) {
  11060. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11061. var data = parsedNode.ranges[index];
  11062. node.createAnimationRange(data.name, data.from, data.to);
  11063. }
  11064. }
  11065. };
  11066. return Node;
  11067. }());
  11068. __decorate([
  11069. BABYLON.serialize()
  11070. ], Node.prototype, "name", void 0);
  11071. __decorate([
  11072. BABYLON.serialize()
  11073. ], Node.prototype, "id", void 0);
  11074. __decorate([
  11075. BABYLON.serialize()
  11076. ], Node.prototype, "uniqueId", void 0);
  11077. __decorate([
  11078. BABYLON.serialize()
  11079. ], Node.prototype, "state", void 0);
  11080. __decorate([
  11081. BABYLON.serialize()
  11082. ], Node.prototype, "metadata", void 0);
  11083. BABYLON.Node = Node;
  11084. })(BABYLON || (BABYLON = {}));
  11085. //# sourceMappingURL=babylon.node.js.map
  11086. var BABYLON;
  11087. (function (BABYLON) {
  11088. var FilesInput = (function () {
  11089. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11090. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11091. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11092. this._engine = p_engine;
  11093. this._canvas = p_canvas;
  11094. this._currentScene = p_scene;
  11095. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11096. this._progressCallback = p_progressCallback;
  11097. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11098. this._textureLoadingCallback = p_textureLoadingCallback;
  11099. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11100. }
  11101. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11102. var _this = this;
  11103. if (p_elementToMonitor) {
  11104. this._elementToMonitor = p_elementToMonitor;
  11105. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11106. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11107. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11108. }
  11109. };
  11110. FilesInput.prototype.renderFunction = function () {
  11111. if (this._additionnalRenderLoopLogicCallback) {
  11112. this._additionnalRenderLoopLogicCallback();
  11113. }
  11114. if (this._currentScene) {
  11115. if (this._textureLoadingCallback) {
  11116. var remaining = this._currentScene.getWaitingItemsCount();
  11117. if (remaining > 0) {
  11118. this._textureLoadingCallback(remaining);
  11119. }
  11120. }
  11121. this._currentScene.render();
  11122. }
  11123. };
  11124. FilesInput.prototype.drag = function (e) {
  11125. e.stopPropagation();
  11126. e.preventDefault();
  11127. };
  11128. FilesInput.prototype.drop = function (eventDrop) {
  11129. eventDrop.stopPropagation();
  11130. eventDrop.preventDefault();
  11131. this.loadFiles(eventDrop);
  11132. };
  11133. FilesInput.prototype.loadFiles = function (event) {
  11134. if (this._startingProcessingFilesCallback)
  11135. this._startingProcessingFilesCallback();
  11136. // Handling data transfer via drag'n'drop
  11137. if (event && event.dataTransfer && event.dataTransfer.files) {
  11138. this._filesToLoad = event.dataTransfer.files;
  11139. }
  11140. // Handling files from input files
  11141. if (event && event.target && event.target.files) {
  11142. this._filesToLoad = event.target.files;
  11143. }
  11144. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11145. for (var i = 0; i < this._filesToLoad.length; i++) {
  11146. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11147. var extension = name_1.split('.').pop();
  11148. var type = this._filesToLoad[i].type;
  11149. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11150. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11151. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11152. }
  11153. else {
  11154. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11155. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11156. this._sceneFileToLoad = this._filesToLoad[i];
  11157. }
  11158. else {
  11159. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11160. }
  11161. }
  11162. }
  11163. this.reload();
  11164. }
  11165. };
  11166. FilesInput.prototype.reload = function () {
  11167. var _this = this;
  11168. var that = this;
  11169. // If a ".babylon" file has been provided
  11170. if (this._sceneFileToLoad) {
  11171. if (this._currentScene) {
  11172. if (BABYLON.Tools.errorsCount > 0) {
  11173. BABYLON.Tools.ClearLogCache();
  11174. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11175. }
  11176. this._engine.stopRenderLoop();
  11177. this._currentScene.dispose();
  11178. }
  11179. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11180. that._currentScene = newScene;
  11181. // Wait for textures and shaders to be ready
  11182. that._currentScene.executeWhenReady(function () {
  11183. // Attach camera to canvas inputs
  11184. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11185. that._currentScene.createDefaultCameraOrLight();
  11186. }
  11187. that._currentScene.activeCamera.attachControl(that._canvas);
  11188. if (that._sceneLoadedCallback) {
  11189. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11190. }
  11191. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11192. });
  11193. }, function (progress) {
  11194. if (_this._progressCallback) {
  11195. _this._progressCallback(progress);
  11196. }
  11197. });
  11198. }
  11199. else {
  11200. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11201. }
  11202. };
  11203. return FilesInput;
  11204. }());
  11205. FilesInput.FilesTextures = new Array();
  11206. FilesInput.FilesToLoad = new Array();
  11207. BABYLON.FilesInput = FilesInput;
  11208. })(BABYLON || (BABYLON = {}));
  11209. //# sourceMappingURL=babylon.filesInput.js.map
  11210. var BABYLON;
  11211. (function (BABYLON) {
  11212. var IntersectionInfo = (function () {
  11213. function IntersectionInfo(bu, bv, distance) {
  11214. this.bu = bu;
  11215. this.bv = bv;
  11216. this.distance = distance;
  11217. this.faceId = 0;
  11218. this.subMeshId = 0;
  11219. }
  11220. return IntersectionInfo;
  11221. }());
  11222. BABYLON.IntersectionInfo = IntersectionInfo;
  11223. var PickingInfo = (function () {
  11224. function PickingInfo() {
  11225. this.hit = false;
  11226. this.distance = 0;
  11227. this.pickedPoint = null;
  11228. this.pickedMesh = null;
  11229. this.bu = 0;
  11230. this.bv = 0;
  11231. this.faceId = -1;
  11232. this.subMeshId = 0;
  11233. this.pickedSprite = null;
  11234. }
  11235. // Methods
  11236. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11237. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11238. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11239. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11240. return null;
  11241. }
  11242. var indices = this.pickedMesh.getIndices();
  11243. var result;
  11244. if (useVerticesNormals) {
  11245. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11246. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11247. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11248. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11249. normal0 = normal0.scale(this.bu);
  11250. normal1 = normal1.scale(this.bv);
  11251. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11252. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11253. }
  11254. else {
  11255. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11256. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11257. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11258. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11259. var p1p2 = vertex1.subtract(vertex2);
  11260. var p3p2 = vertex3.subtract(vertex2);
  11261. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11262. }
  11263. if (useWorldCoordinates) {
  11264. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11265. }
  11266. return BABYLON.Vector3.Normalize(result);
  11267. };
  11268. PickingInfo.prototype.getTextureCoordinates = function () {
  11269. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11270. return null;
  11271. }
  11272. var indices = this.pickedMesh.getIndices();
  11273. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11274. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11275. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11276. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11277. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11278. uv1 = uv1.scale(this.bu);
  11279. uv2 = uv2.scale(this.bv);
  11280. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11281. };
  11282. return PickingInfo;
  11283. }());
  11284. BABYLON.PickingInfo = PickingInfo;
  11285. })(BABYLON || (BABYLON = {}));
  11286. //# sourceMappingURL=babylon.pickingInfo.js.map
  11287. var BABYLON;
  11288. (function (BABYLON) {
  11289. var BoundingSphere = (function () {
  11290. function BoundingSphere(minimum, maximum) {
  11291. this.minimum = minimum;
  11292. this.maximum = maximum;
  11293. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11294. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11295. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11296. this.radius = distance * 0.5;
  11297. this.centerWorld = BABYLON.Vector3.Zero();
  11298. this._update(BABYLON.Matrix.Identity());
  11299. }
  11300. // Methods
  11301. BoundingSphere.prototype._update = function (world) {
  11302. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11303. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11304. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11305. };
  11306. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11307. for (var i = 0; i < 6; i++) {
  11308. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11309. return false;
  11310. }
  11311. return true;
  11312. };
  11313. BoundingSphere.prototype.intersectsPoint = function (point) {
  11314. var x = this.centerWorld.x - point.x;
  11315. var y = this.centerWorld.y - point.y;
  11316. var z = this.centerWorld.z - point.z;
  11317. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11318. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11319. return false;
  11320. return true;
  11321. };
  11322. // Statics
  11323. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11324. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11325. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11326. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11327. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11328. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11329. return false;
  11330. return true;
  11331. };
  11332. return BoundingSphere;
  11333. }());
  11334. BABYLON.BoundingSphere = BoundingSphere;
  11335. })(BABYLON || (BABYLON = {}));
  11336. //# sourceMappingURL=babylon.boundingSphere.js.map
  11337. var BABYLON;
  11338. (function (BABYLON) {
  11339. var BoundingBox = (function () {
  11340. function BoundingBox(minimum, maximum) {
  11341. this.minimum = minimum;
  11342. this.maximum = maximum;
  11343. this.vectors = new Array();
  11344. this.vectorsWorld = new Array();
  11345. // Bounding vectors
  11346. this.vectors.push(this.minimum.clone());
  11347. this.vectors.push(this.maximum.clone());
  11348. this.vectors.push(this.minimum.clone());
  11349. this.vectors[2].x = this.maximum.x;
  11350. this.vectors.push(this.minimum.clone());
  11351. this.vectors[3].y = this.maximum.y;
  11352. this.vectors.push(this.minimum.clone());
  11353. this.vectors[4].z = this.maximum.z;
  11354. this.vectors.push(this.maximum.clone());
  11355. this.vectors[5].z = this.minimum.z;
  11356. this.vectors.push(this.maximum.clone());
  11357. this.vectors[6].x = this.minimum.x;
  11358. this.vectors.push(this.maximum.clone());
  11359. this.vectors[7].y = this.minimum.y;
  11360. // OBB
  11361. this.center = this.maximum.add(this.minimum).scale(0.5);
  11362. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11363. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11364. // World
  11365. for (var index = 0; index < this.vectors.length; index++) {
  11366. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11367. }
  11368. this.minimumWorld = BABYLON.Vector3.Zero();
  11369. this.maximumWorld = BABYLON.Vector3.Zero();
  11370. this.centerWorld = BABYLON.Vector3.Zero();
  11371. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11372. this._update(BABYLON.Matrix.Identity());
  11373. }
  11374. // Methods
  11375. BoundingBox.prototype.getWorldMatrix = function () {
  11376. return this._worldMatrix;
  11377. };
  11378. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11379. this._worldMatrix.copyFrom(matrix);
  11380. return this;
  11381. };
  11382. BoundingBox.prototype._update = function (world) {
  11383. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11384. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11385. for (var index = 0; index < this.vectors.length; index++) {
  11386. var v = this.vectorsWorld[index];
  11387. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11388. if (v.x < this.minimumWorld.x)
  11389. this.minimumWorld.x = v.x;
  11390. if (v.y < this.minimumWorld.y)
  11391. this.minimumWorld.y = v.y;
  11392. if (v.z < this.minimumWorld.z)
  11393. this.minimumWorld.z = v.z;
  11394. if (v.x > this.maximumWorld.x)
  11395. this.maximumWorld.x = v.x;
  11396. if (v.y > this.maximumWorld.y)
  11397. this.maximumWorld.y = v.y;
  11398. if (v.z > this.maximumWorld.z)
  11399. this.maximumWorld.z = v.z;
  11400. }
  11401. // Extend
  11402. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11403. this.extendSizeWorld.scaleInPlace(0.5);
  11404. // OBB
  11405. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11406. this.centerWorld.scaleInPlace(0.5);
  11407. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11408. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11409. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11410. this._worldMatrix = world;
  11411. };
  11412. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11413. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11414. };
  11415. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11416. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11417. };
  11418. BoundingBox.prototype.intersectsPoint = function (point) {
  11419. var delta = -BABYLON.Epsilon;
  11420. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11421. return false;
  11422. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11423. return false;
  11424. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11425. return false;
  11426. return true;
  11427. };
  11428. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11429. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11430. };
  11431. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11432. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11433. return false;
  11434. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11435. return false;
  11436. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11437. return false;
  11438. return true;
  11439. };
  11440. // Statics
  11441. BoundingBox.Intersects = function (box0, box1) {
  11442. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11443. return false;
  11444. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11445. return false;
  11446. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11447. return false;
  11448. return true;
  11449. };
  11450. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11451. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11452. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11453. return (num <= (sphereRadius * sphereRadius));
  11454. };
  11455. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11456. for (var p = 0; p < 6; p++) {
  11457. for (var i = 0; i < 8; i++) {
  11458. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11459. return false;
  11460. }
  11461. }
  11462. }
  11463. return true;
  11464. };
  11465. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11466. for (var p = 0; p < 6; p++) {
  11467. var inCount = 8;
  11468. for (var i = 0; i < 8; i++) {
  11469. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11470. --inCount;
  11471. }
  11472. else {
  11473. break;
  11474. }
  11475. }
  11476. if (inCount === 0)
  11477. return false;
  11478. }
  11479. return true;
  11480. };
  11481. return BoundingBox;
  11482. }());
  11483. BABYLON.BoundingBox = BoundingBox;
  11484. })(BABYLON || (BABYLON = {}));
  11485. //# sourceMappingURL=babylon.boundingBox.js.map
  11486. var BABYLON;
  11487. (function (BABYLON) {
  11488. var computeBoxExtents = function (axis, box) {
  11489. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11490. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11491. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11492. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11493. var r = r0 + r1 + r2;
  11494. return {
  11495. min: p - r,
  11496. max: p + r
  11497. };
  11498. };
  11499. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11500. var axisOverlap = function (axis, box0, box1) {
  11501. var result0 = computeBoxExtents(axis, box0);
  11502. var result1 = computeBoxExtents(axis, box1);
  11503. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11504. };
  11505. var BoundingInfo = (function () {
  11506. function BoundingInfo(minimum, maximum) {
  11507. this.minimum = minimum;
  11508. this.maximum = maximum;
  11509. this._isLocked = false;
  11510. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11511. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11512. }
  11513. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11514. get: function () {
  11515. return this._isLocked;
  11516. },
  11517. set: function (value) {
  11518. this._isLocked = value;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. // Methods
  11524. BoundingInfo.prototype.update = function (world) {
  11525. if (this._isLocked) {
  11526. return;
  11527. }
  11528. this.boundingBox._update(world);
  11529. this.boundingSphere._update(world);
  11530. };
  11531. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11532. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11533. return false;
  11534. return this.boundingBox.isInFrustum(frustumPlanes);
  11535. };
  11536. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11537. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11538. };
  11539. BoundingInfo.prototype._checkCollision = function (collider) {
  11540. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11541. };
  11542. BoundingInfo.prototype.intersectsPoint = function (point) {
  11543. if (!this.boundingSphere.centerWorld) {
  11544. return false;
  11545. }
  11546. if (!this.boundingSphere.intersectsPoint(point)) {
  11547. return false;
  11548. }
  11549. if (!this.boundingBox.intersectsPoint(point)) {
  11550. return false;
  11551. }
  11552. return true;
  11553. };
  11554. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11555. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11556. return false;
  11557. }
  11558. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11559. return false;
  11560. }
  11561. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11562. return false;
  11563. }
  11564. if (!precise) {
  11565. return true;
  11566. }
  11567. var box0 = this.boundingBox;
  11568. var box1 = boundingInfo.boundingBox;
  11569. if (!axisOverlap(box0.directions[0], box0, box1))
  11570. return false;
  11571. if (!axisOverlap(box0.directions[1], box0, box1))
  11572. return false;
  11573. if (!axisOverlap(box0.directions[2], box0, box1))
  11574. return false;
  11575. if (!axisOverlap(box1.directions[0], box0, box1))
  11576. return false;
  11577. if (!axisOverlap(box1.directions[1], box0, box1))
  11578. return false;
  11579. if (!axisOverlap(box1.directions[2], box0, box1))
  11580. return false;
  11581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11582. return false;
  11583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11584. return false;
  11585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11586. return false;
  11587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11588. return false;
  11589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11590. return false;
  11591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11592. return false;
  11593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11594. return false;
  11595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11596. return false;
  11597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11598. return false;
  11599. return true;
  11600. };
  11601. return BoundingInfo;
  11602. }());
  11603. BABYLON.BoundingInfo = BoundingInfo;
  11604. })(BABYLON || (BABYLON = {}));
  11605. //# sourceMappingURL=babylon.boundingInfo.js.map
  11606. var BABYLON;
  11607. (function (BABYLON) {
  11608. var Ray = (function () {
  11609. function Ray(origin, direction, length) {
  11610. if (length === void 0) { length = Number.MAX_VALUE; }
  11611. this.origin = origin;
  11612. this.direction = direction;
  11613. this.length = length;
  11614. }
  11615. // Methods
  11616. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11617. var d = 0.0;
  11618. var maxValue = Number.MAX_VALUE;
  11619. var inv;
  11620. var min;
  11621. var max;
  11622. var temp;
  11623. if (Math.abs(this.direction.x) < 0.0000001) {
  11624. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11625. return false;
  11626. }
  11627. }
  11628. else {
  11629. inv = 1.0 / this.direction.x;
  11630. min = (minimum.x - this.origin.x) * inv;
  11631. max = (maximum.x - this.origin.x) * inv;
  11632. if (max === -Infinity) {
  11633. max = Infinity;
  11634. }
  11635. if (min > max) {
  11636. temp = min;
  11637. min = max;
  11638. max = temp;
  11639. }
  11640. d = Math.max(min, d);
  11641. maxValue = Math.min(max, maxValue);
  11642. if (d > maxValue) {
  11643. return false;
  11644. }
  11645. }
  11646. if (Math.abs(this.direction.y) < 0.0000001) {
  11647. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11648. return false;
  11649. }
  11650. }
  11651. else {
  11652. inv = 1.0 / this.direction.y;
  11653. min = (minimum.y - this.origin.y) * inv;
  11654. max = (maximum.y - this.origin.y) * inv;
  11655. if (max === -Infinity) {
  11656. max = Infinity;
  11657. }
  11658. if (min > max) {
  11659. temp = min;
  11660. min = max;
  11661. max = temp;
  11662. }
  11663. d = Math.max(min, d);
  11664. maxValue = Math.min(max, maxValue);
  11665. if (d > maxValue) {
  11666. return false;
  11667. }
  11668. }
  11669. if (Math.abs(this.direction.z) < 0.0000001) {
  11670. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11671. return false;
  11672. }
  11673. }
  11674. else {
  11675. inv = 1.0 / this.direction.z;
  11676. min = (minimum.z - this.origin.z) * inv;
  11677. max = (maximum.z - this.origin.z) * inv;
  11678. if (max === -Infinity) {
  11679. max = Infinity;
  11680. }
  11681. if (min > max) {
  11682. temp = min;
  11683. min = max;
  11684. max = temp;
  11685. }
  11686. d = Math.max(min, d);
  11687. maxValue = Math.min(max, maxValue);
  11688. if (d > maxValue) {
  11689. return false;
  11690. }
  11691. }
  11692. return true;
  11693. };
  11694. Ray.prototype.intersectsBox = function (box) {
  11695. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11696. };
  11697. Ray.prototype.intersectsSphere = function (sphere) {
  11698. var x = sphere.center.x - this.origin.x;
  11699. var y = sphere.center.y - this.origin.y;
  11700. var z = sphere.center.z - this.origin.z;
  11701. var pyth = (x * x) + (y * y) + (z * z);
  11702. var rr = sphere.radius * sphere.radius;
  11703. if (pyth <= rr) {
  11704. return true;
  11705. }
  11706. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11707. if (dot < 0.0) {
  11708. return false;
  11709. }
  11710. var temp = pyth - (dot * dot);
  11711. return temp <= rr;
  11712. };
  11713. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11714. if (!this._edge1) {
  11715. this._edge1 = BABYLON.Vector3.Zero();
  11716. this._edge2 = BABYLON.Vector3.Zero();
  11717. this._pvec = BABYLON.Vector3.Zero();
  11718. this._tvec = BABYLON.Vector3.Zero();
  11719. this._qvec = BABYLON.Vector3.Zero();
  11720. }
  11721. vertex1.subtractToRef(vertex0, this._edge1);
  11722. vertex2.subtractToRef(vertex0, this._edge2);
  11723. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11724. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11725. if (det === 0) {
  11726. return null;
  11727. }
  11728. var invdet = 1 / det;
  11729. this.origin.subtractToRef(vertex0, this._tvec);
  11730. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11731. if (bu < 0 || bu > 1.0) {
  11732. return null;
  11733. }
  11734. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11735. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11736. if (bv < 0 || bu + bv > 1.0) {
  11737. return null;
  11738. }
  11739. //check if the distance is longer than the predefined length.
  11740. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11741. if (distance > this.length) {
  11742. return null;
  11743. }
  11744. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11745. };
  11746. Ray.prototype.intersectsPlane = function (plane) {
  11747. var distance;
  11748. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11749. if (Math.abs(result1) < 9.99999997475243E-07) {
  11750. return null;
  11751. }
  11752. else {
  11753. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11754. distance = (-plane.d - result2) / result1;
  11755. if (distance < 0.0) {
  11756. if (distance < -9.99999997475243E-07) {
  11757. return null;
  11758. }
  11759. else {
  11760. return 0;
  11761. }
  11762. }
  11763. return distance;
  11764. }
  11765. };
  11766. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11767. var tm = BABYLON.Tmp.Matrix[0];
  11768. mesh.getWorldMatrix().invertToRef(tm);
  11769. if (this._tmpRay) {
  11770. Ray.TransformToRef(this, tm, this._tmpRay);
  11771. }
  11772. else {
  11773. this._tmpRay = Ray.Transform(this, tm);
  11774. }
  11775. return mesh.intersects(this._tmpRay, fastCheck);
  11776. };
  11777. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11778. if (results) {
  11779. results.length = 0;
  11780. }
  11781. else {
  11782. results = [];
  11783. }
  11784. for (var i = 0; i < meshes.length; i++) {
  11785. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11786. if (pickInfo.hit) {
  11787. results.push(pickInfo);
  11788. }
  11789. }
  11790. results.sort(this._comparePickingInfo);
  11791. return results;
  11792. };
  11793. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11794. if (pickingInfoA.distance < pickingInfoB.distance) {
  11795. return -1;
  11796. }
  11797. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11798. return 1;
  11799. }
  11800. else {
  11801. return 0;
  11802. }
  11803. };
  11804. /**
  11805. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11806. * @param sega the first point of the segment to test the intersection against
  11807. * @param segb the second point of the segment to test the intersection against
  11808. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11809. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11810. */
  11811. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11812. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11813. var u = segb.subtract(sega);
  11814. var v = rsegb.subtract(this.origin);
  11815. var w = sega.subtract(this.origin);
  11816. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11817. var b = BABYLON.Vector3.Dot(u, v);
  11818. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11819. var d = BABYLON.Vector3.Dot(u, w);
  11820. var e = BABYLON.Vector3.Dot(v, w);
  11821. var D = a * c - b * b; // always >= 0
  11822. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11823. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11824. // compute the line parameters of the two closest points
  11825. if (D < Ray.smallnum) {
  11826. sN = 0.0; // force using point P0 on segment S1
  11827. sD = 1.0; // to prevent possible division by 0.0 later
  11828. tN = e;
  11829. tD = c;
  11830. }
  11831. else {
  11832. sN = (b * e - c * d);
  11833. tN = (a * e - b * d);
  11834. if (sN < 0.0) {
  11835. sN = 0.0;
  11836. tN = e;
  11837. tD = c;
  11838. }
  11839. else if (sN > sD) {
  11840. sN = sD;
  11841. tN = e + b;
  11842. tD = c;
  11843. }
  11844. }
  11845. if (tN < 0.0) {
  11846. tN = 0.0;
  11847. // recompute sc for this edge
  11848. if (-d < 0.0) {
  11849. sN = 0.0;
  11850. }
  11851. else if (-d > a)
  11852. sN = sD;
  11853. else {
  11854. sN = -d;
  11855. sD = a;
  11856. }
  11857. }
  11858. else if (tN > tD) {
  11859. tN = tD;
  11860. // recompute sc for this edge
  11861. if ((-d + b) < 0.0) {
  11862. sN = 0;
  11863. }
  11864. else if ((-d + b) > a) {
  11865. sN = sD;
  11866. }
  11867. else {
  11868. sN = (-d + b);
  11869. sD = a;
  11870. }
  11871. }
  11872. // finally do the division to get sc and tc
  11873. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11874. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11875. // get the difference of the two closest points
  11876. var qtc = v.multiplyByFloats(tc, tc, tc);
  11877. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11878. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11879. if (isIntersected) {
  11880. return qtc.length();
  11881. }
  11882. return -1;
  11883. };
  11884. // Statics
  11885. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11886. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11887. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11888. var direction = end.subtract(start);
  11889. direction.normalize();
  11890. return new Ray(start, direction);
  11891. };
  11892. /**
  11893. * 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
  11894. * transformed to the given world matrix.
  11895. * @param origin The origin point
  11896. * @param end The end point
  11897. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11898. */
  11899. Ray.CreateNewFromTo = function (origin, end, world) {
  11900. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11901. var direction = end.subtract(origin);
  11902. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11903. direction.normalize();
  11904. return Ray.Transform(new Ray(origin, direction, length), world);
  11905. };
  11906. Ray.Transform = function (ray, matrix) {
  11907. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11908. Ray.TransformToRef(ray, matrix, result);
  11909. return result;
  11910. };
  11911. Ray.TransformToRef = function (ray, matrix, result) {
  11912. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11913. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11914. result.length = ray.length;
  11915. var dir = result.direction;
  11916. var len = dir.length();
  11917. if (!(len === 0 || len === 1)) {
  11918. var num = 1.0 / len;
  11919. dir.x *= num;
  11920. dir.y *= num;
  11921. dir.z *= num;
  11922. result.length *= len;
  11923. }
  11924. };
  11925. return Ray;
  11926. }());
  11927. Ray.smallnum = 0.00000001;
  11928. Ray.rayl = 10e8;
  11929. BABYLON.Ray = Ray;
  11930. })(BABYLON || (BABYLON = {}));
  11931. //# sourceMappingURL=babylon.ray.js.map
  11932. var BABYLON;
  11933. (function (BABYLON) {
  11934. var RayHelper = (function () {
  11935. function RayHelper(ray) {
  11936. this.ray = ray;
  11937. }
  11938. RayHelper.CreateAndShow = function (ray, scene, color) {
  11939. var helper = new RayHelper(ray);
  11940. helper.show(scene, color);
  11941. return helper;
  11942. };
  11943. RayHelper.prototype.show = function (scene, color) {
  11944. if (!this._renderFunction) {
  11945. var ray = this.ray;
  11946. this._renderFunction = this._render.bind(this);
  11947. this._scene = scene;
  11948. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11949. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11950. this._scene.registerBeforeRender(this._renderFunction);
  11951. }
  11952. if (color) {
  11953. this._renderLine.color.copyFrom(color);
  11954. }
  11955. };
  11956. RayHelper.prototype.hide = function () {
  11957. if (this._renderFunction) {
  11958. this._scene.unregisterBeforeRender(this._renderFunction);
  11959. this._scene = null;
  11960. this._renderFunction = null;
  11961. this._renderLine.dispose();
  11962. this._renderLine = null;
  11963. this._renderPoints = null;
  11964. }
  11965. };
  11966. RayHelper.prototype._render = function () {
  11967. var ray = this.ray;
  11968. var point = this._renderPoints[1];
  11969. var len = Math.min(ray.length, 1000000);
  11970. point.copyFrom(ray.direction);
  11971. point.scaleInPlace(len);
  11972. point.addInPlace(ray.origin);
  11973. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11974. };
  11975. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11976. this._attachedToMesh = mesh;
  11977. var ray = this.ray;
  11978. if (!ray.direction) {
  11979. ray.direction = BABYLON.Vector3.Zero();
  11980. }
  11981. if (!ray.origin) {
  11982. ray.origin = BABYLON.Vector3.Zero();
  11983. }
  11984. if (length) {
  11985. ray.length = length;
  11986. }
  11987. if (!meshSpaceOrigin) {
  11988. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11989. }
  11990. if (!meshSpaceDirection) {
  11991. // -1 so that this will work with Mesh.lookAt
  11992. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11993. }
  11994. if (!this._meshSpaceDirection) {
  11995. this._meshSpaceDirection = meshSpaceDirection.clone();
  11996. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11997. }
  11998. else {
  11999. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  12000. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  12001. }
  12002. if (!this._updateToMeshFunction) {
  12003. this._updateToMeshFunction = this._updateToMesh.bind(this);
  12004. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  12005. }
  12006. this._updateToMesh();
  12007. };
  12008. RayHelper.prototype.detachFromMesh = function () {
  12009. if (this._attachedToMesh) {
  12010. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12011. this._attachedToMesh = null;
  12012. this._updateToMeshFunction = null;
  12013. }
  12014. };
  12015. RayHelper.prototype._updateToMesh = function () {
  12016. var ray = this.ray;
  12017. if (this._attachedToMesh._isDisposed) {
  12018. this.detachFromMesh();
  12019. return;
  12020. }
  12021. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12022. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12023. };
  12024. RayHelper.prototype.dispose = function () {
  12025. this.hide();
  12026. this.detachFromMesh();
  12027. this.ray = null;
  12028. };
  12029. return RayHelper;
  12030. }());
  12031. BABYLON.RayHelper = RayHelper;
  12032. })(BABYLON || (BABYLON = {}));
  12033. //# sourceMappingURL=babylon.rayHelper.js.map
  12034. var BABYLON;
  12035. (function (BABYLON) {
  12036. var AbstractMesh = (function (_super) {
  12037. __extends(AbstractMesh, _super);
  12038. // Constructor
  12039. function AbstractMesh(name, scene) {
  12040. var _this = _super.call(this, name, scene) || this;
  12041. _this._facetNb = 0; // facet number
  12042. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12043. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12044. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12045. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12046. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12047. _this._subDiv = {
  12048. max: 1,
  12049. X: 1,
  12050. Y: 1,
  12051. Z: 1
  12052. };
  12053. // Events
  12054. /**
  12055. * An event triggered when this mesh collides with another one
  12056. * @type {BABYLON.Observable}
  12057. */
  12058. _this.onCollideObservable = new BABYLON.Observable();
  12059. /**
  12060. * An event triggered when the collision's position changes
  12061. * @type {BABYLON.Observable}
  12062. */
  12063. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12064. /**
  12065. * An event triggered after the world matrix is updated
  12066. * @type {BABYLON.Observable}
  12067. */
  12068. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12069. // Properties
  12070. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12071. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12072. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12073. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12074. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12075. _this.visibility = 1.0;
  12076. _this.alphaIndex = Number.MAX_VALUE;
  12077. _this.infiniteDistance = false;
  12078. _this.isVisible = true;
  12079. _this.isPickable = true;
  12080. _this.showBoundingBox = false;
  12081. _this.showSubMeshesBoundingBox = false;
  12082. _this.isBlocker = false;
  12083. _this.renderingGroupId = 0;
  12084. _this.receiveShadows = false;
  12085. _this.renderOutline = false;
  12086. _this.outlineColor = BABYLON.Color3.Red();
  12087. _this.outlineWidth = 0.02;
  12088. _this.renderOverlay = false;
  12089. _this.overlayColor = BABYLON.Color3.Red();
  12090. _this.overlayAlpha = 0.5;
  12091. _this.hasVertexAlpha = false;
  12092. _this.useVertexColors = true;
  12093. _this.applyFog = true;
  12094. _this.computeBonesUsingShaders = true;
  12095. _this.scalingDeterminant = 1;
  12096. _this.numBoneInfluencers = 4;
  12097. _this.useOctreeForRenderingSelection = true;
  12098. _this.useOctreeForPicking = true;
  12099. _this.useOctreeForCollisions = true;
  12100. _this.layerMask = 0x0FFFFFFF;
  12101. /**
  12102. * True if the mesh must be rendered in any case.
  12103. */
  12104. _this.alwaysSelectAsActiveMesh = false;
  12105. // Collisions
  12106. _this._checkCollisions = false;
  12107. _this._collisionMask = -1;
  12108. _this._collisionGroup = -1;
  12109. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12110. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12111. _this._collider = new BABYLON.Collider();
  12112. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12113. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12114. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12115. // Edges
  12116. _this.edgesWidth = 1;
  12117. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12118. // Cache
  12119. _this._localWorld = BABYLON.Matrix.Zero();
  12120. _this._worldMatrix = BABYLON.Matrix.Zero();
  12121. _this._absolutePosition = BABYLON.Vector3.Zero();
  12122. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12123. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12124. _this._isDirty = false;
  12125. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12126. _this._isDisposed = false;
  12127. _this._renderId = 0;
  12128. _this._intersectionsInProgress = new Array();
  12129. _this._isWorldMatrixFrozen = false;
  12130. _this._unIndexed = false;
  12131. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12132. if (collidedMesh === void 0) { collidedMesh = null; }
  12133. //TODO move this to the collision coordinator!
  12134. if (_this.getScene().workerCollisions)
  12135. newPosition.multiplyInPlace(_this._collider.radius);
  12136. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12137. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12138. _this.position.addInPlace(_this._diffPositionForCollisions);
  12139. }
  12140. if (collidedMesh) {
  12141. _this.onCollideObservable.notifyObservers(collidedMesh);
  12142. }
  12143. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12144. };
  12145. _this.getScene().addMesh(_this);
  12146. return _this;
  12147. }
  12148. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12149. get: function () {
  12150. return AbstractMesh._BILLBOARDMODE_NONE;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12156. get: function () {
  12157. return AbstractMesh._BILLBOARDMODE_X;
  12158. },
  12159. enumerable: true,
  12160. configurable: true
  12161. });
  12162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12163. get: function () {
  12164. return AbstractMesh._BILLBOARDMODE_Y;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12170. get: function () {
  12171. return AbstractMesh._BILLBOARDMODE_Z;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12177. get: function () {
  12178. return AbstractMesh._BILLBOARDMODE_ALL;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12184. /**
  12185. * Read-only : the number of facets in the mesh
  12186. */
  12187. get: function () {
  12188. return this._facetNb;
  12189. },
  12190. enumerable: true,
  12191. configurable: true
  12192. });
  12193. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12194. /**
  12195. * The number (integer) of subdivisions per axis in the partioning space
  12196. */
  12197. get: function () {
  12198. return this._partitioningSubdivisions;
  12199. },
  12200. set: function (nb) {
  12201. this._partitioningSubdivisions = nb;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12207. /**
  12208. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12209. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12210. */
  12211. get: function () {
  12212. return this._partitioningBBoxRatio;
  12213. },
  12214. set: function (ratio) {
  12215. this._partitioningBBoxRatio = ratio;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12221. /**
  12222. * Read-only boolean : is the feature facetData enabled ?
  12223. */
  12224. get: function () {
  12225. return this._facetDataEnabled;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12231. set: function (callback) {
  12232. if (this._onCollideObserver) {
  12233. this.onCollideObservable.remove(this._onCollideObserver);
  12234. }
  12235. this._onCollideObserver = this.onCollideObservable.add(callback);
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12241. set: function (callback) {
  12242. if (this._onCollisionPositionChangeObserver) {
  12243. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12244. }
  12245. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12251. get: function () {
  12252. return this._collisionMask;
  12253. },
  12254. set: function (mask) {
  12255. this._collisionMask = !isNaN(mask) ? mask : -1;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12261. get: function () {
  12262. return this._collisionGroup;
  12263. },
  12264. set: function (mask) {
  12265. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12271. get: function () {
  12272. return this._skeleton;
  12273. },
  12274. set: function (value) {
  12275. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12276. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12277. }
  12278. if (value && value.needInitialSkinMatrix) {
  12279. value._registerMeshWithPoseMatrix(this);
  12280. }
  12281. this._skeleton = value;
  12282. if (!this._skeleton) {
  12283. this._bonesTransformMatrices = null;
  12284. }
  12285. },
  12286. enumerable: true,
  12287. configurable: true
  12288. });
  12289. /**
  12290. * Returns the string "AbstractMesh"
  12291. */
  12292. AbstractMesh.prototype.getClassName = function () {
  12293. return "AbstractMesh";
  12294. };
  12295. /**
  12296. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12297. */
  12298. AbstractMesh.prototype.toString = function (fullDetails) {
  12299. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12300. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12301. if (this._skeleton) {
  12302. ret += ", skeleton: " + this._skeleton.name;
  12303. }
  12304. if (fullDetails) {
  12305. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12306. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12307. }
  12308. return ret;
  12309. };
  12310. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12311. /**
  12312. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12313. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12314. * Default : (0.0, 0.0, 0.0)
  12315. */
  12316. get: function () {
  12317. return this._rotation;
  12318. },
  12319. set: function (newRotation) {
  12320. this._rotation = newRotation;
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12326. /**
  12327. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12328. * Default : (1.0, 1.0, 1.0)
  12329. */
  12330. get: function () {
  12331. return this._scaling;
  12332. },
  12333. set: function (newScaling) {
  12334. this._scaling = newScaling;
  12335. if (this.physicsImpostor) {
  12336. this.physicsImpostor.forceUpdate();
  12337. }
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12343. /**
  12344. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12345. * It's null by default.
  12346. * 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)
  12347. */
  12348. get: function () {
  12349. return this._rotationQuaternion;
  12350. },
  12351. set: function (quaternion) {
  12352. this._rotationQuaternion = quaternion;
  12353. //reset the rotation vector.
  12354. if (quaternion && this.rotation.length()) {
  12355. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12356. }
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. // Methods
  12362. /**
  12363. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12364. * Returns the AbstractMesh.
  12365. */
  12366. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12367. this._poseMatrix.copyFrom(matrix);
  12368. return this;
  12369. };
  12370. /**
  12371. * Returns the mesh Pose matrix.
  12372. * Returned object : Matrix
  12373. */
  12374. AbstractMesh.prototype.getPoseMatrix = function () {
  12375. return this._poseMatrix;
  12376. };
  12377. /**
  12378. * Disables the mesh edger rendering mode.
  12379. * Returns the AbstractMesh.
  12380. */
  12381. AbstractMesh.prototype.disableEdgesRendering = function () {
  12382. if (this._edgesRenderer !== undefined) {
  12383. this._edgesRenderer.dispose();
  12384. this._edgesRenderer = undefined;
  12385. }
  12386. return this;
  12387. };
  12388. /**
  12389. * Enables the edge rendering mode on the mesh.
  12390. * This mode makes the mesh edges visible.
  12391. * Returns the AbstractMesh.
  12392. */
  12393. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12394. if (epsilon === void 0) { epsilon = 0.95; }
  12395. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12396. this.disableEdgesRendering();
  12397. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12398. return this;
  12399. };
  12400. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12401. /**
  12402. * Returns true if the mesh is blocked. Used by the class Mesh.
  12403. * Returns the boolean `false` by default.
  12404. */
  12405. get: function () {
  12406. return false;
  12407. },
  12408. enumerable: true,
  12409. configurable: true
  12410. });
  12411. /**
  12412. * Returns the mesh itself by default, used by the class Mesh.
  12413. * Returned type : AbstractMesh
  12414. */
  12415. AbstractMesh.prototype.getLOD = function (camera) {
  12416. return this;
  12417. };
  12418. /**
  12419. * Returns 0 by default, used by the class Mesh.
  12420. * Returns an integer.
  12421. */
  12422. AbstractMesh.prototype.getTotalVertices = function () {
  12423. return 0;
  12424. };
  12425. /**
  12426. * Returns null by default, used by the class Mesh.
  12427. * Returned type : integer array
  12428. */
  12429. AbstractMesh.prototype.getIndices = function () {
  12430. return null;
  12431. };
  12432. /**
  12433. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12434. * Returned type : float array or Float32Array
  12435. */
  12436. AbstractMesh.prototype.getVerticesData = function (kind) {
  12437. return null;
  12438. };
  12439. /** Returns false by default, used by the class Mesh.
  12440. * Returns a boolean
  12441. */
  12442. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12443. return false;
  12444. };
  12445. /**
  12446. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12447. * Returns a BoundingInfo
  12448. */
  12449. AbstractMesh.prototype.getBoundingInfo = function () {
  12450. if (this._masterMesh) {
  12451. return this._masterMesh.getBoundingInfo();
  12452. }
  12453. if (!this._boundingInfo) {
  12454. this._updateBoundingInfo();
  12455. }
  12456. return this._boundingInfo;
  12457. };
  12458. /**
  12459. * Sets a mesh new object BoundingInfo.
  12460. * Returns the AbstractMesh.
  12461. */
  12462. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12463. this._boundingInfo = boundingInfo;
  12464. return this;
  12465. };
  12466. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12467. get: function () {
  12468. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. AbstractMesh.prototype._preActivate = function () {
  12474. };
  12475. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12476. };
  12477. AbstractMesh.prototype._activate = function (renderId) {
  12478. this._renderId = renderId;
  12479. };
  12480. /**
  12481. * Returns the last update of the World matrix
  12482. * Returns a Matrix.
  12483. */
  12484. AbstractMesh.prototype.getWorldMatrix = function () {
  12485. if (this._masterMesh) {
  12486. return this._masterMesh.getWorldMatrix();
  12487. }
  12488. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12489. this.computeWorldMatrix();
  12490. }
  12491. return this._worldMatrix;
  12492. };
  12493. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12494. /**
  12495. * Returns directly the last state of the mesh World matrix.
  12496. * A Matrix is returned.
  12497. */
  12498. get: function () {
  12499. return this._worldMatrix;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12505. /**
  12506. * Returns the current mesh absolute position.
  12507. * Retuns a Vector3.
  12508. */
  12509. get: function () {
  12510. return this._absolutePosition;
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. /**
  12516. * Prevents the World matrix to be computed any longer.
  12517. * Returns the AbstractMesh.
  12518. */
  12519. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12520. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12521. this.computeWorldMatrix(true);
  12522. this._isWorldMatrixFrozen = true;
  12523. return this;
  12524. };
  12525. /**
  12526. * Allows back the World matrix computation.
  12527. * Returns the AbstractMesh.
  12528. */
  12529. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12530. this._isWorldMatrixFrozen = false;
  12531. this.computeWorldMatrix(true);
  12532. return this;
  12533. };
  12534. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12535. /**
  12536. * True if the World matrix has been frozen.
  12537. * Returns a boolean.
  12538. */
  12539. get: function () {
  12540. return this._isWorldMatrixFrozen;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. /**
  12546. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12547. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12548. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12549. * The passed axis is also normalized.
  12550. * Returns the AbstractMesh.
  12551. */
  12552. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12553. axis.normalize();
  12554. if (!this.rotationQuaternion) {
  12555. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12556. this.rotation = BABYLON.Vector3.Zero();
  12557. }
  12558. var rotationQuaternion;
  12559. if (!space || space === BABYLON.Space.LOCAL) {
  12560. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12561. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12562. }
  12563. else {
  12564. if (this.parent) {
  12565. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12566. invertParentWorldMatrix.invert();
  12567. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12568. }
  12569. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12570. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12571. }
  12572. return this;
  12573. };
  12574. /**
  12575. * Translates the mesh along the axis vector for the passed distance in the given space.
  12576. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12577. * Returns the AbstractMesh.
  12578. */
  12579. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12580. var displacementVector = axis.scale(distance);
  12581. if (!space || space === BABYLON.Space.LOCAL) {
  12582. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12583. this.setPositionWithLocalVector(tempV3);
  12584. }
  12585. else {
  12586. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12587. }
  12588. return this;
  12589. };
  12590. /**
  12591. * Adds a rotation step to the mesh current rotation.
  12592. * x, y, z are Euler angles expressed in radians.
  12593. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12594. * This means this rotation is made in the mesh local space only.
  12595. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12596. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12597. * ```javascript
  12598. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12599. * ```
  12600. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12601. * 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.
  12602. * Returns the AbstractMesh.
  12603. */
  12604. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12605. var rotationQuaternion;
  12606. if (this.rotationQuaternion) {
  12607. rotationQuaternion = this.rotationQuaternion;
  12608. }
  12609. else {
  12610. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12611. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12612. }
  12613. var accumulation = BABYLON.Tmp.Quaternion[0];
  12614. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12615. rotationQuaternion.multiplyInPlace(accumulation);
  12616. if (!this.rotationQuaternion) {
  12617. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12618. }
  12619. return this;
  12620. };
  12621. /**
  12622. * Retuns the mesh absolute position in the World.
  12623. * Returns a Vector3.
  12624. */
  12625. AbstractMesh.prototype.getAbsolutePosition = function () {
  12626. this.computeWorldMatrix();
  12627. return this._absolutePosition;
  12628. };
  12629. /**
  12630. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12631. * Returns the AbstractMesh.
  12632. */
  12633. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12634. if (!absolutePosition) {
  12635. return;
  12636. }
  12637. var absolutePositionX;
  12638. var absolutePositionY;
  12639. var absolutePositionZ;
  12640. if (absolutePosition.x === undefined) {
  12641. if (arguments.length < 3) {
  12642. return;
  12643. }
  12644. absolutePositionX = arguments[0];
  12645. absolutePositionY = arguments[1];
  12646. absolutePositionZ = arguments[2];
  12647. }
  12648. else {
  12649. absolutePositionX = absolutePosition.x;
  12650. absolutePositionY = absolutePosition.y;
  12651. absolutePositionZ = absolutePosition.z;
  12652. }
  12653. if (this.parent) {
  12654. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12655. invertParentWorldMatrix.invert();
  12656. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12657. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12658. }
  12659. else {
  12660. this.position.x = absolutePositionX;
  12661. this.position.y = absolutePositionY;
  12662. this.position.z = absolutePositionZ;
  12663. }
  12664. return this;
  12665. };
  12666. // ================================== Point of View Movement =================================
  12667. /**
  12668. * Perform relative position change from the point of view of behind the front of the mesh.
  12669. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12670. * Supports definition of mesh facing forward or backward.
  12671. * @param {number} amountRight
  12672. * @param {number} amountUp
  12673. * @param {number} amountForward
  12674. *
  12675. * Returns the AbstractMesh.
  12676. */
  12677. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12678. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12679. return this;
  12680. };
  12681. /**
  12682. * Calculate relative position change from the point of view of behind the front of the mesh.
  12683. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12684. * Supports definition of mesh facing forward or backward.
  12685. * @param {number} amountRight
  12686. * @param {number} amountUp
  12687. * @param {number} amountForward
  12688. *
  12689. * Returns a new Vector3.
  12690. */
  12691. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12692. var rotMatrix = new BABYLON.Matrix();
  12693. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12694. rotQuaternion.toRotationMatrix(rotMatrix);
  12695. var translationDelta = BABYLON.Vector3.Zero();
  12696. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12698. return translationDelta;
  12699. };
  12700. // ================================== Point of View Rotation =================================
  12701. /**
  12702. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12703. * Supports definition of mesh facing forward or backward.
  12704. * @param {number} flipBack
  12705. * @param {number} twirlClockwise
  12706. * @param {number} tiltRight
  12707. *
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12711. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12712. return this;
  12713. };
  12714. /**
  12715. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12716. * Supports definition of mesh facing forward or backward.
  12717. * @param {number} flipBack
  12718. * @param {number} twirlClockwise
  12719. * @param {number} tiltRight
  12720. *
  12721. * Returns a new Vector3.
  12722. */
  12723. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12724. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12725. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12726. };
  12727. /**
  12728. * Sets a new pivot matrix to the mesh.
  12729. * Returns the AbstractMesh.
  12730. */
  12731. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12732. this._pivotMatrix = matrix;
  12733. this._cache.pivotMatrixUpdated = true;
  12734. return this;
  12735. };
  12736. /**
  12737. * Returns the mesh pivot matrix.
  12738. * Default : Identity.
  12739. * A Matrix is returned.
  12740. */
  12741. AbstractMesh.prototype.getPivotMatrix = function () {
  12742. return this._pivotMatrix;
  12743. };
  12744. AbstractMesh.prototype._isSynchronized = function () {
  12745. if (this._isDirty) {
  12746. return false;
  12747. }
  12748. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12749. return false;
  12750. if (this._cache.pivotMatrixUpdated) {
  12751. return false;
  12752. }
  12753. if (this.infiniteDistance) {
  12754. return false;
  12755. }
  12756. if (!this._cache.position.equals(this.position))
  12757. return false;
  12758. if (this.rotationQuaternion) {
  12759. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12760. return false;
  12761. }
  12762. if (!this._cache.rotation.equals(this.rotation))
  12763. return false;
  12764. if (!this._cache.scaling.equals(this.scaling))
  12765. return false;
  12766. return true;
  12767. };
  12768. AbstractMesh.prototype._initCache = function () {
  12769. _super.prototype._initCache.call(this);
  12770. this._cache.localMatrixUpdated = false;
  12771. this._cache.position = BABYLON.Vector3.Zero();
  12772. this._cache.scaling = BABYLON.Vector3.Zero();
  12773. this._cache.rotation = BABYLON.Vector3.Zero();
  12774. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12775. this._cache.billboardMode = -1;
  12776. };
  12777. AbstractMesh.prototype.markAsDirty = function (property) {
  12778. if (property === "rotation") {
  12779. this.rotationQuaternion = null;
  12780. }
  12781. this._currentRenderId = Number.MAX_VALUE;
  12782. this._isDirty = true;
  12783. return this;
  12784. };
  12785. /**
  12786. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12787. * Returns the AbstractMesh.
  12788. */
  12789. AbstractMesh.prototype._updateBoundingInfo = function () {
  12790. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12791. this._boundingInfo.update(this.worldMatrixFromCache);
  12792. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12793. return this;
  12794. };
  12795. /**
  12796. * Update a mesh's children BoundingInfo objects only.
  12797. * Returns the AbstractMesh.
  12798. */
  12799. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12800. if (!this.subMeshes) {
  12801. return;
  12802. }
  12803. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12804. var subMesh = this.subMeshes[subIndex];
  12805. if (!subMesh.IsGlobal) {
  12806. subMesh.updateBoundingInfo(matrix);
  12807. }
  12808. }
  12809. return this;
  12810. };
  12811. /**
  12812. * Computes the mesh World matrix and returns it.
  12813. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12814. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12815. * If the parameter `force`is set to `true`, the actual computation is done.
  12816. * Returns the mesh World Matrix.
  12817. */
  12818. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12819. if (this._isWorldMatrixFrozen) {
  12820. return this._worldMatrix;
  12821. }
  12822. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  12823. this._currentRenderId = this.getScene().getRenderId();
  12824. return this._worldMatrix;
  12825. }
  12826. this._cache.position.copyFrom(this.position);
  12827. this._cache.scaling.copyFrom(this.scaling);
  12828. this._cache.pivotMatrixUpdated = false;
  12829. this._cache.billboardMode = this.billboardMode;
  12830. this._currentRenderId = this.getScene().getRenderId();
  12831. this._isDirty = false;
  12832. // Scaling
  12833. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12834. // Rotation
  12835. //rotate, if quaternion is set and rotation was used
  12836. if (this.rotationQuaternion) {
  12837. var len = this.rotation.length();
  12838. if (len) {
  12839. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12840. this.rotation.copyFromFloats(0, 0, 0);
  12841. }
  12842. }
  12843. if (this.rotationQuaternion) {
  12844. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12845. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12846. }
  12847. else {
  12848. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12849. this._cache.rotation.copyFrom(this.rotation);
  12850. }
  12851. // Translation
  12852. if (this.infiniteDistance && !this.parent) {
  12853. var camera = this.getScene().activeCamera;
  12854. if (camera) {
  12855. var cameraWorldMatrix = camera.getWorldMatrix();
  12856. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12857. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12858. }
  12859. }
  12860. else {
  12861. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12862. }
  12863. // Composing transformations
  12864. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12865. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12866. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12867. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12868. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12869. // Need to decompose each rotation here
  12870. var currentPosition = BABYLON.Tmp.Vector3[3];
  12871. if (this.parent && this.parent.getWorldMatrix) {
  12872. if (this._meshToBoneReferal) {
  12873. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12874. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12875. }
  12876. else {
  12877. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12878. }
  12879. }
  12880. else {
  12881. currentPosition.copyFrom(this.position);
  12882. }
  12883. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12884. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12885. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12886. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12887. }
  12888. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12889. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12890. }
  12891. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12892. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12893. }
  12894. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12895. }
  12896. else {
  12897. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12898. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12899. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12900. }
  12901. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12902. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12903. }
  12904. // Local world
  12905. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12906. // Parent
  12907. if (this.parent && this.parent.getWorldMatrix) {
  12908. this._markSyncedWithParent();
  12909. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12910. if (this._meshToBoneReferal) {
  12911. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12912. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12913. }
  12914. else {
  12915. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12916. }
  12917. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12918. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12919. this._worldMatrix.copyFrom(this._localWorld);
  12920. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12921. }
  12922. else {
  12923. if (this._meshToBoneReferal) {
  12924. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12925. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12926. }
  12927. else {
  12928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12929. }
  12930. }
  12931. }
  12932. else {
  12933. this._worldMatrix.copyFrom(this._localWorld);
  12934. }
  12935. // Bounding info
  12936. this._updateBoundingInfo();
  12937. // Absolute position
  12938. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12939. // Callbacks
  12940. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12941. if (!this._poseMatrix) {
  12942. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12943. }
  12944. return this._worldMatrix;
  12945. };
  12946. /**
  12947. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12948. * @param func: callback function to add
  12949. *
  12950. * Returns the AbstractMesh.
  12951. */
  12952. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12953. this.onAfterWorldMatrixUpdateObservable.add(func);
  12954. return this;
  12955. };
  12956. /**
  12957. * Removes a registered callback function.
  12958. * Returns the AbstractMesh.
  12959. */
  12960. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12961. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12962. return this;
  12963. };
  12964. /**
  12965. * Sets the mesh position in its local space.
  12966. * Returns the AbstractMesh.
  12967. */
  12968. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12969. this.computeWorldMatrix();
  12970. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12971. return this;
  12972. };
  12973. /**
  12974. * Returns the mesh position in the local space from the current World matrix values.
  12975. * Returns a new Vector3.
  12976. */
  12977. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12978. this.computeWorldMatrix();
  12979. var invLocalWorldMatrix = this._localWorld.clone();
  12980. invLocalWorldMatrix.invert();
  12981. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12982. };
  12983. /**
  12984. * Translates the mesh along the passed Vector3 in its local space.
  12985. * Returns the AbstractMesh.
  12986. */
  12987. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12988. this.computeWorldMatrix(true);
  12989. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12990. return this;
  12991. };
  12992. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12993. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12994. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12995. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12996. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12997. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12998. /// <returns>Mesh oriented towards targetMesh</returns>
  12999. if (yawCor === void 0) { yawCor = 0; }
  13000. if (pitchCor === void 0) { pitchCor = 0; }
  13001. if (rollCor === void 0) { rollCor = 0; }
  13002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13003. var dv = AbstractMesh._lookAtVectorCache;
  13004. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13005. targetPoint.subtractToRef(pos, dv);
  13006. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13007. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13008. var pitch = Math.atan2(dv.y, len);
  13009. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13010. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13011. return this;
  13012. };
  13013. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13014. this._meshToBoneReferal = affectedMesh;
  13015. this.parent = bone;
  13016. if (bone.getWorldMatrix().determinant() < 0) {
  13017. this.scalingDeterminant *= -1;
  13018. }
  13019. return this;
  13020. };
  13021. AbstractMesh.prototype.detachFromBone = function () {
  13022. if (this.parent.getWorldMatrix().determinant() < 0) {
  13023. this.scalingDeterminant *= -1;
  13024. }
  13025. this._meshToBoneReferal = null;
  13026. this.parent = null;
  13027. return this;
  13028. };
  13029. /**
  13030. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13031. * A mesh is in the frustum if its bounding box intersects the frustum.
  13032. * Boolean returned.
  13033. */
  13034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13035. return this._boundingInfo.isInFrustum(frustumPlanes);
  13036. };
  13037. /**
  13038. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13039. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13040. * Boolean returned.
  13041. */
  13042. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13043. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13044. ;
  13045. };
  13046. /**
  13047. * True if the mesh intersects another mesh or a SolidParticle object.
  13048. * 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)
  13049. * Returns a boolean.
  13050. */
  13051. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13052. if (!this._boundingInfo || !mesh._boundingInfo) {
  13053. return false;
  13054. }
  13055. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13056. };
  13057. /**
  13058. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13059. * Returns a boolean.
  13060. */
  13061. AbstractMesh.prototype.intersectsPoint = function (point) {
  13062. if (!this._boundingInfo) {
  13063. return false;
  13064. }
  13065. return this._boundingInfo.intersectsPoint(point);
  13066. };
  13067. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13068. return this.physicsImpostor;
  13069. };
  13070. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13071. if (!camera) {
  13072. camera = this.getScene().activeCamera;
  13073. }
  13074. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13075. };
  13076. /**
  13077. * Returns the distance from the mesh to the active camera.
  13078. * Returns a float.
  13079. */
  13080. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13081. if (!camera) {
  13082. camera = this.getScene().activeCamera;
  13083. }
  13084. return this.absolutePosition.subtract(camera.position).length();
  13085. };
  13086. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13087. if (!this.physicsImpostor) {
  13088. return;
  13089. }
  13090. this.physicsImpostor.applyImpulse(force, contactPoint);
  13091. return this;
  13092. };
  13093. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13094. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13095. return;
  13096. }
  13097. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13098. mainPivot: pivot1,
  13099. connectedPivot: pivot2,
  13100. nativeParams: options
  13101. });
  13102. return this;
  13103. };
  13104. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13105. // Collisions
  13106. /**
  13107. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13108. * Default `false`.
  13109. */
  13110. get: function () {
  13111. return this._checkCollisions;
  13112. },
  13113. set: function (collisionEnabled) {
  13114. this._checkCollisions = collisionEnabled;
  13115. if (this.getScene().workerCollisions) {
  13116. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13117. }
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13123. var globalPosition = this.getAbsolutePosition();
  13124. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13125. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13126. this._collider.radius = this.ellipsoid;
  13127. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13128. return this;
  13129. };
  13130. // Submeshes octree
  13131. /**
  13132. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13133. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13134. * Returns an Octree of submeshes.
  13135. */
  13136. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13137. if (maxCapacity === void 0) { maxCapacity = 64; }
  13138. if (maxDepth === void 0) { maxDepth = 2; }
  13139. if (!this._submeshesOctree) {
  13140. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13141. }
  13142. this.computeWorldMatrix(true);
  13143. // Update octree
  13144. var bbox = this.getBoundingInfo().boundingBox;
  13145. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13146. return this._submeshesOctree;
  13147. };
  13148. // Collisions
  13149. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13150. this._generatePointsArray();
  13151. // Transformation
  13152. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13153. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13154. subMesh._lastColliderWorldVertices = [];
  13155. subMesh._trianglePlanes = [];
  13156. var start = subMesh.verticesStart;
  13157. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13158. for (var i = start; i < end; i++) {
  13159. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13160. }
  13161. }
  13162. // Collide
  13163. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13164. if (collider.collisionFound) {
  13165. collider.collidedMesh = this;
  13166. }
  13167. return this;
  13168. };
  13169. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13170. var subMeshes;
  13171. var len;
  13172. // Octrees
  13173. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13174. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13175. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13176. len = intersections.length;
  13177. subMeshes = intersections.data;
  13178. }
  13179. else {
  13180. subMeshes = this.subMeshes;
  13181. len = subMeshes.length;
  13182. }
  13183. for (var index = 0; index < len; index++) {
  13184. var subMesh = subMeshes[index];
  13185. // Bounding test
  13186. if (len > 1 && !subMesh._checkCollision(collider))
  13187. continue;
  13188. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13189. }
  13190. return this;
  13191. };
  13192. AbstractMesh.prototype._checkCollision = function (collider) {
  13193. // Bounding box test
  13194. if (!this._boundingInfo._checkCollision(collider))
  13195. return this;
  13196. // Transformation matrix
  13197. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13198. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13199. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13200. return this;
  13201. };
  13202. // Picking
  13203. AbstractMesh.prototype._generatePointsArray = function () {
  13204. return false;
  13205. };
  13206. /**
  13207. * Checks if the passed Ray intersects with the mesh.
  13208. * Returns an object PickingInfo.
  13209. */
  13210. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13211. var pickingInfo = new BABYLON.PickingInfo();
  13212. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13213. return pickingInfo;
  13214. }
  13215. if (!this._generatePointsArray()) {
  13216. return pickingInfo;
  13217. }
  13218. var intersectInfo = null;
  13219. // Octrees
  13220. var subMeshes;
  13221. var len;
  13222. if (this._submeshesOctree && this.useOctreeForPicking) {
  13223. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13224. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13225. len = intersections.length;
  13226. subMeshes = intersections.data;
  13227. }
  13228. else {
  13229. subMeshes = this.subMeshes;
  13230. len = subMeshes.length;
  13231. }
  13232. for (var index = 0; index < len; index++) {
  13233. var subMesh = subMeshes[index];
  13234. // Bounding test
  13235. if (len > 1 && !subMesh.canIntersects(ray))
  13236. continue;
  13237. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13238. if (currentIntersectInfo) {
  13239. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13240. intersectInfo = currentIntersectInfo;
  13241. intersectInfo.subMeshId = index;
  13242. if (fastCheck) {
  13243. break;
  13244. }
  13245. }
  13246. }
  13247. }
  13248. if (intersectInfo) {
  13249. // Get picked point
  13250. var world = this.getWorldMatrix();
  13251. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13252. var direction = ray.direction.clone();
  13253. direction = direction.scale(intersectInfo.distance);
  13254. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13255. var pickedPoint = worldOrigin.add(worldDirection);
  13256. // Return result
  13257. pickingInfo.hit = true;
  13258. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13259. pickingInfo.pickedPoint = pickedPoint;
  13260. pickingInfo.pickedMesh = this;
  13261. pickingInfo.bu = intersectInfo.bu;
  13262. pickingInfo.bv = intersectInfo.bv;
  13263. pickingInfo.faceId = intersectInfo.faceId;
  13264. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13265. return pickingInfo;
  13266. }
  13267. return pickingInfo;
  13268. };
  13269. /**
  13270. * Clones the mesh, used by the class Mesh.
  13271. * Just returns `null` for an AbstractMesh.
  13272. */
  13273. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13274. return null;
  13275. };
  13276. /**
  13277. * Disposes all the mesh submeshes.
  13278. * Returns the AbstractMesh.
  13279. */
  13280. AbstractMesh.prototype.releaseSubMeshes = function () {
  13281. if (this.subMeshes) {
  13282. while (this.subMeshes.length) {
  13283. this.subMeshes[0].dispose();
  13284. }
  13285. }
  13286. else {
  13287. this.subMeshes = new Array();
  13288. }
  13289. return this;
  13290. };
  13291. /**
  13292. * Disposes the AbstractMesh.
  13293. * Some internal references are kept for further use.
  13294. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13295. * Returns nothing.
  13296. */
  13297. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13298. var _this = this;
  13299. var index;
  13300. // Action manager
  13301. if (this.actionManager) {
  13302. this.actionManager.dispose();
  13303. this.actionManager = null;
  13304. }
  13305. // Skeleton
  13306. this.skeleton = null;
  13307. // Animations
  13308. this.getScene().stopAnimation(this);
  13309. // Physics
  13310. if (this.physicsImpostor) {
  13311. this.physicsImpostor.dispose();
  13312. }
  13313. // Intersections in progress
  13314. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13315. var other = this._intersectionsInProgress[index];
  13316. var pos = other._intersectionsInProgress.indexOf(this);
  13317. other._intersectionsInProgress.splice(pos, 1);
  13318. }
  13319. this._intersectionsInProgress = [];
  13320. // Lights
  13321. var lights = this.getScene().lights;
  13322. lights.forEach(function (light) {
  13323. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13324. if (meshIndex !== -1) {
  13325. light.includedOnlyMeshes.splice(meshIndex, 1);
  13326. }
  13327. meshIndex = light.excludedMeshes.indexOf(_this);
  13328. if (meshIndex !== -1) {
  13329. light.excludedMeshes.splice(meshIndex, 1);
  13330. }
  13331. // Shadow generators
  13332. var generator = light.getShadowGenerator();
  13333. if (generator) {
  13334. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13335. if (meshIndex !== -1) {
  13336. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13337. }
  13338. }
  13339. });
  13340. // Edges
  13341. if (this._edgesRenderer) {
  13342. this._edgesRenderer.dispose();
  13343. this._edgesRenderer = null;
  13344. }
  13345. // SubMeshes
  13346. if (this.getClassName() !== "InstancedMesh") {
  13347. this.releaseSubMeshes();
  13348. }
  13349. // Engine
  13350. this.getScene().getEngine().wipeCaches();
  13351. // Remove from scene
  13352. this.getScene().removeMesh(this);
  13353. if (!doNotRecurse) {
  13354. // Particles
  13355. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13356. if (this.getScene().particleSystems[index].emitter === this) {
  13357. this.getScene().particleSystems[index].dispose();
  13358. index--;
  13359. }
  13360. }
  13361. // Children
  13362. var objects = this.getDescendants(true);
  13363. for (index = 0; index < objects.length; index++) {
  13364. objects[index].dispose();
  13365. }
  13366. }
  13367. else {
  13368. var childMeshes = this.getChildMeshes(true);
  13369. for (index = 0; index < childMeshes.length; index++) {
  13370. var child = childMeshes[index];
  13371. child.parent = null;
  13372. child.computeWorldMatrix(true);
  13373. }
  13374. }
  13375. // facet data
  13376. if (this._facetDataEnabled) {
  13377. this.disableFacetData();
  13378. }
  13379. this.onAfterWorldMatrixUpdateObservable.clear();
  13380. this.onCollideObservable.clear();
  13381. this.onCollisionPositionChangeObservable.clear();
  13382. this._isDisposed = true;
  13383. _super.prototype.dispose.call(this);
  13384. };
  13385. /**
  13386. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13387. * This Vector3 is expressed in the World space.
  13388. */
  13389. AbstractMesh.prototype.getDirection = function (localAxis) {
  13390. var result = BABYLON.Vector3.Zero();
  13391. this.getDirectionToRef(localAxis, result);
  13392. return result;
  13393. };
  13394. /**
  13395. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13396. * localAxis is expressed in the mesh local space.
  13397. * result is computed in the Wordl space from the mesh World matrix.
  13398. * Returns the AbstractMesh.
  13399. */
  13400. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13401. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13402. return this;
  13403. };
  13404. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13406. if (this.getScene().getRenderId() == 0) {
  13407. this.computeWorldMatrix(true);
  13408. }
  13409. var wm = this.getWorldMatrix();
  13410. if (space == BABYLON.Space.WORLD) {
  13411. var tmat = BABYLON.Tmp.Matrix[0];
  13412. wm.invertToRef(tmat);
  13413. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13414. }
  13415. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13416. this._pivotMatrix.m[12] = -point.x;
  13417. this._pivotMatrix.m[13] = -point.y;
  13418. this._pivotMatrix.m[14] = -point.z;
  13419. this._cache.pivotMatrixUpdated = true;
  13420. return this;
  13421. };
  13422. /**
  13423. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13424. */
  13425. AbstractMesh.prototype.getPivotPoint = function () {
  13426. var point = BABYLON.Vector3.Zero();
  13427. this.getPivotPointToRef(point);
  13428. return point;
  13429. };
  13430. /**
  13431. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13432. * Returns the AbstractMesh.
  13433. */
  13434. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13435. result.x = -this._pivotMatrix.m[12];
  13436. result.y = -this._pivotMatrix.m[13];
  13437. result.z = -this._pivotMatrix.m[14];
  13438. return this;
  13439. };
  13440. /**
  13441. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13442. */
  13443. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13444. var point = BABYLON.Vector3.Zero();
  13445. this.getAbsolutePivotPointToRef(point);
  13446. return point;
  13447. };
  13448. /**
  13449. * Defines the passed mesh as the parent of the current mesh.
  13450. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13451. * Returns the AbstractMesh.
  13452. */
  13453. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13454. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13455. var child = this;
  13456. var parent = mesh;
  13457. if (mesh == null) {
  13458. if (child.parent && keepWorldPositionRotation) {
  13459. var rotation = BABYLON.Tmp.Quaternion[0];
  13460. var position = BABYLON.Tmp.Vector3[0];
  13461. var scale = BABYLON.Tmp.Vector3[1];
  13462. child.getWorldMatrix().decompose(scale, rotation, position);
  13463. if (child.rotationQuaternion) {
  13464. child.rotationQuaternion.copyFrom(rotation);
  13465. }
  13466. else {
  13467. rotation.toEulerAnglesToRef(child.rotation);
  13468. }
  13469. child.position.x = position.x;
  13470. child.position.y = position.y;
  13471. child.position.z = position.z;
  13472. }
  13473. }
  13474. else {
  13475. if (keepWorldPositionRotation) {
  13476. var rotation = BABYLON.Tmp.Quaternion[0];
  13477. var position = BABYLON.Tmp.Vector3[0];
  13478. var scale = BABYLON.Tmp.Vector3[1];
  13479. var m1 = BABYLON.Tmp.Matrix[0];
  13480. var m2 = BABYLON.Tmp.Matrix[1];
  13481. parent.getWorldMatrix().decompose(scale, rotation, position);
  13482. rotation.toRotationMatrix(m1);
  13483. m2.setTranslation(position);
  13484. m2.multiplyToRef(m1, m1);
  13485. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13486. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13487. m.decompose(scale, rotation, position);
  13488. if (child.rotationQuaternion) {
  13489. child.rotationQuaternion.copyFrom(rotation);
  13490. }
  13491. else {
  13492. rotation.toEulerAnglesToRef(child.rotation);
  13493. }
  13494. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13495. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13496. m.decompose(scale, rotation, position);
  13497. child.position.x = position.x;
  13498. child.position.y = position.y;
  13499. child.position.z = position.z;
  13500. }
  13501. }
  13502. child.parent = parent;
  13503. return this;
  13504. };
  13505. /**
  13506. * Adds the passed mesh as a child to the current mesh.
  13507. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13508. * Returns the AbstractMesh.
  13509. */
  13510. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13511. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13512. mesh.setParent(this, keepWorldPositionRotation);
  13513. return this;
  13514. };
  13515. /**
  13516. * Removes the passed mesh from the current mesh children list.
  13517. * Returns the AbstractMesh.
  13518. */
  13519. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13520. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13521. mesh.setParent(null, keepWorldPositionRotation);
  13522. return this;
  13523. };
  13524. /**
  13525. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13526. * Returns the AbstractMesh.
  13527. */
  13528. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13529. result.x = this._pivotMatrix.m[12];
  13530. result.y = this._pivotMatrix.m[13];
  13531. result.z = this._pivotMatrix.m[14];
  13532. this.getPivotPointToRef(result);
  13533. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13534. return this;
  13535. };
  13536. // Facet data
  13537. /**
  13538. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13539. * Returns the AbstractMesh.
  13540. */
  13541. AbstractMesh.prototype._initFacetData = function () {
  13542. if (!this._facetNormals) {
  13543. this._facetNormals = new Array();
  13544. }
  13545. if (!this._facetPositions) {
  13546. this._facetPositions = new Array();
  13547. }
  13548. if (!this._facetPartitioning) {
  13549. this._facetPartitioning = new Array();
  13550. }
  13551. this._facetNb = this.getIndices().length / 3;
  13552. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13553. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13554. for (var f = 0; f < this._facetNb; f++) {
  13555. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13556. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13557. }
  13558. this._facetDataEnabled = true;
  13559. return this;
  13560. };
  13561. /**
  13562. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13563. * This method can be called within the render loop.
  13564. * 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.
  13565. * Returns the AbstractMesh.
  13566. */
  13567. AbstractMesh.prototype.updateFacetData = function () {
  13568. if (!this._facetDataEnabled) {
  13569. this._initFacetData();
  13570. }
  13571. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13572. var indices = this.getIndices();
  13573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13574. var bInfo = this.getBoundingInfo();
  13575. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13576. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13577. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13578. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13579. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13580. this._subDiv.max = this._partitioningSubdivisions;
  13581. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13582. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13583. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13584. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13585. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13586. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13587. // set the parameters for ComputeNormals()
  13588. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13589. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13590. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13591. this._facetParameters.bInfo = bInfo;
  13592. this._facetParameters.bbSize = this._bbSize;
  13593. this._facetParameters.subDiv = this._subDiv;
  13594. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13595. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13596. return this;
  13597. };
  13598. /**
  13599. * Returns the facetLocalNormals array.
  13600. * The normals are expressed in the mesh local space.
  13601. */
  13602. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13603. if (!this._facetNormals) {
  13604. this.updateFacetData();
  13605. }
  13606. return this._facetNormals;
  13607. };
  13608. /**
  13609. * Returns the facetLocalPositions array.
  13610. * The facet positions are expressed in the mesh local space.
  13611. */
  13612. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13613. if (!this._facetPositions) {
  13614. this.updateFacetData();
  13615. }
  13616. return this._facetPositions;
  13617. };
  13618. /**
  13619. * Returns the facetLocalPartioning array.
  13620. */
  13621. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13622. if (!this._facetPartitioning) {
  13623. this.updateFacetData();
  13624. }
  13625. return this._facetPartitioning;
  13626. };
  13627. /**
  13628. * Returns the i-th facet position in the world system.
  13629. * This method allocates a new Vector3 per call.
  13630. */
  13631. AbstractMesh.prototype.getFacetPosition = function (i) {
  13632. var pos = BABYLON.Vector3.Zero();
  13633. this.getFacetPositionToRef(i, pos);
  13634. return pos;
  13635. };
  13636. /**
  13637. * Sets the reference Vector3 with the i-th facet position in the world system.
  13638. * Returns the AbstractMesh.
  13639. */
  13640. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13641. var localPos = (this.getFacetLocalPositions())[i];
  13642. var world = this.getWorldMatrix();
  13643. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13644. return this;
  13645. };
  13646. /**
  13647. * Returns the i-th facet normal in the world system.
  13648. * This method allocates a new Vector3 per call.
  13649. */
  13650. AbstractMesh.prototype.getFacetNormal = function (i) {
  13651. var norm = BABYLON.Vector3.Zero();
  13652. this.getFacetNormalToRef(i, norm);
  13653. return norm;
  13654. };
  13655. /**
  13656. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13657. * Returns the AbstractMesh.
  13658. */
  13659. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13660. var localNorm = (this.getFacetLocalNormals())[i];
  13661. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13662. return this;
  13663. };
  13664. /**
  13665. * 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).
  13666. */
  13667. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13668. var bInfo = this.getBoundingInfo();
  13669. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13670. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13671. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13672. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13673. return null;
  13674. }
  13675. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13676. };
  13677. /**
  13678. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13679. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13680. * 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.
  13681. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13682. * 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.
  13683. */
  13684. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13685. if (checkFace === void 0) { checkFace = false; }
  13686. if (facing === void 0) { facing = true; }
  13687. var world = this.getWorldMatrix();
  13688. var invMat = BABYLON.Tmp.Matrix[5];
  13689. world.invertToRef(invMat);
  13690. var invVect = BABYLON.Tmp.Vector3[8];
  13691. var closest = null;
  13692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13693. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13694. if (projected) {
  13695. // tranform the local computed projected vector to world coordinates
  13696. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13697. }
  13698. return closest;
  13699. };
  13700. /**
  13701. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13702. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13703. * 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.
  13704. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13705. * 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.
  13706. */
  13707. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13708. if (checkFace === void 0) { checkFace = false; }
  13709. if (facing === void 0) { facing = true; }
  13710. var closest = null;
  13711. var tmpx = 0.0;
  13712. var tmpy = 0.0;
  13713. var tmpz = 0.0;
  13714. var d = 0.0; // tmp dot facet normal * facet position
  13715. var t0 = 0.0;
  13716. var projx = 0.0;
  13717. var projy = 0.0;
  13718. var projz = 0.0;
  13719. // Get all the facets in the same partitioning block than (x, y, z)
  13720. var facetPositions = this.getFacetLocalPositions();
  13721. var facetNormals = this.getFacetLocalNormals();
  13722. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13723. if (!facetsInBlock) {
  13724. return null;
  13725. }
  13726. // Get the closest facet to (x, y, z)
  13727. var shortest = Number.MAX_VALUE; // init distance vars
  13728. var tmpDistance = shortest;
  13729. var fib; // current facet in the block
  13730. var norm; // current facet normal
  13731. var p0; // current facet barycenter position
  13732. // loop on all the facets in the current partitioning block
  13733. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13734. fib = facetsInBlock[idx];
  13735. norm = facetNormals[fib];
  13736. p0 = facetPositions[fib];
  13737. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13738. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13739. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13740. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13741. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13742. projx = x + norm.x * t0;
  13743. projy = y + norm.y * t0;
  13744. projz = z + norm.z * t0;
  13745. tmpx = projx - x;
  13746. tmpy = projy - y;
  13747. tmpz = projz - z;
  13748. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13749. if (tmpDistance < shortest) {
  13750. shortest = tmpDistance;
  13751. closest = fib;
  13752. if (projected) {
  13753. projected.x = projx;
  13754. projected.y = projy;
  13755. projected.z = projz;
  13756. }
  13757. }
  13758. }
  13759. }
  13760. return closest;
  13761. };
  13762. /**
  13763. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13764. */
  13765. AbstractMesh.prototype.getFacetDataParameters = function () {
  13766. return this._facetParameters;
  13767. };
  13768. /**
  13769. * Disables the feature FacetData and frees the related memory.
  13770. * Returns the AbstractMesh.
  13771. */
  13772. AbstractMesh.prototype.disableFacetData = function () {
  13773. if (this._facetDataEnabled) {
  13774. this._facetDataEnabled = false;
  13775. this._facetPositions = null;
  13776. this._facetNormals = null;
  13777. this._facetPartitioning = null;
  13778. this._facetParameters = null;
  13779. }
  13780. return this;
  13781. };
  13782. return AbstractMesh;
  13783. }(BABYLON.Node));
  13784. // Statics
  13785. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13786. AbstractMesh._BILLBOARDMODE_X = 1;
  13787. AbstractMesh._BILLBOARDMODE_Y = 2;
  13788. AbstractMesh._BILLBOARDMODE_Z = 4;
  13789. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13790. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13791. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13792. BABYLON.AbstractMesh = AbstractMesh;
  13793. })(BABYLON || (BABYLON = {}));
  13794. //# sourceMappingURL=babylon.abstractMesh.js.map
  13795. var BABYLON;
  13796. (function (BABYLON) {
  13797. var Light = (function (_super) {
  13798. __extends(Light, _super);
  13799. /**
  13800. * Creates a Light object in the scene.
  13801. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13802. */
  13803. function Light(name, scene) {
  13804. var _this = _super.call(this, name, scene) || this;
  13805. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13806. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13807. _this.intensity = 1.0;
  13808. _this.range = Number.MAX_VALUE;
  13809. _this.includeOnlyWithLayerMask = 0;
  13810. _this.includedOnlyMeshes = new Array();
  13811. _this.excludedMeshes = new Array();
  13812. _this.excludeWithLayerMask = 0;
  13813. _this.lightmapMode = 0;
  13814. // PBR Properties.
  13815. _this.radius = 0.00001;
  13816. _this._excludedMeshesIds = new Array();
  13817. _this._includedOnlyMeshesIds = new Array();
  13818. _this.getScene().addLight(_this);
  13819. return _this;
  13820. }
  13821. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13822. /**
  13823. * If every light affecting the material is in this lightmapMode,
  13824. * material.lightmapTexture adds or multiplies
  13825. * (depends on material.useLightmapAsShadowmap)
  13826. * after every other light calculations.
  13827. */
  13828. get: function () {
  13829. return Light._LIGHTMAP_DEFAULT;
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13835. /**
  13836. * material.lightmapTexture as only diffuse lighting from this light
  13837. * adds pnly specular lighting from this light
  13838. * adds dynamic shadows
  13839. */
  13840. get: function () {
  13841. return Light._LIGHTMAP_SPECULAR;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13847. /**
  13848. * material.lightmapTexture as only lighting
  13849. * no light calculation from this light
  13850. * only adds dynamic shadows from this light
  13851. */
  13852. get: function () {
  13853. return Light._LIGHTMAP_SHADOWSONLY;
  13854. },
  13855. enumerable: true,
  13856. configurable: true
  13857. });
  13858. /**
  13859. * Returns the string "Light".
  13860. */
  13861. Light.prototype.getClassName = function () {
  13862. return "Light";
  13863. };
  13864. /**
  13865. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13866. */
  13867. Light.prototype.toString = function (fullDetails) {
  13868. var ret = "Name: " + this.name;
  13869. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13870. if (this.animations) {
  13871. for (var i = 0; i < this.animations.length; i++) {
  13872. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13873. }
  13874. }
  13875. if (fullDetails) {
  13876. }
  13877. return ret;
  13878. };
  13879. /**
  13880. * Returns the Light associated shadow generator.
  13881. */
  13882. Light.prototype.getShadowGenerator = function () {
  13883. return this._shadowGenerator;
  13884. };
  13885. /**
  13886. * Returns a Vector3, the absolute light position in the World.
  13887. */
  13888. Light.prototype.getAbsolutePosition = function () {
  13889. return BABYLON.Vector3.Zero();
  13890. };
  13891. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13892. };
  13893. Light.prototype._getWorldMatrix = function () {
  13894. return BABYLON.Matrix.Identity();
  13895. };
  13896. /**
  13897. * Boolean : True if the light will affect the passed mesh.
  13898. */
  13899. Light.prototype.canAffectMesh = function (mesh) {
  13900. if (!mesh) {
  13901. return true;
  13902. }
  13903. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13904. return false;
  13905. }
  13906. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13907. return false;
  13908. }
  13909. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13910. return false;
  13911. }
  13912. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13913. return false;
  13914. }
  13915. return true;
  13916. };
  13917. /**
  13918. * Returns the light World matrix.
  13919. */
  13920. Light.prototype.getWorldMatrix = function () {
  13921. this._currentRenderId = this.getScene().getRenderId();
  13922. var worldMatrix = this._getWorldMatrix();
  13923. if (this.parent && this.parent.getWorldMatrix) {
  13924. if (!this._parentedWorldMatrix) {
  13925. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13926. }
  13927. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13928. this._markSyncedWithParent();
  13929. return this._parentedWorldMatrix;
  13930. }
  13931. return worldMatrix;
  13932. };
  13933. /**
  13934. * Disposes the light.
  13935. */
  13936. Light.prototype.dispose = function () {
  13937. if (this._shadowGenerator) {
  13938. this._shadowGenerator.dispose();
  13939. this._shadowGenerator = null;
  13940. }
  13941. // Animations
  13942. this.getScene().stopAnimation(this);
  13943. // Remove from scene
  13944. this.getScene().removeLight(this);
  13945. _super.prototype.dispose.call(this);
  13946. };
  13947. /**
  13948. * Returns the light type ID (integer).
  13949. */
  13950. Light.prototype.getTypeID = function () {
  13951. return 0;
  13952. };
  13953. /**
  13954. * Returns a new Light object, named "name", from the current one.
  13955. */
  13956. Light.prototype.clone = function (name) {
  13957. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13958. };
  13959. /**
  13960. * Serializes the current light into a Serialization object.
  13961. * Returns the serialized object.
  13962. */
  13963. Light.prototype.serialize = function () {
  13964. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13965. // Type
  13966. serializationObject.type = this.getTypeID();
  13967. // Parent
  13968. if (this.parent) {
  13969. serializationObject.parentId = this.parent.id;
  13970. }
  13971. // Inclusion / exclusions
  13972. if (this.excludedMeshes.length > 0) {
  13973. serializationObject.excludedMeshesIds = [];
  13974. this.excludedMeshes.forEach(function (mesh) {
  13975. serializationObject.excludedMeshesIds.push(mesh.id);
  13976. });
  13977. }
  13978. if (this.includedOnlyMeshes.length > 0) {
  13979. serializationObject.includedOnlyMeshesIds = [];
  13980. this.includedOnlyMeshes.forEach(function (mesh) {
  13981. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13982. });
  13983. }
  13984. // Animations
  13985. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13986. serializationObject.ranges = this.serializeAnimationRanges();
  13987. return serializationObject;
  13988. };
  13989. /**
  13990. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13991. * This new light is named "name" and added to the passed scene.
  13992. */
  13993. Light.GetConstructorFromName = function (type, name, scene) {
  13994. switch (type) {
  13995. case 0:
  13996. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13997. case 1:
  13998. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13999. case 2:
  14000. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14001. case 3:
  14002. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14003. }
  14004. };
  14005. /**
  14006. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14007. */
  14008. Light.Parse = function (parsedLight, scene) {
  14009. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14010. // Inclusion / exclusions
  14011. if (parsedLight.excludedMeshesIds) {
  14012. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14013. }
  14014. if (parsedLight.includedOnlyMeshesIds) {
  14015. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14016. }
  14017. // Parent
  14018. if (parsedLight.parentId) {
  14019. light._waitingParentId = parsedLight.parentId;
  14020. }
  14021. // Animations
  14022. if (parsedLight.animations) {
  14023. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14024. var parsedAnimation = parsedLight.animations[animationIndex];
  14025. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14026. }
  14027. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14028. }
  14029. if (parsedLight.autoAnimate) {
  14030. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14031. }
  14032. return light;
  14033. };
  14034. return Light;
  14035. }(BABYLON.Node));
  14036. //lightmapMode Consts
  14037. Light._LIGHTMAP_DEFAULT = 0;
  14038. Light._LIGHTMAP_SPECULAR = 1;
  14039. Light._LIGHTMAP_SHADOWSONLY = 2;
  14040. __decorate([
  14041. BABYLON.serializeAsColor3()
  14042. ], Light.prototype, "diffuse", void 0);
  14043. __decorate([
  14044. BABYLON.serializeAsColor3()
  14045. ], Light.prototype, "specular", void 0);
  14046. __decorate([
  14047. BABYLON.serialize()
  14048. ], Light.prototype, "intensity", void 0);
  14049. __decorate([
  14050. BABYLON.serialize()
  14051. ], Light.prototype, "range", void 0);
  14052. __decorate([
  14053. BABYLON.serialize()
  14054. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  14055. __decorate([
  14056. BABYLON.serialize()
  14057. ], Light.prototype, "excludeWithLayerMask", void 0);
  14058. __decorate([
  14059. BABYLON.serialize()
  14060. ], Light.prototype, "lightmapMode", void 0);
  14061. __decorate([
  14062. BABYLON.serialize()
  14063. ], Light.prototype, "radius", void 0);
  14064. BABYLON.Light = Light;
  14065. })(BABYLON || (BABYLON = {}));
  14066. //# sourceMappingURL=babylon.light.js.map
  14067. var BABYLON;
  14068. (function (BABYLON) {
  14069. var PointLight = (function (_super) {
  14070. __extends(PointLight, _super);
  14071. /**
  14072. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14073. * A PointLight emits the light in every direction.
  14074. * It can cast shadows.
  14075. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14076. * ```javascript
  14077. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14078. * ```
  14079. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14080. */
  14081. function PointLight(name, position, scene) {
  14082. var _this = _super.call(this, name, scene) || this;
  14083. _this.position = position;
  14084. return _this;
  14085. }
  14086. /**
  14087. * Returns the string "PointLight"
  14088. */
  14089. PointLight.prototype.getClassName = function () {
  14090. return "PointLight";
  14091. };
  14092. /**
  14093. * Returns a Vector3, the PointLight absolute position in the World.
  14094. */
  14095. PointLight.prototype.getAbsolutePosition = function () {
  14096. return this.transformedPosition ? this.transformedPosition : this.position;
  14097. };
  14098. /**
  14099. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14100. */
  14101. PointLight.prototype.computeTransformedPosition = function () {
  14102. if (this.parent && this.parent.getWorldMatrix) {
  14103. if (!this.transformedPosition) {
  14104. this.transformedPosition = BABYLON.Vector3.Zero();
  14105. }
  14106. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14107. return true;
  14108. }
  14109. return false;
  14110. };
  14111. /**
  14112. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14113. * Returns the PointLight.
  14114. */
  14115. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14116. if (this.parent && this.parent.getWorldMatrix) {
  14117. this.computeTransformedPosition();
  14118. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14119. return this;
  14120. }
  14121. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14122. return this;
  14123. };
  14124. /**
  14125. * Boolean : returns true by default.
  14126. */
  14127. PointLight.prototype.needCube = function () {
  14128. return true;
  14129. };
  14130. /**
  14131. * Boolean : returns false by default.
  14132. */
  14133. PointLight.prototype.needRefreshPerFrame = function () {
  14134. return false;
  14135. };
  14136. /**
  14137. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14138. */
  14139. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14140. switch (faceIndex) {
  14141. case 0:
  14142. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14143. case 1:
  14144. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14145. case 2:
  14146. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14147. case 3:
  14148. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14149. case 4:
  14150. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14151. case 5:
  14152. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14153. }
  14154. return BABYLON.Vector3.Zero();
  14155. };
  14156. /**
  14157. * Return the depth scale used for the shadow map.
  14158. */
  14159. PointLight.prototype.getDepthScale = function () {
  14160. return 30.0;
  14161. };
  14162. /**
  14163. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14164. * - fov = PI / 2
  14165. * - aspect ratio : 1.0
  14166. * - z-near and far equal to the active camera minZ and maxZ.
  14167. * Returns the PointLight.
  14168. */
  14169. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14170. if (this.customProjectionMatrixBuilder) {
  14171. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14172. }
  14173. else {
  14174. var activeCamera = this.getScene().activeCamera;
  14175. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14176. }
  14177. return this;
  14178. };
  14179. PointLight.prototype._getWorldMatrix = function () {
  14180. if (!this._worldMatrix) {
  14181. this._worldMatrix = BABYLON.Matrix.Identity();
  14182. }
  14183. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14184. return this._worldMatrix;
  14185. };
  14186. /**
  14187. * Returns the integer 0.
  14188. */
  14189. PointLight.prototype.getTypeID = function () {
  14190. return 0;
  14191. };
  14192. return PointLight;
  14193. }(BABYLON.Light));
  14194. __decorate([
  14195. BABYLON.serializeAsVector3()
  14196. ], PointLight.prototype, "position", void 0);
  14197. __decorate([
  14198. BABYLON.serialize()
  14199. ], PointLight.prototype, "shadowMinZ", void 0);
  14200. __decorate([
  14201. BABYLON.serialize()
  14202. ], PointLight.prototype, "shadowMaxZ", void 0);
  14203. BABYLON.PointLight = PointLight;
  14204. })(BABYLON || (BABYLON = {}));
  14205. //# sourceMappingURL=babylon.pointLight.js.map
  14206. var BABYLON;
  14207. (function (BABYLON) {
  14208. var SpotLight = (function (_super) {
  14209. __extends(SpotLight, _super);
  14210. /**
  14211. * Creates a SpotLight object in the scene with the passed parameters :
  14212. * - `position` (Vector3) is the initial SpotLight position,
  14213. * - `direction` (Vector3) is the initial SpotLight direction,
  14214. * - `angle` (float, in radians) is the spot light cone angle,
  14215. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14216. * A spot light is a simply light oriented cone.
  14217. * It can cast shadows.
  14218. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14219. */
  14220. function SpotLight(name, position, direction, angle, exponent, scene) {
  14221. var _this = _super.call(this, name, scene) || this;
  14222. _this.position = position;
  14223. _this.direction = direction;
  14224. _this.angle = angle;
  14225. _this.exponent = exponent;
  14226. return _this;
  14227. }
  14228. /**
  14229. * Returns the string "SpotLight".
  14230. */
  14231. SpotLight.prototype.getClassName = function () {
  14232. return "SpotLight";
  14233. };
  14234. /**
  14235. * Returns the SpotLight absolute position in the World (Vector3).
  14236. */
  14237. SpotLight.prototype.getAbsolutePosition = function () {
  14238. return this.transformedPosition ? this.transformedPosition : this.position;
  14239. };
  14240. /**
  14241. * Return the depth scale used for the shadow map.
  14242. */
  14243. SpotLight.prototype.getDepthScale = function () {
  14244. return 30.0;
  14245. };
  14246. /**
  14247. * 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.
  14248. * Returns the SpotLight.
  14249. */
  14250. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14251. if (this.customProjectionMatrixBuilder) {
  14252. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14253. }
  14254. else {
  14255. var activeCamera = this.getScene().activeCamera;
  14256. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14257. }
  14258. return this;
  14259. };
  14260. /**
  14261. * Boolean : false by default.
  14262. */
  14263. SpotLight.prototype.needCube = function () {
  14264. return false;
  14265. };
  14266. /**
  14267. * Boolean : false by default.
  14268. */
  14269. SpotLight.prototype.needRefreshPerFrame = function () {
  14270. return false;
  14271. };
  14272. /**
  14273. * Returns the SpotLight direction (Vector3) for any passed face index.
  14274. */
  14275. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14276. return this.direction;
  14277. };
  14278. /**
  14279. * Updates the SpotLight direction towards the passed target (Vector3).
  14280. * Returns the updated direction.
  14281. */
  14282. SpotLight.prototype.setDirectionToTarget = function (target) {
  14283. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14284. return this.direction;
  14285. };
  14286. /**
  14287. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14288. */
  14289. SpotLight.prototype.computeTransformedPosition = function () {
  14290. if (this.parent && this.parent.getWorldMatrix) {
  14291. if (!this.transformedPosition) {
  14292. this.transformedPosition = BABYLON.Vector3.Zero();
  14293. }
  14294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14295. return true;
  14296. }
  14297. return false;
  14298. };
  14299. /**
  14300. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14301. * Return the SpotLight.
  14302. */
  14303. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14304. var normalizeDirection;
  14305. if (this.parent && this.parent.getWorldMatrix) {
  14306. if (!this._transformedDirection) {
  14307. this._transformedDirection = BABYLON.Vector3.Zero();
  14308. }
  14309. this.computeTransformedPosition();
  14310. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14311. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14312. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14313. }
  14314. else {
  14315. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14316. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14317. }
  14318. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14319. return this;
  14320. };
  14321. SpotLight.prototype._getWorldMatrix = function () {
  14322. if (!this._worldMatrix) {
  14323. this._worldMatrix = BABYLON.Matrix.Identity();
  14324. }
  14325. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14326. return this._worldMatrix;
  14327. };
  14328. /**
  14329. * Returns the integer 2.
  14330. */
  14331. SpotLight.prototype.getTypeID = function () {
  14332. return 2;
  14333. };
  14334. /**
  14335. * Returns the SpotLight rotation (Vector3).
  14336. */
  14337. SpotLight.prototype.getRotation = function () {
  14338. this.direction.normalize();
  14339. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14340. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14341. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14342. };
  14343. return SpotLight;
  14344. }(BABYLON.Light));
  14345. __decorate([
  14346. BABYLON.serializeAsVector3()
  14347. ], SpotLight.prototype, "position", void 0);
  14348. __decorate([
  14349. BABYLON.serializeAsVector3()
  14350. ], SpotLight.prototype, "direction", void 0);
  14351. __decorate([
  14352. BABYLON.serialize()
  14353. ], SpotLight.prototype, "angle", void 0);
  14354. __decorate([
  14355. BABYLON.serialize()
  14356. ], SpotLight.prototype, "exponent", void 0);
  14357. __decorate([
  14358. BABYLON.serialize()
  14359. ], SpotLight.prototype, "shadowMinZ", void 0);
  14360. __decorate([
  14361. BABYLON.serialize()
  14362. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14363. BABYLON.SpotLight = SpotLight;
  14364. })(BABYLON || (BABYLON = {}));
  14365. //# sourceMappingURL=babylon.spotLight.js.map
  14366. var BABYLON;
  14367. (function (BABYLON) {
  14368. var HemisphericLight = (function (_super) {
  14369. __extends(HemisphericLight, _super);
  14370. /**
  14371. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14372. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14373. * The HemisphericLight can't cast shadows.
  14374. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14375. */
  14376. function HemisphericLight(name, direction, scene) {
  14377. var _this = _super.call(this, name, scene) || this;
  14378. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14379. _this.direction = direction;
  14380. return _this;
  14381. }
  14382. /**
  14383. * Returns the string "HemisphericLight".
  14384. */
  14385. HemisphericLight.prototype.getClassName = function () {
  14386. return "HemisphericLight";
  14387. };
  14388. /**
  14389. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14390. * Returns the updated direction.
  14391. */
  14392. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14393. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14394. return this.direction;
  14395. };
  14396. HemisphericLight.prototype.getShadowGenerator = function () {
  14397. return null;
  14398. };
  14399. /**
  14400. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14401. * Returns the HemisphericLight.
  14402. */
  14403. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14404. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14405. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14406. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14407. return this;
  14408. };
  14409. HemisphericLight.prototype._getWorldMatrix = function () {
  14410. if (!this._worldMatrix) {
  14411. this._worldMatrix = BABYLON.Matrix.Identity();
  14412. }
  14413. return this._worldMatrix;
  14414. };
  14415. /**
  14416. * Returns the integer 3.
  14417. */
  14418. HemisphericLight.prototype.getTypeID = function () {
  14419. return 3;
  14420. };
  14421. return HemisphericLight;
  14422. }(BABYLON.Light));
  14423. __decorate([
  14424. BABYLON.serializeAsColor3()
  14425. ], HemisphericLight.prototype, "groundColor", void 0);
  14426. __decorate([
  14427. BABYLON.serializeAsVector3()
  14428. ], HemisphericLight.prototype, "direction", void 0);
  14429. BABYLON.HemisphericLight = HemisphericLight;
  14430. })(BABYLON || (BABYLON = {}));
  14431. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14432. /// <reference path="babylon.light.ts" />
  14433. var BABYLON;
  14434. (function (BABYLON) {
  14435. var DirectionalLight = (function (_super) {
  14436. __extends(DirectionalLight, _super);
  14437. /**
  14438. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14439. * The directional light is emitted from everywhere in the given direction.
  14440. * It can cast shawdows.
  14441. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14442. */
  14443. function DirectionalLight(name, direction, scene) {
  14444. var _this = _super.call(this, name, scene) || this;
  14445. _this.shadowOrthoScale = 0.5;
  14446. _this.autoUpdateExtends = true;
  14447. // Cache
  14448. _this._orthoLeft = Number.MAX_VALUE;
  14449. _this._orthoRight = Number.MIN_VALUE;
  14450. _this._orthoTop = Number.MIN_VALUE;
  14451. _this._orthoBottom = Number.MAX_VALUE;
  14452. _this.position = direction.scale(-1.0);
  14453. _this.direction = direction;
  14454. return _this;
  14455. }
  14456. /**
  14457. * Returns the string "DirectionalLight".
  14458. */
  14459. DirectionalLight.prototype.getClassName = function () {
  14460. return "DirectionalLight";
  14461. };
  14462. /**
  14463. * Returns the DirectionalLight absolute position in the World.
  14464. */
  14465. DirectionalLight.prototype.getAbsolutePosition = function () {
  14466. return this.transformedPosition ? this.transformedPosition : this.position;
  14467. };
  14468. /**
  14469. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14470. * Returns the updated DirectionalLight direction (Vector3).
  14471. */
  14472. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14473. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14474. return this.direction;
  14475. };
  14476. /**
  14477. * Return the depth scale used for the shadow map.
  14478. */
  14479. DirectionalLight.prototype.getDepthScale = function () {
  14480. return 30.0;
  14481. };
  14482. /**
  14483. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14484. * Returns the DirectionalLight.
  14485. */
  14486. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14487. if (this.customProjectionMatrixBuilder) {
  14488. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14489. }
  14490. else {
  14491. var activeCamera = this.getScene().activeCamera;
  14492. // Check extends
  14493. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14494. var tempVector3 = BABYLON.Vector3.Zero();
  14495. this._orthoLeft = Number.MAX_VALUE;
  14496. this._orthoRight = Number.MIN_VALUE;
  14497. this._orthoTop = Number.MIN_VALUE;
  14498. this._orthoBottom = Number.MAX_VALUE;
  14499. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14500. var mesh = renderList[meshIndex];
  14501. if (!mesh) {
  14502. continue;
  14503. }
  14504. var boundingInfo = mesh.getBoundingInfo();
  14505. if (!boundingInfo) {
  14506. continue;
  14507. }
  14508. var boundingBox = boundingInfo.boundingBox;
  14509. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14510. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14511. if (tempVector3.x < this._orthoLeft)
  14512. this._orthoLeft = tempVector3.x;
  14513. if (tempVector3.y < this._orthoBottom)
  14514. this._orthoBottom = tempVector3.y;
  14515. if (tempVector3.x > this._orthoRight)
  14516. this._orthoRight = tempVector3.x;
  14517. if (tempVector3.y > this._orthoTop)
  14518. this._orthoTop = tempVector3.y;
  14519. }
  14520. }
  14521. }
  14522. var xOffset = this._orthoRight - this._orthoLeft;
  14523. var yOffset = this._orthoTop - this._orthoBottom;
  14524. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14525. }
  14526. return this;
  14527. };
  14528. /**
  14529. * Boolean : true by default.
  14530. */
  14531. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14532. return true;
  14533. };
  14534. /**
  14535. * Boolean : false by default.
  14536. */
  14537. DirectionalLight.prototype.needCube = function () {
  14538. return false;
  14539. };
  14540. /**
  14541. * Returns the light direction (Vector3) for any passed face index.
  14542. */
  14543. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14544. return this.direction;
  14545. };
  14546. /**
  14547. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14548. */
  14549. DirectionalLight.prototype.computeTransformedPosition = function () {
  14550. if (this.parent && this.parent.getWorldMatrix) {
  14551. if (!this.transformedPosition) {
  14552. this.transformedPosition = BABYLON.Vector3.Zero();
  14553. }
  14554. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14555. return true;
  14556. }
  14557. return false;
  14558. };
  14559. /**
  14560. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14561. * Returns the DirectionalLight.
  14562. */
  14563. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14564. if (this.parent && this.parent.getWorldMatrix) {
  14565. if (!this._transformedDirection) {
  14566. this._transformedDirection = BABYLON.Vector3.Zero();
  14567. }
  14568. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14569. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14570. return this;
  14571. }
  14572. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14573. return this;
  14574. };
  14575. DirectionalLight.prototype._getWorldMatrix = function () {
  14576. if (!this._worldMatrix) {
  14577. this._worldMatrix = BABYLON.Matrix.Identity();
  14578. }
  14579. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14580. return this._worldMatrix;
  14581. };
  14582. /**
  14583. * Returns the integer 1.
  14584. */
  14585. DirectionalLight.prototype.getTypeID = function () {
  14586. return 1;
  14587. };
  14588. return DirectionalLight;
  14589. }(BABYLON.Light));
  14590. __decorate([
  14591. BABYLON.serializeAsVector3()
  14592. ], DirectionalLight.prototype, "position", void 0);
  14593. __decorate([
  14594. BABYLON.serializeAsVector3()
  14595. ], DirectionalLight.prototype, "direction", void 0);
  14596. __decorate([
  14597. BABYLON.serialize()
  14598. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14599. __decorate([
  14600. BABYLON.serialize()
  14601. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14602. __decorate([
  14603. BABYLON.serialize()
  14604. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  14605. __decorate([
  14606. BABYLON.serialize()
  14607. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  14608. BABYLON.DirectionalLight = DirectionalLight;
  14609. })(BABYLON || (BABYLON = {}));
  14610. //# sourceMappingURL=babylon.directionalLight.js.map
  14611. var BABYLON;
  14612. (function (BABYLON) {
  14613. var ShadowGenerator = (function () {
  14614. /**
  14615. * Creates a ShadowGenerator object.
  14616. * A ShadowGenerator is the required tool to use the shadows.
  14617. * Each light casting shadows needs to use its own ShadowGenerator.
  14618. * Required parameters :
  14619. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14620. * - `light` : the light object generating the shadows.
  14621. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14622. */
  14623. function ShadowGenerator(mapSize, light) {
  14624. var _this = this;
  14625. // Members
  14626. this._filter = ShadowGenerator.FILTER_NONE;
  14627. this.blurScale = 2;
  14628. this._blurBoxOffset = 0;
  14629. this._bias = 0.00005;
  14630. this._lightDirection = BABYLON.Vector3.Zero();
  14631. this.forceBackFacesOnly = false;
  14632. this._darkness = 0;
  14633. this._transparencyShadow = false;
  14634. this._viewMatrix = BABYLON.Matrix.Zero();
  14635. this._projectionMatrix = BABYLON.Matrix.Zero();
  14636. this._transformMatrix = BABYLON.Matrix.Zero();
  14637. this._worldViewProjection = BABYLON.Matrix.Zero();
  14638. this._currentFaceIndex = 0;
  14639. this._currentFaceIndexCache = 0;
  14640. this._useFullFloat = true;
  14641. this._light = light;
  14642. this._scene = light.getScene();
  14643. this._mapSize = mapSize;
  14644. light._shadowGenerator = this;
  14645. // Texture type fallback from float to int if not supported.
  14646. var textureType;
  14647. var caps = this._scene.getEngine().getCaps();
  14648. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14649. this._useFullFloat = true;
  14650. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14651. }
  14652. else {
  14653. this._useFullFloat = false;
  14654. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14655. }
  14656. // Render target
  14657. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14658. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14659. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14660. this._shadowMap.anisotropicFilteringLevel = 1;
  14661. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14662. this._shadowMap.renderParticles = false;
  14663. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14664. _this._currentFaceIndex = faceIndex;
  14665. });
  14666. this._shadowMap.onAfterUnbindObservable.add(function () {
  14667. if (!_this.useBlurExponentialShadowMap) {
  14668. return;
  14669. }
  14670. if (!_this._shadowMap2) {
  14671. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14672. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14673. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14674. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14675. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  14676. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14677. effect.setTexture("textureSampler", _this._shadowMap);
  14678. });
  14679. _this.blurBoxOffset = 1;
  14680. }
  14681. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14682. });
  14683. // Custom render function
  14684. var renderSubMesh = function (subMesh) {
  14685. var mesh = subMesh.getRenderingMesh();
  14686. var scene = _this._scene;
  14687. var engine = scene.getEngine();
  14688. // Culling
  14689. engine.setState(subMesh.getMaterial().backFaceCulling);
  14690. // Managing instances
  14691. var batch = mesh._getInstancesRenderList(subMesh._id);
  14692. if (batch.mustReturn) {
  14693. return;
  14694. }
  14695. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14696. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14697. engine.enableEffect(_this._effect);
  14698. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14699. var material = subMesh.getMaterial();
  14700. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  14701. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14702. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14703. if (_this.getLight().needCube()) {
  14704. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14705. }
  14706. // Alpha test
  14707. if (material && material.needAlphaTesting()) {
  14708. var alphaTexture = material.getAlphaTestTexture();
  14709. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14710. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14711. }
  14712. // Bones
  14713. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14714. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14715. }
  14716. if (_this.forceBackFacesOnly) {
  14717. engine.setState(true, 0, false, true);
  14718. }
  14719. // Draw
  14720. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14721. if (_this.forceBackFacesOnly) {
  14722. engine.setState(true, 0, false, false);
  14723. }
  14724. }
  14725. else {
  14726. // Need to reset refresh rate of the shadowMap
  14727. _this._shadowMap.resetRefreshCounter();
  14728. }
  14729. };
  14730. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14731. var index;
  14732. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14733. renderSubMesh(opaqueSubMeshes.data[index]);
  14734. }
  14735. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14736. renderSubMesh(alphaTestSubMeshes.data[index]);
  14737. }
  14738. if (_this._transparencyShadow) {
  14739. for (index = 0; index < transparentSubMeshes.length; index++) {
  14740. renderSubMesh(transparentSubMeshes.data[index]);
  14741. }
  14742. }
  14743. };
  14744. this._shadowMap.onClearObservable.add(function (engine) {
  14745. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  14746. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14747. }
  14748. else {
  14749. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14750. }
  14751. });
  14752. }
  14753. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14754. // Static
  14755. get: function () {
  14756. return ShadowGenerator._FILTER_NONE;
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14762. get: function () {
  14763. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  14769. get: function () {
  14770. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  14776. get: function () {
  14777. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14783. get: function () {
  14784. return this._bias;
  14785. },
  14786. set: function (bias) {
  14787. this._bias = bias;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14793. get: function () {
  14794. return this._blurBoxOffset;
  14795. },
  14796. set: function (value) {
  14797. var _this = this;
  14798. if (this._blurBoxOffset === value) {
  14799. return;
  14800. }
  14801. this._blurBoxOffset = value;
  14802. if (this._boxBlurPostprocess) {
  14803. this._boxBlurPostprocess.dispose();
  14804. }
  14805. var textureType;
  14806. var caps = this._scene.getEngine().getCaps();
  14807. if (this._useFullFloat) {
  14808. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14809. }
  14810. else {
  14811. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14812. }
  14813. 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, textureType);
  14814. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14815. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14816. });
  14817. },
  14818. enumerable: true,
  14819. configurable: true
  14820. });
  14821. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  14822. get: function () {
  14823. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  14824. },
  14825. set: function (value) {
  14826. this._depthScale = value;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14832. get: function () {
  14833. return this._filter;
  14834. },
  14835. set: function (value) {
  14836. if (this._filter === value) {
  14837. return;
  14838. }
  14839. this._filter = value;
  14840. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14841. this._shadowMap.anisotropicFilteringLevel = 16;
  14842. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14843. }
  14844. else {
  14845. this._shadowMap.anisotropicFilteringLevel = 1;
  14846. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14847. }
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14853. get: function () {
  14854. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14855. return this.useExponentialShadowMap;
  14856. },
  14857. set: function (value) {
  14858. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14859. this.useExponentialShadowMap = value;
  14860. },
  14861. enumerable: true,
  14862. configurable: true
  14863. });
  14864. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  14865. get: function () {
  14866. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  14867. },
  14868. set: function (value) {
  14869. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14875. get: function () {
  14876. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  14877. },
  14878. set: function (value) {
  14879. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14880. },
  14881. enumerable: true,
  14882. configurable: true
  14883. });
  14884. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14885. get: function () {
  14886. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14887. return this.useBlurExponentialShadowMap;
  14888. },
  14889. set: function (value) {
  14890. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14891. this.useBlurExponentialShadowMap = value;
  14892. },
  14893. enumerable: true,
  14894. configurable: true
  14895. });
  14896. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  14897. get: function () {
  14898. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  14899. },
  14900. set: function (value) {
  14901. if (this._light.needCube() && value) {
  14902. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  14903. }
  14904. else {
  14905. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14906. }
  14907. },
  14908. enumerable: true,
  14909. configurable: true
  14910. });
  14911. /**
  14912. * Boolean : true when the ShadowGenerator is finally computed.
  14913. */
  14914. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14915. var defines = [];
  14916. if (this._useFullFloat) {
  14917. defines.push("#define FULLFLOAT");
  14918. }
  14919. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14920. defines.push("#define ESM");
  14921. }
  14922. if (this.getLight().needCube()) {
  14923. defines.push("#define CUBEMAP");
  14924. }
  14925. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14926. var mesh = subMesh.getMesh();
  14927. var material = subMesh.getMaterial();
  14928. // Alpha test
  14929. if (material && material.needAlphaTesting()) {
  14930. defines.push("#define ALPHATEST");
  14931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14932. attribs.push(BABYLON.VertexBuffer.UVKind);
  14933. defines.push("#define UV1");
  14934. }
  14935. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14936. var alphaTexture = material.getAlphaTestTexture();
  14937. if (alphaTexture.coordinatesIndex === 1) {
  14938. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14939. defines.push("#define UV2");
  14940. }
  14941. }
  14942. }
  14943. // Bones
  14944. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14947. if (mesh.numBoneInfluencers > 4) {
  14948. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14949. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14950. }
  14951. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14952. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14953. }
  14954. else {
  14955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14956. }
  14957. // Instances
  14958. if (useInstances) {
  14959. defines.push("#define INSTANCES");
  14960. attribs.push("world0");
  14961. attribs.push("world1");
  14962. attribs.push("world2");
  14963. attribs.push("world3");
  14964. }
  14965. // Get correct effect
  14966. var join = defines.join("\n");
  14967. if (this._cachedDefines !== join) {
  14968. this._cachedDefines = join;
  14969. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  14970. }
  14971. return this._effect.isReady();
  14972. };
  14973. /**
  14974. * Returns a RenderTargetTexture object : the shadow map texture.
  14975. */
  14976. ShadowGenerator.prototype.getShadowMap = function () {
  14977. return this._shadowMap;
  14978. };
  14979. /**
  14980. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14981. */
  14982. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14983. if (this._shadowMap2) {
  14984. return this._shadowMap2;
  14985. }
  14986. return this._shadowMap;
  14987. };
  14988. /**
  14989. * Returns the associated light object.
  14990. */
  14991. ShadowGenerator.prototype.getLight = function () {
  14992. return this._light;
  14993. };
  14994. // Methods
  14995. /**
  14996. * Returns a Matrix object : the updated transformation matrix.
  14997. */
  14998. ShadowGenerator.prototype.getTransformMatrix = function () {
  14999. var scene = this._scene;
  15000. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  15001. return this._transformMatrix;
  15002. }
  15003. this._currentRenderID = scene.getRenderId();
  15004. this._currentFaceIndexCache = this._currentFaceIndex;
  15005. var lightPosition = this._light.position;
  15006. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  15007. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  15008. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  15009. }
  15010. if (this._light.computeTransformedPosition()) {
  15011. lightPosition = this._light.transformedPosition;
  15012. }
  15013. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  15014. this._cachedPosition = lightPosition.clone();
  15015. this._cachedDirection = this._lightDirection.clone();
  15016. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  15017. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  15018. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15019. }
  15020. return this._transformMatrix;
  15021. };
  15022. /**
  15023. * Returns the darkness value (float).
  15024. */
  15025. ShadowGenerator.prototype.getDarkness = function () {
  15026. return this._darkness;
  15027. };
  15028. /**
  15029. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15030. * Returns the ShadowGenerator.
  15031. */
  15032. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15033. if (darkness >= 1.0)
  15034. this._darkness = 1.0;
  15035. else if (darkness <= 0.0)
  15036. this._darkness = 0.0;
  15037. else
  15038. this._darkness = darkness;
  15039. return this;
  15040. };
  15041. /**
  15042. * Sets the ability to have transparent shadow (boolean).
  15043. * Returns the ShadowGenerator.
  15044. */
  15045. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15046. this._transparencyShadow = hasShadow;
  15047. return this;
  15048. };
  15049. ShadowGenerator.prototype._packHalf = function (depth) {
  15050. var scale = depth * 255.0;
  15051. var fract = scale - Math.floor(scale);
  15052. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15053. };
  15054. /**
  15055. * Disposes the ShadowGenerator.
  15056. * Returns nothing.
  15057. */
  15058. ShadowGenerator.prototype.dispose = function () {
  15059. this._shadowMap.dispose();
  15060. if (this._shadowMap2) {
  15061. this._shadowMap2.dispose();
  15062. }
  15063. if (this._downSamplePostprocess) {
  15064. this._downSamplePostprocess.dispose();
  15065. }
  15066. if (this._boxBlurPostprocess) {
  15067. this._boxBlurPostprocess.dispose();
  15068. }
  15069. this._light._shadowGenerator = null;
  15070. };
  15071. /**
  15072. * Serializes the ShadowGenerator and returns a serializationObject.
  15073. */
  15074. ShadowGenerator.prototype.serialize = function () {
  15075. var serializationObject = {};
  15076. serializationObject.lightId = this._light.id;
  15077. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15078. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15079. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15080. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15081. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15082. serializationObject.depthScale = this.depthScale;
  15083. serializationObject.darkness = this.getDarkness();
  15084. serializationObject.renderList = [];
  15085. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15086. var mesh = this.getShadowMap().renderList[meshIndex];
  15087. serializationObject.renderList.push(mesh.id);
  15088. }
  15089. return serializationObject;
  15090. };
  15091. /**
  15092. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15093. */
  15094. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15095. //casting to point light, as light is missing the position attr and typescript complains.
  15096. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15097. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15098. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15099. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15100. meshes.forEach(function (mesh) {
  15101. shadowGenerator.getShadowMap().renderList.push(mesh);
  15102. });
  15103. }
  15104. if (parsedShadowGenerator.usePoissonSampling) {
  15105. shadowGenerator.usePoissonSampling = true;
  15106. }
  15107. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15108. shadowGenerator.useExponentialShadowMap = true;
  15109. }
  15110. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15111. shadowGenerator.useBlurExponentialShadowMap = true;
  15112. }
  15113. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15114. shadowGenerator.useExponentialShadowMap = true;
  15115. }
  15116. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15117. shadowGenerator.useBlurExponentialShadowMap = true;
  15118. }
  15119. if (parsedShadowGenerator.depthScale) {
  15120. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  15121. }
  15122. if (parsedShadowGenerator.blurScale) {
  15123. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15124. }
  15125. if (parsedShadowGenerator.blurBoxOffset) {
  15126. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15127. }
  15128. if (parsedShadowGenerator.bias !== undefined) {
  15129. shadowGenerator.bias = parsedShadowGenerator.bias;
  15130. }
  15131. if (parsedShadowGenerator.darkness) {
  15132. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15133. }
  15134. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15135. return shadowGenerator;
  15136. };
  15137. return ShadowGenerator;
  15138. }());
  15139. ShadowGenerator._FILTER_NONE = 0;
  15140. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15141. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15142. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15143. BABYLON.ShadowGenerator = ShadowGenerator;
  15144. })(BABYLON || (BABYLON = {}));
  15145. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15146. var BABYLON;
  15147. (function (BABYLON) {
  15148. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15149. if (boxMin.x > sphereCenter.x + sphereRadius)
  15150. return false;
  15151. if (sphereCenter.x - sphereRadius > boxMax.x)
  15152. return false;
  15153. if (boxMin.y > sphereCenter.y + sphereRadius)
  15154. return false;
  15155. if (sphereCenter.y - sphereRadius > boxMax.y)
  15156. return false;
  15157. if (boxMin.z > sphereCenter.z + sphereRadius)
  15158. return false;
  15159. if (sphereCenter.z - sphereRadius > boxMax.z)
  15160. return false;
  15161. return true;
  15162. };
  15163. var getLowestRoot = (function () {
  15164. var result = { root: 0, found: false };
  15165. return function (a, b, c, maxR) {
  15166. result.root = 0;
  15167. result.found = false;
  15168. var determinant = b * b - 4.0 * a * c;
  15169. if (determinant < 0)
  15170. return result;
  15171. var sqrtD = Math.sqrt(determinant);
  15172. var r1 = (-b - sqrtD) / (2.0 * a);
  15173. var r2 = (-b + sqrtD) / (2.0 * a);
  15174. if (r1 > r2) {
  15175. var temp = r2;
  15176. r2 = r1;
  15177. r1 = temp;
  15178. }
  15179. if (r1 > 0 && r1 < maxR) {
  15180. result.root = r1;
  15181. result.found = true;
  15182. return result;
  15183. }
  15184. if (r2 > 0 && r2 < maxR) {
  15185. result.root = r2;
  15186. result.found = true;
  15187. return result;
  15188. }
  15189. return result;
  15190. };
  15191. })();
  15192. var Collider = (function () {
  15193. function Collider() {
  15194. this.radius = new BABYLON.Vector3(1, 1, 1);
  15195. this.retry = 0;
  15196. this.basePointWorld = BABYLON.Vector3.Zero();
  15197. this.velocityWorld = BABYLON.Vector3.Zero();
  15198. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15199. this._collisionPoint = BABYLON.Vector3.Zero();
  15200. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15201. this._tempVector = BABYLON.Vector3.Zero();
  15202. this._tempVector2 = BABYLON.Vector3.Zero();
  15203. this._tempVector3 = BABYLON.Vector3.Zero();
  15204. this._tempVector4 = BABYLON.Vector3.Zero();
  15205. this._edge = BABYLON.Vector3.Zero();
  15206. this._baseToVertex = BABYLON.Vector3.Zero();
  15207. this._destinationPoint = BABYLON.Vector3.Zero();
  15208. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15209. this._displacementVector = BABYLON.Vector3.Zero();
  15210. this._collisionMask = -1;
  15211. }
  15212. Object.defineProperty(Collider.prototype, "collisionMask", {
  15213. get: function () {
  15214. return this._collisionMask;
  15215. },
  15216. set: function (mask) {
  15217. this._collisionMask = !isNaN(mask) ? mask : -1;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. // Methods
  15223. Collider.prototype._initialize = function (source, dir, e) {
  15224. this.velocity = dir;
  15225. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15226. this.basePoint = source;
  15227. source.multiplyToRef(this.radius, this.basePointWorld);
  15228. dir.multiplyToRef(this.radius, this.velocityWorld);
  15229. this.velocityWorldLength = this.velocityWorld.length();
  15230. this.epsilon = e;
  15231. this.collisionFound = false;
  15232. };
  15233. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15234. pa.subtractToRef(point, this._tempVector);
  15235. pb.subtractToRef(point, this._tempVector2);
  15236. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15237. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15238. if (d < 0)
  15239. return false;
  15240. pc.subtractToRef(point, this._tempVector3);
  15241. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15242. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15243. if (d < 0)
  15244. return false;
  15245. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15246. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15247. return d >= 0;
  15248. };
  15249. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15250. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15251. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15252. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15253. return false;
  15254. }
  15255. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15256. return false;
  15257. return true;
  15258. };
  15259. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15260. var t0;
  15261. var embeddedInPlane = false;
  15262. //defensive programming, actually not needed.
  15263. if (!trianglePlaneArray) {
  15264. trianglePlaneArray = [];
  15265. }
  15266. if (!trianglePlaneArray[faceIndex]) {
  15267. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15268. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15269. }
  15270. var trianglePlane = trianglePlaneArray[faceIndex];
  15271. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15272. return;
  15273. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15274. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15275. if (normalDotVelocity == 0) {
  15276. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15277. return;
  15278. embeddedInPlane = true;
  15279. t0 = 0;
  15280. }
  15281. else {
  15282. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15283. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15284. if (t0 > t1) {
  15285. var temp = t1;
  15286. t1 = t0;
  15287. t0 = temp;
  15288. }
  15289. if (t0 > 1.0 || t1 < 0.0)
  15290. return;
  15291. if (t0 < 0)
  15292. t0 = 0;
  15293. if (t0 > 1.0)
  15294. t0 = 1.0;
  15295. }
  15296. this._collisionPoint.copyFromFloats(0, 0, 0);
  15297. var found = false;
  15298. var t = 1.0;
  15299. if (!embeddedInPlane) {
  15300. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15301. this.velocity.scaleToRef(t0, this._tempVector);
  15302. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15303. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15304. found = true;
  15305. t = t0;
  15306. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15307. }
  15308. }
  15309. if (!found) {
  15310. var velocitySquaredLength = this.velocity.lengthSquared();
  15311. var a = velocitySquaredLength;
  15312. this.basePoint.subtractToRef(p1, this._tempVector);
  15313. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15314. var c = this._tempVector.lengthSquared() - 1.0;
  15315. var lowestRoot = getLowestRoot(a, b, c, t);
  15316. if (lowestRoot.found) {
  15317. t = lowestRoot.root;
  15318. found = true;
  15319. this._collisionPoint.copyFrom(p1);
  15320. }
  15321. this.basePoint.subtractToRef(p2, this._tempVector);
  15322. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15323. c = this._tempVector.lengthSquared() - 1.0;
  15324. lowestRoot = getLowestRoot(a, b, c, t);
  15325. if (lowestRoot.found) {
  15326. t = lowestRoot.root;
  15327. found = true;
  15328. this._collisionPoint.copyFrom(p2);
  15329. }
  15330. this.basePoint.subtractToRef(p3, this._tempVector);
  15331. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15332. c = this._tempVector.lengthSquared() - 1.0;
  15333. lowestRoot = getLowestRoot(a, b, c, t);
  15334. if (lowestRoot.found) {
  15335. t = lowestRoot.root;
  15336. found = true;
  15337. this._collisionPoint.copyFrom(p3);
  15338. }
  15339. p2.subtractToRef(p1, this._edge);
  15340. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15341. var edgeSquaredLength = this._edge.lengthSquared();
  15342. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15343. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15344. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15345. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15346. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15347. lowestRoot = getLowestRoot(a, b, c, t);
  15348. if (lowestRoot.found) {
  15349. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15350. if (f >= 0.0 && f <= 1.0) {
  15351. t = lowestRoot.root;
  15352. found = true;
  15353. this._edge.scaleInPlace(f);
  15354. p1.addToRef(this._edge, this._collisionPoint);
  15355. }
  15356. }
  15357. p3.subtractToRef(p2, this._edge);
  15358. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15359. edgeSquaredLength = this._edge.lengthSquared();
  15360. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15361. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15362. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15363. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15364. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15365. lowestRoot = getLowestRoot(a, b, c, t);
  15366. if (lowestRoot.found) {
  15367. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15368. if (f >= 0.0 && f <= 1.0) {
  15369. t = lowestRoot.root;
  15370. found = true;
  15371. this._edge.scaleInPlace(f);
  15372. p2.addToRef(this._edge, this._collisionPoint);
  15373. }
  15374. }
  15375. p1.subtractToRef(p3, this._edge);
  15376. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15377. edgeSquaredLength = this._edge.lengthSquared();
  15378. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15379. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15380. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15381. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15382. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15383. lowestRoot = getLowestRoot(a, b, c, t);
  15384. if (lowestRoot.found) {
  15385. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15386. if (f >= 0.0 && f <= 1.0) {
  15387. t = lowestRoot.root;
  15388. found = true;
  15389. this._edge.scaleInPlace(f);
  15390. p3.addToRef(this._edge, this._collisionPoint);
  15391. }
  15392. }
  15393. }
  15394. if (found) {
  15395. var distToCollision = t * this.velocity.length();
  15396. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15397. if (!this.intersectionPoint) {
  15398. this.intersectionPoint = this._collisionPoint.clone();
  15399. }
  15400. else {
  15401. this.intersectionPoint.copyFrom(this._collisionPoint);
  15402. }
  15403. this.nearestDistance = distToCollision;
  15404. this.collisionFound = true;
  15405. }
  15406. }
  15407. };
  15408. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15409. for (var i = indexStart; i < indexEnd; i += 3) {
  15410. var p1 = pts[indices[i] - decal];
  15411. var p2 = pts[indices[i + 1] - decal];
  15412. var p3 = pts[indices[i + 2] - decal];
  15413. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15414. }
  15415. };
  15416. Collider.prototype._getResponse = function (pos, vel) {
  15417. pos.addToRef(vel, this._destinationPoint);
  15418. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15419. this.basePoint.addToRef(vel, pos);
  15420. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15421. this._slidePlaneNormal.normalize();
  15422. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15423. pos.addInPlace(this._displacementVector);
  15424. this.intersectionPoint.addInPlace(this._displacementVector);
  15425. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15426. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15427. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15428. };
  15429. return Collider;
  15430. }());
  15431. BABYLON.Collider = Collider;
  15432. })(BABYLON || (BABYLON = {}));
  15433. //# sourceMappingURL=babylon.collider.js.map
  15434. var BABYLON;
  15435. (function (BABYLON) {
  15436. //WebWorker code will be inserted to this variable.
  15437. BABYLON.CollisionWorker = "";
  15438. var WorkerTaskType;
  15439. (function (WorkerTaskType) {
  15440. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15441. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15442. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15443. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15444. var WorkerReplyType;
  15445. (function (WorkerReplyType) {
  15446. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15447. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15448. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15449. var CollisionCoordinatorWorker = (function () {
  15450. function CollisionCoordinatorWorker() {
  15451. var _this = this;
  15452. this._scaledPosition = BABYLON.Vector3.Zero();
  15453. this._scaledVelocity = BABYLON.Vector3.Zero();
  15454. this.onMeshUpdated = function (mesh) {
  15455. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15456. };
  15457. this.onGeometryUpdated = function (geometry) {
  15458. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15459. };
  15460. this._afterRender = function () {
  15461. if (!_this._init)
  15462. return;
  15463. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15464. return;
  15465. }
  15466. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15467. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15468. if (_this._runningUpdated > 4) {
  15469. return;
  15470. }
  15471. ++_this._runningUpdated;
  15472. var payload = {
  15473. updatedMeshes: _this._addUpdateMeshesList,
  15474. updatedGeometries: _this._addUpdateGeometriesList,
  15475. removedGeometries: _this._toRemoveGeometryArray,
  15476. removedMeshes: _this._toRemoveMeshesArray
  15477. };
  15478. var message = {
  15479. payload: payload,
  15480. taskType: WorkerTaskType.UPDATE
  15481. };
  15482. var serializable = [];
  15483. for (var id in payload.updatedGeometries) {
  15484. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15485. //prepare transferables
  15486. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15487. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15488. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15489. }
  15490. }
  15491. _this._worker.postMessage(message, serializable);
  15492. _this._addUpdateMeshesList = {};
  15493. _this._addUpdateGeometriesList = {};
  15494. _this._toRemoveGeometryArray = [];
  15495. _this._toRemoveMeshesArray = [];
  15496. };
  15497. this._onMessageFromWorker = function (e) {
  15498. var returnData = e.data;
  15499. if (returnData.error != WorkerReplyType.SUCCESS) {
  15500. //TODO what errors can be returned from the worker?
  15501. BABYLON.Tools.Warn("error returned from worker!");
  15502. return;
  15503. }
  15504. switch (returnData.taskType) {
  15505. case WorkerTaskType.INIT:
  15506. _this._init = true;
  15507. //Update the worked with ALL of the scene's current state
  15508. _this._scene.meshes.forEach(function (mesh) {
  15509. _this.onMeshAdded(mesh);
  15510. });
  15511. _this._scene.getGeometries().forEach(function (geometry) {
  15512. _this.onGeometryAdded(geometry);
  15513. });
  15514. break;
  15515. case WorkerTaskType.UPDATE:
  15516. _this._runningUpdated--;
  15517. break;
  15518. case WorkerTaskType.COLLIDE:
  15519. _this._runningCollisionTask = false;
  15520. var returnPayload = returnData.payload;
  15521. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15522. return;
  15523. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15524. //cleanup
  15525. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15526. break;
  15527. }
  15528. };
  15529. this._collisionsCallbackArray = [];
  15530. this._init = false;
  15531. this._runningUpdated = 0;
  15532. this._runningCollisionTask = false;
  15533. this._addUpdateMeshesList = {};
  15534. this._addUpdateGeometriesList = {};
  15535. this._toRemoveGeometryArray = [];
  15536. this._toRemoveMeshesArray = [];
  15537. }
  15538. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15539. if (!this._init)
  15540. return;
  15541. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15542. return;
  15543. position.divideToRef(collider.radius, this._scaledPosition);
  15544. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15545. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15546. var payload = {
  15547. collider: {
  15548. position: this._scaledPosition.asArray(),
  15549. velocity: this._scaledVelocity.asArray(),
  15550. radius: collider.radius.asArray()
  15551. },
  15552. collisionId: collisionIndex,
  15553. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15554. maximumRetry: maximumRetry
  15555. };
  15556. var message = {
  15557. payload: payload,
  15558. taskType: WorkerTaskType.COLLIDE
  15559. };
  15560. this._worker.postMessage(message);
  15561. };
  15562. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15563. this._scene = scene;
  15564. this._scene.registerAfterRender(this._afterRender);
  15565. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15566. this._worker = new Worker(workerUrl);
  15567. this._worker.onmessage = this._onMessageFromWorker;
  15568. var message = {
  15569. payload: {},
  15570. taskType: WorkerTaskType.INIT
  15571. };
  15572. this._worker.postMessage(message);
  15573. };
  15574. CollisionCoordinatorWorker.prototype.destroy = function () {
  15575. this._scene.unregisterAfterRender(this._afterRender);
  15576. this._worker.terminate();
  15577. };
  15578. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15579. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15580. this.onMeshUpdated(mesh);
  15581. };
  15582. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15583. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15584. };
  15585. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15586. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15587. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15588. this.onGeometryUpdated(geometry);
  15589. };
  15590. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15591. this._toRemoveGeometryArray.push(geometry.id);
  15592. };
  15593. return CollisionCoordinatorWorker;
  15594. }());
  15595. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15596. var submeshes = [];
  15597. if (mesh.subMeshes) {
  15598. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15599. return {
  15600. position: idx,
  15601. verticesStart: sm.verticesStart,
  15602. verticesCount: sm.verticesCount,
  15603. indexStart: sm.indexStart,
  15604. indexCount: sm.indexCount,
  15605. hasMaterial: !!sm.getMaterial(),
  15606. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15607. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15608. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15609. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15610. };
  15611. });
  15612. }
  15613. var geometryId = null;
  15614. if (mesh instanceof BABYLON.Mesh) {
  15615. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15616. }
  15617. else if (mesh instanceof BABYLON.InstancedMesh) {
  15618. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15619. }
  15620. return {
  15621. uniqueId: mesh.uniqueId,
  15622. id: mesh.id,
  15623. name: mesh.name,
  15624. geometryId: geometryId,
  15625. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15626. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15627. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15628. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15629. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15630. subMeshes: submeshes,
  15631. checkCollisions: mesh.checkCollisions
  15632. };
  15633. };
  15634. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15635. return {
  15636. id: geometry.id,
  15637. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15638. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15639. indices: new Uint32Array(geometry.getIndices() || []),
  15640. };
  15641. };
  15642. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15643. var CollisionCoordinatorLegacy = (function () {
  15644. function CollisionCoordinatorLegacy() {
  15645. this._scaledPosition = BABYLON.Vector3.Zero();
  15646. this._scaledVelocity = BABYLON.Vector3.Zero();
  15647. this._finalPosition = BABYLON.Vector3.Zero();
  15648. }
  15649. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15650. position.divideToRef(collider.radius, this._scaledPosition);
  15651. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15652. collider.collidedMesh = null;
  15653. collider.retry = 0;
  15654. collider.initialVelocity = this._scaledVelocity;
  15655. collider.initialPosition = this._scaledPosition;
  15656. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15657. this._finalPosition.multiplyInPlace(collider.radius);
  15658. //run the callback
  15659. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15660. };
  15661. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15662. this._scene = scene;
  15663. };
  15664. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15665. //Legacy need no destruction method.
  15666. };
  15667. //No update in legacy mode
  15668. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15669. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15670. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15671. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15672. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15673. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15674. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15675. if (excludedMesh === void 0) { excludedMesh = null; }
  15676. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15677. if (collider.retry >= maximumRetry) {
  15678. finalPosition.copyFrom(position);
  15679. return;
  15680. }
  15681. // Check if this is a mesh else camera or -1
  15682. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15683. collider._initialize(position, velocity, closeDistance);
  15684. // Check all meshes
  15685. for (var index = 0; index < this._scene.meshes.length; index++) {
  15686. var mesh = this._scene.meshes[index];
  15687. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15688. mesh._checkCollision(collider);
  15689. }
  15690. }
  15691. if (!collider.collisionFound) {
  15692. position.addToRef(velocity, finalPosition);
  15693. return;
  15694. }
  15695. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15696. collider._getResponse(position, velocity);
  15697. }
  15698. if (velocity.length() <= closeDistance) {
  15699. finalPosition.copyFrom(position);
  15700. return;
  15701. }
  15702. collider.retry++;
  15703. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15704. };
  15705. return CollisionCoordinatorLegacy;
  15706. }());
  15707. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15708. })(BABYLON || (BABYLON = {}));
  15709. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15710. var BABYLON;
  15711. (function (BABYLON) {
  15712. var Camera = (function (_super) {
  15713. __extends(Camera, _super);
  15714. function Camera(name, position, scene) {
  15715. var _this = _super.call(this, name, scene) || this;
  15716. _this.upVector = BABYLON.Vector3.Up();
  15717. _this.orthoLeft = null;
  15718. _this.orthoRight = null;
  15719. _this.orthoBottom = null;
  15720. _this.orthoTop = null;
  15721. _this.fov = 0.8;
  15722. _this.minZ = 1.0;
  15723. _this.maxZ = 10000.0;
  15724. _this.inertia = 0.9;
  15725. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15726. _this.isIntermediate = false;
  15727. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15728. _this.layerMask = 0x0FFFFFFF;
  15729. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15730. // Camera rig members
  15731. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15732. _this._rigCameras = new Array();
  15733. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15734. // Cache
  15735. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15736. _this._projectionMatrix = new BABYLON.Matrix();
  15737. _this._doNotComputeProjectionMatrix = false;
  15738. _this._postProcesses = new Array();
  15739. _this._transformMatrix = BABYLON.Matrix.Zero();
  15740. _this._activeMeshes = new BABYLON.SmartArray(256);
  15741. _this._globalPosition = BABYLON.Vector3.Zero();
  15742. _this._refreshFrustumPlanes = true;
  15743. _this.getScene().addCamera(_this);
  15744. if (!_this.getScene().activeCamera) {
  15745. _this.getScene().activeCamera = _this;
  15746. }
  15747. _this.position = position;
  15748. return _this;
  15749. }
  15750. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15751. get: function () {
  15752. return Camera._PERSPECTIVE_CAMERA;
  15753. },
  15754. enumerable: true,
  15755. configurable: true
  15756. });
  15757. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15758. get: function () {
  15759. return Camera._ORTHOGRAPHIC_CAMERA;
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15765. get: function () {
  15766. return Camera._FOVMODE_VERTICAL_FIXED;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15772. get: function () {
  15773. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15779. get: function () {
  15780. return Camera._RIG_MODE_NONE;
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15786. get: function () {
  15787. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15793. get: function () {
  15794. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15800. get: function () {
  15801. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15807. get: function () {
  15808. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15814. get: function () {
  15815. return Camera._RIG_MODE_VR;
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15821. get: function () {
  15822. return Camera._RIG_MODE_WEBVR;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Camera.prototype.getClassName = function () {
  15828. return "Camera";
  15829. };
  15830. /**
  15831. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15832. */
  15833. Camera.prototype.toString = function (fullDetails) {
  15834. var ret = "Name: " + this.name;
  15835. ret += ", type: " + this.getClassName();
  15836. if (this.animations) {
  15837. for (var i = 0; i < this.animations.length; i++) {
  15838. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15839. }
  15840. }
  15841. if (fullDetails) {
  15842. }
  15843. return ret;
  15844. };
  15845. Object.defineProperty(Camera.prototype, "globalPosition", {
  15846. get: function () {
  15847. return this._globalPosition;
  15848. },
  15849. enumerable: true,
  15850. configurable: true
  15851. });
  15852. Camera.prototype.getActiveMeshes = function () {
  15853. return this._activeMeshes;
  15854. };
  15855. Camera.prototype.isActiveMesh = function (mesh) {
  15856. return (this._activeMeshes.indexOf(mesh) !== -1);
  15857. };
  15858. //Cache
  15859. Camera.prototype._initCache = function () {
  15860. _super.prototype._initCache.call(this);
  15861. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15862. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15863. this._cache.mode = undefined;
  15864. this._cache.minZ = undefined;
  15865. this._cache.maxZ = undefined;
  15866. this._cache.fov = undefined;
  15867. this._cache.fovMode = undefined;
  15868. this._cache.aspectRatio = undefined;
  15869. this._cache.orthoLeft = undefined;
  15870. this._cache.orthoRight = undefined;
  15871. this._cache.orthoBottom = undefined;
  15872. this._cache.orthoTop = undefined;
  15873. this._cache.renderWidth = undefined;
  15874. this._cache.renderHeight = undefined;
  15875. };
  15876. Camera.prototype._updateCache = function (ignoreParentClass) {
  15877. if (!ignoreParentClass) {
  15878. _super.prototype._updateCache.call(this);
  15879. }
  15880. var engine = this.getEngine();
  15881. this._cache.position.copyFrom(this.position);
  15882. this._cache.upVector.copyFrom(this.upVector);
  15883. this._cache.mode = this.mode;
  15884. this._cache.minZ = this.minZ;
  15885. this._cache.maxZ = this.maxZ;
  15886. this._cache.fov = this.fov;
  15887. this._cache.fovMode = this.fovMode;
  15888. this._cache.aspectRatio = engine.getAspectRatio(this);
  15889. this._cache.orthoLeft = this.orthoLeft;
  15890. this._cache.orthoRight = this.orthoRight;
  15891. this._cache.orthoBottom = this.orthoBottom;
  15892. this._cache.orthoTop = this.orthoTop;
  15893. this._cache.renderWidth = engine.getRenderWidth();
  15894. this._cache.renderHeight = engine.getRenderHeight();
  15895. };
  15896. Camera.prototype._updateFromScene = function () {
  15897. this.updateCache();
  15898. this.update();
  15899. };
  15900. // Synchronized
  15901. Camera.prototype._isSynchronized = function () {
  15902. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15903. };
  15904. Camera.prototype._isSynchronizedViewMatrix = function () {
  15905. if (!_super.prototype._isSynchronized.call(this))
  15906. return false;
  15907. return this._cache.position.equals(this.position)
  15908. && this._cache.upVector.equals(this.upVector)
  15909. && this.isSynchronizedWithParent();
  15910. };
  15911. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15912. var check = this._cache.mode === this.mode
  15913. && this._cache.minZ === this.minZ
  15914. && this._cache.maxZ === this.maxZ;
  15915. if (!check) {
  15916. return false;
  15917. }
  15918. var engine = this.getEngine();
  15919. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15920. check = this._cache.fov === this.fov
  15921. && this._cache.fovMode === this.fovMode
  15922. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15923. }
  15924. else {
  15925. check = this._cache.orthoLeft === this.orthoLeft
  15926. && this._cache.orthoRight === this.orthoRight
  15927. && this._cache.orthoBottom === this.orthoBottom
  15928. && this._cache.orthoTop === this.orthoTop
  15929. && this._cache.renderWidth === engine.getRenderWidth()
  15930. && this._cache.renderHeight === engine.getRenderHeight();
  15931. }
  15932. return check;
  15933. };
  15934. // Controls
  15935. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15936. };
  15937. Camera.prototype.detachControl = function (element) {
  15938. };
  15939. Camera.prototype.update = function () {
  15940. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15941. this._updateRigCameras();
  15942. }
  15943. this._checkInputs();
  15944. };
  15945. Camera.prototype._checkInputs = function () {
  15946. };
  15947. Object.defineProperty(Camera.prototype, "rigCameras", {
  15948. get: function () {
  15949. return this._rigCameras;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15955. get: function () {
  15956. return this._rigPostProcess;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15962. // invalidate framebuffer
  15963. if (this._postProcesses.length > 0) {
  15964. this._postProcesses[0].markTextureDirty();
  15965. }
  15966. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15967. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15968. var cam = this._rigCameras[i];
  15969. var rigPostProcess = cam._rigPostProcess;
  15970. // for VR rig, there does not have to be a post process
  15971. if (rigPostProcess) {
  15972. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15973. if (isPass) {
  15974. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15975. cam.isIntermediate = this._postProcesses.length === 0;
  15976. }
  15977. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15978. rigPostProcess.markTextureDirty();
  15979. }
  15980. else {
  15981. cam._postProcesses = this._postProcesses.slice(0);
  15982. }
  15983. }
  15984. };
  15985. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15986. if (insertAt === void 0) { insertAt = null; }
  15987. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15988. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15989. return 0;
  15990. }
  15991. if (insertAt == null || insertAt < 0) {
  15992. this._postProcesses.push(postProcess);
  15993. }
  15994. else {
  15995. this._postProcesses.splice(insertAt, 0, postProcess);
  15996. }
  15997. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15998. return this._postProcesses.indexOf(postProcess);
  15999. };
  16000. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  16001. if (atIndices === void 0) { atIndices = null; }
  16002. var result = [];
  16003. var i;
  16004. var index;
  16005. if (!atIndices) {
  16006. var idx = this._postProcesses.indexOf(postProcess);
  16007. if (idx !== -1) {
  16008. this._postProcesses.splice(idx, 1);
  16009. }
  16010. }
  16011. else {
  16012. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  16013. // iterate descending, so can just splice as we go
  16014. for (i = atIndices.length - 1; i >= 0; i--) {
  16015. if (this._postProcesses[atIndices[i]] !== postProcess) {
  16016. result.push(i);
  16017. continue;
  16018. }
  16019. index = atIndices[i];
  16020. this._postProcesses.splice(index, 1);
  16021. }
  16022. }
  16023. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16024. return result;
  16025. };
  16026. Camera.prototype.getWorldMatrix = function () {
  16027. if (!this._worldMatrix) {
  16028. this._worldMatrix = BABYLON.Matrix.Identity();
  16029. }
  16030. var viewMatrix = this.getViewMatrix();
  16031. viewMatrix.invertToRef(this._worldMatrix);
  16032. return this._worldMatrix;
  16033. };
  16034. Camera.prototype._getViewMatrix = function () {
  16035. return BABYLON.Matrix.Identity();
  16036. };
  16037. Camera.prototype.getViewMatrix = function (force) {
  16038. this._computedViewMatrix = this._computeViewMatrix(force);
  16039. if (!force && this._isSynchronizedViewMatrix()) {
  16040. return this._computedViewMatrix;
  16041. }
  16042. this._refreshFrustumPlanes = true;
  16043. if (!this.parent || !this.parent.getWorldMatrix) {
  16044. this._globalPosition.copyFrom(this.position);
  16045. }
  16046. else {
  16047. if (!this._worldMatrix) {
  16048. this._worldMatrix = BABYLON.Matrix.Identity();
  16049. }
  16050. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16051. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16052. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16053. this._computedViewMatrix.invert();
  16054. this._markSyncedWithParent();
  16055. }
  16056. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16057. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16058. }
  16059. this._currentRenderId = this.getScene().getRenderId();
  16060. return this._computedViewMatrix;
  16061. };
  16062. Camera.prototype._computeViewMatrix = function (force) {
  16063. if (!force && this._isSynchronizedViewMatrix()) {
  16064. return this._computedViewMatrix;
  16065. }
  16066. this._computedViewMatrix = this._getViewMatrix();
  16067. this._currentRenderId = this.getScene().getRenderId();
  16068. return this._computedViewMatrix;
  16069. };
  16070. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16071. this._doNotComputeProjectionMatrix = true;
  16072. if (projection !== undefined) {
  16073. this._projectionMatrix = projection;
  16074. }
  16075. };
  16076. ;
  16077. Camera.prototype.unfreezeProjectionMatrix = function () {
  16078. this._doNotComputeProjectionMatrix = false;
  16079. };
  16080. ;
  16081. Camera.prototype.getProjectionMatrix = function (force) {
  16082. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16083. return this._projectionMatrix;
  16084. }
  16085. this._refreshFrustumPlanes = true;
  16086. var engine = this.getEngine();
  16087. var scene = this.getScene();
  16088. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16089. if (this.minZ <= 0) {
  16090. this.minZ = 0.1;
  16091. }
  16092. if (scene.useRightHandedSystem) {
  16093. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16094. }
  16095. else {
  16096. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16097. }
  16098. return this._projectionMatrix;
  16099. }
  16100. var halfWidth = engine.getRenderWidth() / 2.0;
  16101. var halfHeight = engine.getRenderHeight() / 2.0;
  16102. if (scene.useRightHandedSystem) {
  16103. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16104. }
  16105. else {
  16106. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16107. }
  16108. return this._projectionMatrix;
  16109. };
  16110. Camera.prototype.getTranformationMatrix = function () {
  16111. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16112. return this._transformMatrix;
  16113. };
  16114. Camera.prototype.updateFrustumPlanes = function () {
  16115. if (!this._refreshFrustumPlanes) {
  16116. return;
  16117. }
  16118. this.getTranformationMatrix();
  16119. if (!this._frustumPlanes) {
  16120. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16121. }
  16122. else {
  16123. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16124. }
  16125. this._refreshFrustumPlanes = false;
  16126. };
  16127. Camera.prototype.isInFrustum = function (target) {
  16128. this.updateFrustumPlanes();
  16129. return target.isInFrustum(this._frustumPlanes);
  16130. };
  16131. Camera.prototype.isCompletelyInFrustum = function (target) {
  16132. this.updateFrustumPlanes();
  16133. return target.isCompletelyInFrustum(this._frustumPlanes);
  16134. };
  16135. Camera.prototype.dispose = function () {
  16136. // Animations
  16137. this.getScene().stopAnimation(this);
  16138. // Remove from scene
  16139. this.getScene().removeCamera(this);
  16140. while (this._rigCameras.length > 0) {
  16141. this._rigCameras.pop().dispose();
  16142. }
  16143. // Postprocesses
  16144. var i = this._postProcesses.length;
  16145. while (--i >= 0) {
  16146. this._postProcesses[i].dispose(this);
  16147. }
  16148. _super.prototype.dispose.call(this);
  16149. };
  16150. // ---- Camera rigs section ----
  16151. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16152. while (this._rigCameras.length > 0) {
  16153. this._rigCameras.pop().dispose();
  16154. }
  16155. this.cameraRigMode = mode;
  16156. this._cameraRigParams = {};
  16157. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16158. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16159. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16160. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16161. // create the rig cameras, unless none
  16162. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16163. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16164. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16165. }
  16166. switch (this.cameraRigMode) {
  16167. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16168. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16169. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16170. break;
  16171. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16172. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16173. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16174. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16175. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16176. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16177. break;
  16178. case Camera.RIG_MODE_VR:
  16179. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16180. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16181. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16182. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16183. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16184. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16185. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16186. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16187. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16188. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16189. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16190. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16191. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16192. if (metrics.compensateDistortion) {
  16193. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16194. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16195. }
  16196. break;
  16197. case Camera.RIG_MODE_WEBVR:
  16198. if (rigParams.vrDisplay) {
  16199. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16200. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16201. //Left eye
  16202. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16203. this._rigCameras[0].setCameraRigParameter("left", true);
  16204. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16205. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16206. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16207. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16208. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16209. this._rigCameras[0].parent = this;
  16210. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16211. //Right eye
  16212. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16213. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16214. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16215. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16216. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16217. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16218. this._rigCameras[1].parent = this;
  16219. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16220. }
  16221. break;
  16222. }
  16223. this._cascadePostProcessesToRigCams();
  16224. this.
  16225. update();
  16226. };
  16227. Camera.prototype._getVRProjectionMatrix = function () {
  16228. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16229. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16230. return this._projectionMatrix;
  16231. };
  16232. Camera.prototype._updateCameraRotationMatrix = function () {
  16233. //Here for WebVR
  16234. };
  16235. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16236. //Here for WebVR
  16237. };
  16238. /**
  16239. * This function MUST be overwritten by the different WebVR cameras available.
  16240. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16241. */
  16242. Camera.prototype._getWebVRProjectionMatrix = function () {
  16243. return BABYLON.Matrix.Identity();
  16244. };
  16245. /**
  16246. * This function MUST be overwritten by the different WebVR cameras available.
  16247. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16248. */
  16249. Camera.prototype._getWebVRViewMatrix = function () {
  16250. return BABYLON.Matrix.Identity();
  16251. };
  16252. Camera.prototype.setCameraRigParameter = function (name, value) {
  16253. if (!this._cameraRigParams) {
  16254. this._cameraRigParams = {};
  16255. }
  16256. this._cameraRigParams[name] = value;
  16257. //provisionnally:
  16258. if (name === "interaxialDistance") {
  16259. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16260. }
  16261. };
  16262. /**
  16263. * needs to be overridden by children so sub has required properties to be copied
  16264. */
  16265. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16266. return null;
  16267. };
  16268. /**
  16269. * May need to be overridden by children
  16270. */
  16271. Camera.prototype._updateRigCameras = function () {
  16272. for (var i = 0; i < this._rigCameras.length; i++) {
  16273. this._rigCameras[i].minZ = this.minZ;
  16274. this._rigCameras[i].maxZ = this.maxZ;
  16275. this._rigCameras[i].fov = this.fov;
  16276. }
  16277. // only update viewport when ANAGLYPH
  16278. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16279. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16280. }
  16281. };
  16282. Camera.prototype._setupInputs = function () {
  16283. };
  16284. Camera.prototype.serialize = function () {
  16285. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16286. // Type
  16287. serializationObject.type = this.getClassName();
  16288. // Parent
  16289. if (this.parent) {
  16290. serializationObject.parentId = this.parent.id;
  16291. }
  16292. if (this.inputs) {
  16293. this.inputs.serialize(serializationObject);
  16294. }
  16295. // Animations
  16296. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16297. serializationObject.ranges = this.serializeAnimationRanges();
  16298. return serializationObject;
  16299. };
  16300. Camera.prototype.clone = function (name) {
  16301. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16302. };
  16303. Camera.prototype.getDirection = function (localAxis) {
  16304. var result = BABYLON.Vector3.Zero();
  16305. this.getDirectionToRef(localAxis, result);
  16306. return result;
  16307. };
  16308. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16309. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16310. };
  16311. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16312. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16313. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16314. switch (type) {
  16315. case "ArcRotateCamera":
  16316. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16317. case "DeviceOrientationCamera":
  16318. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16319. case "FollowCamera":
  16320. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16321. case "ArcFollowCamera":
  16322. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16323. case "GamepadCamera":
  16324. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16325. case "TouchCamera":
  16326. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16327. case "VirtualJoysticksCamera":
  16328. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16329. case "WebVRFreeCamera":
  16330. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16331. case "WebVRGamepadCamera":
  16332. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16333. case "VRDeviceOrientationFreeCamera":
  16334. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16335. case "VRDeviceOrientationGamepadCamera":
  16336. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16337. case "AnaglyphArcRotateCamera":
  16338. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16339. case "AnaglyphFreeCamera":
  16340. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16341. case "AnaglyphGamepadCamera":
  16342. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16343. case "AnaglyphUniversalCamera":
  16344. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16345. case "StereoscopicArcRotateCamera":
  16346. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16347. case "StereoscopicFreeCamera":
  16348. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16349. case "StereoscopicGamepadCamera":
  16350. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16351. case "StereoscopicUniversalCamera":
  16352. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16353. case "FreeCamera":
  16354. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16355. default:
  16356. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16357. }
  16358. };
  16359. Camera.Parse = function (parsedCamera, scene) {
  16360. var type = parsedCamera.type;
  16361. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16362. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16363. // Parent
  16364. if (parsedCamera.parentId) {
  16365. camera._waitingParentId = parsedCamera.parentId;
  16366. }
  16367. //If camera has an input manager, let it parse inputs settings
  16368. if (camera.inputs) {
  16369. camera.inputs.parse(parsedCamera);
  16370. camera._setupInputs();
  16371. }
  16372. // Target
  16373. if (parsedCamera.target) {
  16374. if (camera.setTarget) {
  16375. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16376. }
  16377. }
  16378. // Apply 3d rig, when found
  16379. if (parsedCamera.cameraRigMode) {
  16380. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16381. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16382. }
  16383. // Animations
  16384. if (parsedCamera.animations) {
  16385. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16386. var parsedAnimation = parsedCamera.animations[animationIndex];
  16387. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16388. }
  16389. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16390. }
  16391. if (parsedCamera.autoAnimate) {
  16392. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16393. }
  16394. return camera;
  16395. };
  16396. return Camera;
  16397. }(BABYLON.Node));
  16398. // Statics
  16399. Camera._PERSPECTIVE_CAMERA = 0;
  16400. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16401. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16402. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16403. Camera._RIG_MODE_NONE = 0;
  16404. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16405. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16406. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16407. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16408. Camera._RIG_MODE_VR = 20;
  16409. Camera._RIG_MODE_WEBVR = 21;
  16410. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16411. __decorate([
  16412. BABYLON.serializeAsVector3()
  16413. ], Camera.prototype, "position", void 0);
  16414. __decorate([
  16415. BABYLON.serializeAsVector3()
  16416. ], Camera.prototype, "upVector", void 0);
  16417. __decorate([
  16418. BABYLON.serialize()
  16419. ], Camera.prototype, "orthoLeft", void 0);
  16420. __decorate([
  16421. BABYLON.serialize()
  16422. ], Camera.prototype, "orthoRight", void 0);
  16423. __decorate([
  16424. BABYLON.serialize()
  16425. ], Camera.prototype, "orthoBottom", void 0);
  16426. __decorate([
  16427. BABYLON.serialize()
  16428. ], Camera.prototype, "orthoTop", void 0);
  16429. __decorate([
  16430. BABYLON.serialize()
  16431. ], Camera.prototype, "fov", void 0);
  16432. __decorate([
  16433. BABYLON.serialize()
  16434. ], Camera.prototype, "minZ", void 0);
  16435. __decorate([
  16436. BABYLON.serialize()
  16437. ], Camera.prototype, "maxZ", void 0);
  16438. __decorate([
  16439. BABYLON.serialize()
  16440. ], Camera.prototype, "inertia", void 0);
  16441. __decorate([
  16442. BABYLON.serialize()
  16443. ], Camera.prototype, "mode", void 0);
  16444. __decorate([
  16445. BABYLON.serialize()
  16446. ], Camera.prototype, "layerMask", void 0);
  16447. __decorate([
  16448. BABYLON.serialize()
  16449. ], Camera.prototype, "fovMode", void 0);
  16450. __decorate([
  16451. BABYLON.serialize()
  16452. ], Camera.prototype, "cameraRigMode", void 0);
  16453. __decorate([
  16454. BABYLON.serialize()
  16455. ], Camera.prototype, "interaxialDistance", void 0);
  16456. __decorate([
  16457. BABYLON.serialize()
  16458. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16459. BABYLON.Camera = Camera;
  16460. })(BABYLON || (BABYLON = {}));
  16461. //# sourceMappingURL=babylon.camera.js.map
  16462. var BABYLON;
  16463. (function (BABYLON) {
  16464. BABYLON.CameraInputTypes = {};
  16465. var CameraInputsManager = (function () {
  16466. function CameraInputsManager(camera) {
  16467. this.attached = {};
  16468. this.camera = camera;
  16469. this.checkInputs = function () { };
  16470. }
  16471. CameraInputsManager.prototype.add = function (input) {
  16472. var type = input.getSimpleName();
  16473. if (this.attached[type]) {
  16474. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16475. return;
  16476. }
  16477. this.attached[type] = input;
  16478. input.camera = this.camera;
  16479. //for checkInputs, we are dynamically creating a function
  16480. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16481. if (input.checkInputs) {
  16482. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16483. }
  16484. if (this.attachedElement) {
  16485. input.attachControl(this.attachedElement);
  16486. }
  16487. };
  16488. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16489. for (var cam in this.attached) {
  16490. var input = this.attached[cam];
  16491. if (input === inputToRemove) {
  16492. input.detachControl(this.attachedElement);
  16493. delete this.attached[cam];
  16494. this.rebuildInputCheck();
  16495. }
  16496. }
  16497. };
  16498. CameraInputsManager.prototype.removeByType = function (inputType) {
  16499. for (var cam in this.attached) {
  16500. var input = this.attached[cam];
  16501. if (input.getTypeName() === inputType) {
  16502. input.detachControl(this.attachedElement);
  16503. delete this.attached[cam];
  16504. this.rebuildInputCheck();
  16505. }
  16506. }
  16507. };
  16508. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16509. var current = this.checkInputs;
  16510. return function () {
  16511. current();
  16512. fn();
  16513. };
  16514. };
  16515. CameraInputsManager.prototype.attachInput = function (input) {
  16516. input.attachControl(this.attachedElement, this.noPreventDefault);
  16517. };
  16518. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16519. if (this.attachedElement) {
  16520. return;
  16521. }
  16522. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16523. this.attachedElement = element;
  16524. this.noPreventDefault = noPreventDefault;
  16525. for (var cam in this.attached) {
  16526. var input = this.attached[cam];
  16527. this.attached[cam].attachControl(element, noPreventDefault);
  16528. }
  16529. };
  16530. CameraInputsManager.prototype.detachElement = function (element) {
  16531. if (this.attachedElement !== element) {
  16532. return;
  16533. }
  16534. for (var cam in this.attached) {
  16535. var input = this.attached[cam];
  16536. this.attached[cam].detachControl(element);
  16537. }
  16538. this.attachedElement = null;
  16539. };
  16540. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16541. this.checkInputs = function () { };
  16542. for (var cam in this.attached) {
  16543. var input = this.attached[cam];
  16544. if (input.checkInputs) {
  16545. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16546. }
  16547. }
  16548. };
  16549. CameraInputsManager.prototype.clear = function () {
  16550. if (this.attachedElement) {
  16551. this.detachElement(this.attachedElement);
  16552. }
  16553. this.attached = {};
  16554. this.attachedElement = null;
  16555. this.checkInputs = function () { };
  16556. };
  16557. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16558. var inputs = {};
  16559. for (var cam in this.attached) {
  16560. var input = this.attached[cam];
  16561. var res = BABYLON.SerializationHelper.Serialize(input);
  16562. inputs[input.getTypeName()] = res;
  16563. }
  16564. serializedCamera.inputsmgr = inputs;
  16565. };
  16566. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16567. var parsedInputs = parsedCamera.inputsmgr;
  16568. if (parsedInputs) {
  16569. this.clear();
  16570. for (var n in parsedInputs) {
  16571. var construct = BABYLON.CameraInputTypes[n];
  16572. if (construct) {
  16573. var parsedinput = parsedInputs[n];
  16574. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16575. this.add(input);
  16576. }
  16577. }
  16578. }
  16579. else {
  16580. //2016-03-08 this part is for managing backward compatibility
  16581. for (var n in this.attached) {
  16582. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16583. if (construct) {
  16584. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16585. this.remove(this.attached[n]);
  16586. this.add(input);
  16587. }
  16588. }
  16589. }
  16590. };
  16591. return CameraInputsManager;
  16592. }());
  16593. BABYLON.CameraInputsManager = CameraInputsManager;
  16594. })(BABYLON || (BABYLON = {}));
  16595. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16596. var BABYLON;
  16597. (function (BABYLON) {
  16598. var FreeCameraMouseInput = (function () {
  16599. function FreeCameraMouseInput(touchEnabled) {
  16600. if (touchEnabled === void 0) { touchEnabled = true; }
  16601. this.touchEnabled = touchEnabled;
  16602. this.buttons = [0, 1, 2];
  16603. this.angularSensibility = 2000.0;
  16604. }
  16605. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16606. var _this = this;
  16607. var engine = this.camera.getEngine();
  16608. if (!this._pointerInput) {
  16609. this._pointerInput = function (p, s) {
  16610. var evt = p.event;
  16611. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16612. return;
  16613. }
  16614. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16615. return;
  16616. }
  16617. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16618. try {
  16619. evt.srcElement.setPointerCapture(evt.pointerId);
  16620. }
  16621. catch (e) {
  16622. //Nothing to do with the error. Execution will continue.
  16623. }
  16624. _this.previousPosition = {
  16625. x: evt.clientX,
  16626. y: evt.clientY
  16627. };
  16628. if (!noPreventDefault) {
  16629. evt.preventDefault();
  16630. element.focus();
  16631. }
  16632. }
  16633. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16634. try {
  16635. evt.srcElement.releasePointerCapture(evt.pointerId);
  16636. }
  16637. catch (e) {
  16638. //Nothing to do with the error.
  16639. }
  16640. _this.previousPosition = null;
  16641. if (!noPreventDefault) {
  16642. evt.preventDefault();
  16643. }
  16644. }
  16645. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16646. if (!_this.previousPosition || engine.isPointerLock) {
  16647. return;
  16648. }
  16649. var offsetX = evt.clientX - _this.previousPosition.x;
  16650. var offsetY = evt.clientY - _this.previousPosition.y;
  16651. if (_this.camera.getScene().useRightHandedSystem) {
  16652. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16653. }
  16654. else {
  16655. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16656. }
  16657. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16658. _this.previousPosition = {
  16659. x: evt.clientX,
  16660. y: evt.clientY
  16661. };
  16662. if (!noPreventDefault) {
  16663. evt.preventDefault();
  16664. }
  16665. }
  16666. };
  16667. }
  16668. this._onMouseMove = function (evt) {
  16669. if (!engine.isPointerLock) {
  16670. return;
  16671. }
  16672. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16673. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16674. if (_this.camera.getScene().useRightHandedSystem) {
  16675. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16676. }
  16677. else {
  16678. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16679. }
  16680. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16681. _this.previousPosition = null;
  16682. if (!noPreventDefault) {
  16683. evt.preventDefault();
  16684. }
  16685. };
  16686. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16687. element.addEventListener("mousemove", this._onMouseMove, false);
  16688. };
  16689. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16690. if (this._observer && element) {
  16691. this.camera.getScene().onPointerObservable.remove(this._observer);
  16692. element.removeEventListener("mousemove", this._onMouseMove);
  16693. this._observer = null;
  16694. this._onMouseMove = null;
  16695. this.previousPosition = null;
  16696. }
  16697. };
  16698. FreeCameraMouseInput.prototype.getTypeName = function () {
  16699. return "FreeCameraMouseInput";
  16700. };
  16701. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16702. return "mouse";
  16703. };
  16704. return FreeCameraMouseInput;
  16705. }());
  16706. __decorate([
  16707. BABYLON.serialize()
  16708. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16709. __decorate([
  16710. BABYLON.serialize()
  16711. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16712. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16713. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16714. })(BABYLON || (BABYLON = {}));
  16715. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16716. var BABYLON;
  16717. (function (BABYLON) {
  16718. var FreeCameraKeyboardMoveInput = (function () {
  16719. function FreeCameraKeyboardMoveInput() {
  16720. this._keys = [];
  16721. this.keysUp = [38];
  16722. this.keysDown = [40];
  16723. this.keysLeft = [37];
  16724. this.keysRight = [39];
  16725. }
  16726. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16727. var _this = this;
  16728. if (!this._onKeyDown) {
  16729. element.tabIndex = 1;
  16730. this._onKeyDown = function (evt) {
  16731. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16732. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16733. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16734. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16735. var index = _this._keys.indexOf(evt.keyCode);
  16736. if (index === -1) {
  16737. _this._keys.push(evt.keyCode);
  16738. }
  16739. if (!noPreventDefault) {
  16740. evt.preventDefault();
  16741. }
  16742. }
  16743. };
  16744. this._onKeyUp = function (evt) {
  16745. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16746. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16747. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16748. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16749. var index = _this._keys.indexOf(evt.keyCode);
  16750. if (index >= 0) {
  16751. _this._keys.splice(index, 1);
  16752. }
  16753. if (!noPreventDefault) {
  16754. evt.preventDefault();
  16755. }
  16756. }
  16757. };
  16758. element.addEventListener("keydown", this._onKeyDown, false);
  16759. element.addEventListener("keyup", this._onKeyUp, false);
  16760. BABYLON.Tools.RegisterTopRootEvents([
  16761. { name: "blur", handler: this._onLostFocus }
  16762. ]);
  16763. }
  16764. };
  16765. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16766. if (this._onKeyDown) {
  16767. element.removeEventListener("keydown", this._onKeyDown);
  16768. element.removeEventListener("keyup", this._onKeyUp);
  16769. BABYLON.Tools.UnregisterTopRootEvents([
  16770. { name: "blur", handler: this._onLostFocus }
  16771. ]);
  16772. this._keys = [];
  16773. this._onKeyDown = null;
  16774. this._onKeyUp = null;
  16775. }
  16776. };
  16777. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16778. if (this._onKeyDown) {
  16779. var camera = this.camera;
  16780. // Keyboard
  16781. for (var index = 0; index < this._keys.length; index++) {
  16782. var keyCode = this._keys[index];
  16783. var speed = camera._computeLocalCameraSpeed();
  16784. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16785. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16786. }
  16787. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16788. camera._localDirection.copyFromFloats(0, 0, speed);
  16789. }
  16790. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16791. camera._localDirection.copyFromFloats(speed, 0, 0);
  16792. }
  16793. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16794. camera._localDirection.copyFromFloats(0, 0, -speed);
  16795. }
  16796. if (camera.getScene().useRightHandedSystem) {
  16797. camera._localDirection.z *= -1;
  16798. }
  16799. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16800. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16801. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16802. }
  16803. }
  16804. };
  16805. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16806. return "FreeCameraKeyboardMoveInput";
  16807. };
  16808. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16809. this._keys = [];
  16810. };
  16811. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16812. return "keyboard";
  16813. };
  16814. return FreeCameraKeyboardMoveInput;
  16815. }());
  16816. __decorate([
  16817. BABYLON.serialize()
  16818. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16819. __decorate([
  16820. BABYLON.serialize()
  16821. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16822. __decorate([
  16823. BABYLON.serialize()
  16824. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16825. __decorate([
  16826. BABYLON.serialize()
  16827. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16828. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16829. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16830. })(BABYLON || (BABYLON = {}));
  16831. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16832. var BABYLON;
  16833. (function (BABYLON) {
  16834. var FreeCameraTouchInput = (function () {
  16835. function FreeCameraTouchInput() {
  16836. this._offsetX = null;
  16837. this._offsetY = null;
  16838. this._pointerCount = 0;
  16839. this._pointerPressed = [];
  16840. this.touchAngularSensibility = 200000.0;
  16841. this.touchMoveSensibility = 250.0;
  16842. }
  16843. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16844. var _this = this;
  16845. var previousPosition;
  16846. if (this._pointerInput === undefined) {
  16847. this._onLostFocus = function (evt) {
  16848. _this._offsetX = null;
  16849. _this._offsetY = null;
  16850. };
  16851. this._pointerInput = function (p, s) {
  16852. var evt = p.event;
  16853. if (evt.pointerType === "mouse") {
  16854. return;
  16855. }
  16856. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16857. if (!noPreventDefault) {
  16858. evt.preventDefault();
  16859. }
  16860. _this._pointerPressed.push(evt.pointerId);
  16861. if (_this._pointerPressed.length !== 1) {
  16862. return;
  16863. }
  16864. previousPosition = {
  16865. x: evt.clientX,
  16866. y: evt.clientY
  16867. };
  16868. }
  16869. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16870. if (!noPreventDefault) {
  16871. evt.preventDefault();
  16872. }
  16873. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16874. if (index === -1) {
  16875. return;
  16876. }
  16877. _this._pointerPressed.splice(index, 1);
  16878. if (index != 0) {
  16879. return;
  16880. }
  16881. previousPosition = null;
  16882. _this._offsetX = null;
  16883. _this._offsetY = null;
  16884. }
  16885. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16886. if (!noPreventDefault) {
  16887. evt.preventDefault();
  16888. }
  16889. if (!previousPosition) {
  16890. return;
  16891. }
  16892. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16893. if (index != 0) {
  16894. return;
  16895. }
  16896. _this._offsetX = evt.clientX - previousPosition.x;
  16897. _this._offsetY = -(evt.clientY - previousPosition.y);
  16898. }
  16899. };
  16900. }
  16901. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16902. element.addEventListener("blur", this._onLostFocus);
  16903. };
  16904. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16905. if (this._pointerInput && element) {
  16906. this.camera.getScene().onPointerObservable.remove(this._observer);
  16907. this._observer = null;
  16908. element.removeEventListener("blur", this._onLostFocus);
  16909. this._onLostFocus = null;
  16910. this._pointerPressed = [];
  16911. this._offsetX = null;
  16912. this._offsetY = null;
  16913. this._pointerCount = 0;
  16914. }
  16915. };
  16916. FreeCameraTouchInput.prototype.checkInputs = function () {
  16917. if (this._offsetX) {
  16918. var camera = this.camera;
  16919. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16920. if (this._pointerPressed.length > 1) {
  16921. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16922. }
  16923. else {
  16924. var speed = camera._computeLocalCameraSpeed();
  16925. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16926. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16927. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16928. }
  16929. }
  16930. };
  16931. FreeCameraTouchInput.prototype.getTypeName = function () {
  16932. return "FreeCameraTouchInput";
  16933. };
  16934. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16935. return "touch";
  16936. };
  16937. return FreeCameraTouchInput;
  16938. }());
  16939. __decorate([
  16940. BABYLON.serialize()
  16941. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16942. __decorate([
  16943. BABYLON.serialize()
  16944. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16945. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16946. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16947. })(BABYLON || (BABYLON = {}));
  16948. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16949. var BABYLON;
  16950. (function (BABYLON) {
  16951. var FreeCameraDeviceOrientationInput = (function () {
  16952. function FreeCameraDeviceOrientationInput() {
  16953. var _this = this;
  16954. this._screenOrientationAngle = 0;
  16955. this._screenQuaternion = new BABYLON.Quaternion();
  16956. this._alpha = 0;
  16957. this._beta = 0;
  16958. this._gamma = 0;
  16959. this._orientationChanged = function () {
  16960. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16961. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16962. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16963. };
  16964. this._deviceOrientation = function (evt) {
  16965. _this._alpha = evt.alpha;
  16966. _this._beta = evt.beta;
  16967. _this._gamma = evt.gamma;
  16968. };
  16969. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16970. this._orientationChanged();
  16971. }
  16972. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16973. get: function () {
  16974. return this._camera;
  16975. },
  16976. set: function (camera) {
  16977. this._camera = camera;
  16978. if (!this._camera.rotationQuaternion)
  16979. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16985. window.addEventListener("orientationchange", this._orientationChanged);
  16986. window.addEventListener("deviceorientation", this._deviceOrientation);
  16987. //In certain cases, the attach control is called AFTER orientation was changed,
  16988. //So this is needed.
  16989. this._orientationChanged();
  16990. };
  16991. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16992. window.removeEventListener("orientationchange", this._orientationChanged);
  16993. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16994. };
  16995. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16996. //if no device orientation provided, don't update the rotation.
  16997. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16998. if (!this._alpha)
  16999. return;
  17000. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  17001. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  17002. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  17003. //Mirror on XY Plane
  17004. this._camera.rotationQuaternion.z *= -1;
  17005. this._camera.rotationQuaternion.w *= -1;
  17006. };
  17007. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  17008. return "FreeCameraDeviceOrientationInput";
  17009. };
  17010. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  17011. return "deviceOrientation";
  17012. };
  17013. return FreeCameraDeviceOrientationInput;
  17014. }());
  17015. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  17016. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  17017. })(BABYLON || (BABYLON = {}));
  17018. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  17019. var BABYLON;
  17020. (function (BABYLON) {
  17021. var FreeCameraGamepadInput = (function () {
  17022. function FreeCameraGamepadInput() {
  17023. this.gamepadAngularSensibility = 200;
  17024. this.gamepadMoveSensibility = 40;
  17025. // private members
  17026. this._cameraTransform = BABYLON.Matrix.Identity();
  17027. this._deltaTransform = BABYLON.Vector3.Zero();
  17028. this._vector3 = BABYLON.Vector3.Zero();
  17029. this._vector2 = BABYLON.Vector2.Zero();
  17030. }
  17031. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17032. var _this = this;
  17033. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17034. };
  17035. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  17036. if (this._gamepads) {
  17037. this._gamepads.dispose();
  17038. }
  17039. this.gamepad = null;
  17040. };
  17041. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17042. if (this.gamepad && this.gamepad.leftStick) {
  17043. var camera = this.camera;
  17044. var LSValues = this.gamepad.leftStick;
  17045. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17046. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17047. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17048. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17049. var RSValues = this.gamepad.rightStick;
  17050. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17051. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17052. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17053. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17054. if (!camera.rotationQuaternion) {
  17055. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17056. }
  17057. else {
  17058. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17059. }
  17060. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17061. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17062. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17063. camera.cameraDirection.addInPlace(this._deltaTransform);
  17064. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17065. camera.cameraRotation.addInPlace(this._vector2);
  17066. }
  17067. };
  17068. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17069. // Only the first gamepad found can control the camera
  17070. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17071. // prioritize XBOX gamepads.
  17072. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17073. this.gamepad = gamepad;
  17074. }
  17075. }
  17076. };
  17077. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17078. return "FreeCameraGamepadInput";
  17079. };
  17080. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17081. return "gamepad";
  17082. };
  17083. return FreeCameraGamepadInput;
  17084. }());
  17085. __decorate([
  17086. BABYLON.serialize()
  17087. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17088. __decorate([
  17089. BABYLON.serialize()
  17090. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17091. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17092. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17093. })(BABYLON || (BABYLON = {}));
  17094. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17095. var BABYLON;
  17096. (function (BABYLON) {
  17097. var ArcRotateCameraKeyboardMoveInput = (function () {
  17098. function ArcRotateCameraKeyboardMoveInput() {
  17099. this._keys = [];
  17100. this.keysUp = [38];
  17101. this.keysDown = [40];
  17102. this.keysLeft = [37];
  17103. this.keysRight = [39];
  17104. }
  17105. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17106. var _this = this;
  17107. element.tabIndex = 1;
  17108. this._onKeyDown = function (evt) {
  17109. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17110. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17111. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17112. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17113. var index = _this._keys.indexOf(evt.keyCode);
  17114. if (index === -1) {
  17115. _this._keys.push(evt.keyCode);
  17116. }
  17117. if (evt.preventDefault) {
  17118. if (!noPreventDefault) {
  17119. evt.preventDefault();
  17120. }
  17121. }
  17122. }
  17123. };
  17124. this._onKeyUp = function (evt) {
  17125. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17126. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17127. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17128. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17129. var index = _this._keys.indexOf(evt.keyCode);
  17130. if (index >= 0) {
  17131. _this._keys.splice(index, 1);
  17132. }
  17133. if (evt.preventDefault) {
  17134. if (!noPreventDefault) {
  17135. evt.preventDefault();
  17136. }
  17137. }
  17138. }
  17139. };
  17140. this._onLostFocus = function () {
  17141. _this._keys = [];
  17142. };
  17143. element.addEventListener("keydown", this._onKeyDown, false);
  17144. element.addEventListener("keyup", this._onKeyUp, false);
  17145. BABYLON.Tools.RegisterTopRootEvents([
  17146. { name: "blur", handler: this._onLostFocus }
  17147. ]);
  17148. };
  17149. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17150. if (element) {
  17151. element.removeEventListener("keydown", this._onKeyDown);
  17152. element.removeEventListener("keyup", this._onKeyUp);
  17153. }
  17154. BABYLON.Tools.UnregisterTopRootEvents([
  17155. { name: "blur", handler: this._onLostFocus }
  17156. ]);
  17157. this._keys = [];
  17158. this._onKeyDown = null;
  17159. this._onKeyUp = null;
  17160. this._onLostFocus = null;
  17161. };
  17162. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17163. if (this._onKeyDown) {
  17164. var camera = this.camera;
  17165. for (var index = 0; index < this._keys.length; index++) {
  17166. var keyCode = this._keys[index];
  17167. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17168. camera.inertialAlphaOffset -= 0.01;
  17169. }
  17170. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17171. camera.inertialBetaOffset -= 0.01;
  17172. }
  17173. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17174. camera.inertialAlphaOffset += 0.01;
  17175. }
  17176. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17177. camera.inertialBetaOffset += 0.01;
  17178. }
  17179. }
  17180. }
  17181. };
  17182. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17183. return "ArcRotateCameraKeyboardMoveInput";
  17184. };
  17185. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17186. return "keyboard";
  17187. };
  17188. return ArcRotateCameraKeyboardMoveInput;
  17189. }());
  17190. __decorate([
  17191. BABYLON.serialize()
  17192. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17193. __decorate([
  17194. BABYLON.serialize()
  17195. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17196. __decorate([
  17197. BABYLON.serialize()
  17198. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17199. __decorate([
  17200. BABYLON.serialize()
  17201. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17202. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17203. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17204. })(BABYLON || (BABYLON = {}));
  17205. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17206. var BABYLON;
  17207. (function (BABYLON) {
  17208. var ArcRotateCameraMouseWheelInput = (function () {
  17209. function ArcRotateCameraMouseWheelInput() {
  17210. this.wheelPrecision = 3.0;
  17211. }
  17212. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17213. var _this = this;
  17214. this._wheel = function (p, s) {
  17215. //sanity check - this should be a PointerWheel event.
  17216. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17217. return;
  17218. var event = p.event;
  17219. var delta = 0;
  17220. if (event.wheelDelta) {
  17221. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17222. }
  17223. else if (event.detail) {
  17224. delta = -event.detail / _this.wheelPrecision;
  17225. }
  17226. if (delta)
  17227. _this.camera.inertialRadiusOffset += delta;
  17228. if (event.preventDefault) {
  17229. if (!noPreventDefault) {
  17230. event.preventDefault();
  17231. }
  17232. }
  17233. };
  17234. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17235. };
  17236. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17237. if (this._observer && element) {
  17238. this.camera.getScene().onPointerObservable.remove(this._observer);
  17239. this._observer = null;
  17240. this._wheel = null;
  17241. }
  17242. };
  17243. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17244. return "ArcRotateCameraMouseWheelInput";
  17245. };
  17246. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17247. return "mousewheel";
  17248. };
  17249. return ArcRotateCameraMouseWheelInput;
  17250. }());
  17251. __decorate([
  17252. BABYLON.serialize()
  17253. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17254. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17255. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17256. })(BABYLON || (BABYLON = {}));
  17257. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17258. var BABYLON;
  17259. (function (BABYLON) {
  17260. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17261. var ArcRotateCameraPointersInput = (function () {
  17262. function ArcRotateCameraPointersInput() {
  17263. this.buttons = [0, 1, 2];
  17264. this.angularSensibilityX = 1000.0;
  17265. this.angularSensibilityY = 1000.0;
  17266. this.pinchPrecision = 6.0;
  17267. this.panningSensibility = 50.0;
  17268. this._isPanClick = false;
  17269. this.pinchInwards = true;
  17270. }
  17271. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17272. var _this = this;
  17273. var engine = this.camera.getEngine();
  17274. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17275. var pointA, pointB;
  17276. var previousPinchDistance = 0;
  17277. this._pointerInput = function (p, s) {
  17278. var evt = p.event;
  17279. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17280. return;
  17281. }
  17282. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17283. try {
  17284. evt.srcElement.setPointerCapture(evt.pointerId);
  17285. }
  17286. catch (e) {
  17287. //Nothing to do with the error. Execution will continue.
  17288. }
  17289. // Manage panning with pan button click
  17290. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17291. // manage pointers
  17292. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17293. if (pointA === undefined) {
  17294. pointA = cacheSoloPointer;
  17295. }
  17296. else if (pointB === undefined) {
  17297. pointB = cacheSoloPointer;
  17298. }
  17299. if (!noPreventDefault) {
  17300. evt.preventDefault();
  17301. element.focus();
  17302. }
  17303. }
  17304. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17305. try {
  17306. evt.srcElement.releasePointerCapture(evt.pointerId);
  17307. }
  17308. catch (e) {
  17309. //Nothing to do with the error.
  17310. }
  17311. cacheSoloPointer = null;
  17312. previousPinchDistance = 0;
  17313. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17314. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17315. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17316. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17317. pointA = pointB = undefined;
  17318. if (!noPreventDefault) {
  17319. evt.preventDefault();
  17320. }
  17321. }
  17322. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17323. if (!noPreventDefault) {
  17324. evt.preventDefault();
  17325. }
  17326. // One button down
  17327. if (pointA && pointB === undefined) {
  17328. if (_this.panningSensibility !== 0 &&
  17329. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17330. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17331. _this.camera
  17332. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17333. _this.camera
  17334. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17335. }
  17336. else {
  17337. var offsetX = evt.clientX - cacheSoloPointer.x;
  17338. var offsetY = evt.clientY - cacheSoloPointer.y;
  17339. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17340. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17341. }
  17342. cacheSoloPointer.x = evt.clientX;
  17343. cacheSoloPointer.y = evt.clientY;
  17344. }
  17345. else if (pointA && pointB) {
  17346. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17347. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17348. ed.x = evt.clientX;
  17349. ed.y = evt.clientY;
  17350. var direction = _this.pinchInwards ? 1 : -1;
  17351. var distX = pointA.x - pointB.x;
  17352. var distY = pointA.y - pointB.y;
  17353. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17354. if (previousPinchDistance === 0) {
  17355. previousPinchDistance = pinchSquaredDistance;
  17356. return;
  17357. }
  17358. if (pinchSquaredDistance !== previousPinchDistance) {
  17359. _this.camera
  17360. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17361. (_this.pinchPrecision *
  17362. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17363. direction);
  17364. previousPinchDistance = pinchSquaredDistance;
  17365. }
  17366. }
  17367. }
  17368. };
  17369. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17370. this._onContextMenu = function (evt) {
  17371. evt.preventDefault();
  17372. };
  17373. if (!this.camera._useCtrlForPanning) {
  17374. element.addEventListener("contextmenu", this._onContextMenu, false);
  17375. }
  17376. this._onLostFocus = function () {
  17377. //this._keys = [];
  17378. pointA = pointB = undefined;
  17379. previousPinchDistance = 0;
  17380. cacheSoloPointer = null;
  17381. };
  17382. this._onMouseMove = function (evt) {
  17383. if (!engine.isPointerLock) {
  17384. return;
  17385. }
  17386. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17387. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17388. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17389. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17390. if (!noPreventDefault) {
  17391. evt.preventDefault();
  17392. }
  17393. };
  17394. this._onGestureStart = function (e) {
  17395. if (window.MSGesture === undefined) {
  17396. return;
  17397. }
  17398. if (!_this._MSGestureHandler) {
  17399. _this._MSGestureHandler = new MSGesture();
  17400. _this._MSGestureHandler.target = element;
  17401. }
  17402. _this._MSGestureHandler.addPointer(e.pointerId);
  17403. };
  17404. this._onGesture = function (e) {
  17405. _this.camera.radius *= e.scale;
  17406. if (e.preventDefault) {
  17407. if (!noPreventDefault) {
  17408. e.stopPropagation();
  17409. e.preventDefault();
  17410. }
  17411. }
  17412. };
  17413. element.addEventListener("mousemove", this._onMouseMove, false);
  17414. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17415. element.addEventListener("MSGestureChange", this._onGesture, false);
  17416. element.addEventListener("keydown", this._onKeyDown, false);
  17417. element.addEventListener("keyup", this._onKeyUp, false);
  17418. BABYLON.Tools.RegisterTopRootEvents([
  17419. { name: "blur", handler: this._onLostFocus }
  17420. ]);
  17421. };
  17422. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17423. if (element && this._observer) {
  17424. this.camera.getScene().onPointerObservable.remove(this._observer);
  17425. this._observer = null;
  17426. element.removeEventListener("contextmenu", this._onContextMenu);
  17427. element.removeEventListener("mousemove", this._onMouseMove);
  17428. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17429. element.removeEventListener("MSGestureChange", this._onGesture);
  17430. element.removeEventListener("keydown", this._onKeyDown);
  17431. element.removeEventListener("keyup", this._onKeyUp);
  17432. this._isPanClick = false;
  17433. this.pinchInwards = true;
  17434. this._onKeyDown = null;
  17435. this._onKeyUp = null;
  17436. this._onMouseMove = null;
  17437. this._onGestureStart = null;
  17438. this._onGesture = null;
  17439. this._MSGestureHandler = null;
  17440. this._onLostFocus = null;
  17441. this._onContextMenu = null;
  17442. }
  17443. BABYLON.Tools.UnregisterTopRootEvents([
  17444. { name: "blur", handler: this._onLostFocus }
  17445. ]);
  17446. };
  17447. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17448. return "ArcRotateCameraPointersInput";
  17449. };
  17450. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17451. return "pointers";
  17452. };
  17453. return ArcRotateCameraPointersInput;
  17454. }());
  17455. __decorate([
  17456. BABYLON.serialize()
  17457. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17458. __decorate([
  17459. BABYLON.serialize()
  17460. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17461. __decorate([
  17462. BABYLON.serialize()
  17463. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17464. __decorate([
  17465. BABYLON.serialize()
  17466. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17467. __decorate([
  17468. BABYLON.serialize()
  17469. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17470. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17471. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17472. })(BABYLON || (BABYLON = {}));
  17473. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17474. var BABYLON;
  17475. (function (BABYLON) {
  17476. var ArcRotateCameraGamepadInput = (function () {
  17477. function ArcRotateCameraGamepadInput() {
  17478. this.gamepadRotationSensibility = 80;
  17479. this.gamepadMoveSensibility = 40;
  17480. }
  17481. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17482. var _this = this;
  17483. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17484. };
  17485. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17486. if (this._gamepads) {
  17487. this._gamepads.dispose();
  17488. }
  17489. this.gamepad = null;
  17490. };
  17491. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17492. if (this.gamepad) {
  17493. var camera = this.camera;
  17494. var RSValues = this.gamepad.rightStick;
  17495. if (RSValues.x != 0) {
  17496. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17497. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17498. camera.inertialAlphaOffset += normalizedRX;
  17499. }
  17500. }
  17501. if (RSValues.y != 0) {
  17502. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17503. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17504. camera.inertialBetaOffset += normalizedRY;
  17505. }
  17506. }
  17507. var LSValues = this.gamepad.leftStick;
  17508. if (LSValues.y != 0) {
  17509. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17510. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17511. this.camera.inertialRadiusOffset -= normalizedLY;
  17512. }
  17513. }
  17514. }
  17515. };
  17516. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17517. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17518. // prioritize XBOX gamepads.
  17519. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17520. this.gamepad = gamepad;
  17521. }
  17522. }
  17523. };
  17524. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17525. return "ArcRotateCameraGamepadInput";
  17526. };
  17527. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17528. return "gamepad";
  17529. };
  17530. return ArcRotateCameraGamepadInput;
  17531. }());
  17532. __decorate([
  17533. BABYLON.serialize()
  17534. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17535. __decorate([
  17536. BABYLON.serialize()
  17537. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17538. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17539. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17540. })(BABYLON || (BABYLON = {}));
  17541. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17542. var BABYLON;
  17543. (function (BABYLON) {
  17544. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17545. function ArcRotateCameraVRDeviceOrientationInput() {
  17546. this.alphaCorrection = 1;
  17547. this.betaCorrection = 1;
  17548. this.gammaCorrection = 1;
  17549. this._alpha = 0;
  17550. this._beta = 0;
  17551. this._gamma = 0;
  17552. this._dirty = false;
  17553. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17554. }
  17555. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17556. this.camera.attachControl(element, noPreventDefault);
  17557. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17558. };
  17559. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17560. var camera = this.camera;
  17561. this._alpha = +evt.alpha | 0;
  17562. this._beta = +evt.beta | 0;
  17563. this._gamma = +evt.gamma | 0;
  17564. this._dirty = true;
  17565. };
  17566. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17567. if (this._dirty) {
  17568. this._dirty = false;
  17569. if (this._gamma < 0) {
  17570. this._gamma = 180 + this._gamma;
  17571. }
  17572. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17573. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17574. }
  17575. };
  17576. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17577. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17578. };
  17579. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17580. return "ArcRotateCameraVRDeviceOrientationInput";
  17581. };
  17582. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17583. return "VRDeviceOrientation";
  17584. };
  17585. return ArcRotateCameraVRDeviceOrientationInput;
  17586. }());
  17587. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17588. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17589. })(BABYLON || (BABYLON = {}));
  17590. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17591. /// <reference path="babylon.camera.ts" />
  17592. var BABYLON;
  17593. (function (BABYLON) {
  17594. var TargetCamera = (function (_super) {
  17595. __extends(TargetCamera, _super);
  17596. function TargetCamera(name, position, scene) {
  17597. var _this = _super.call(this, name, position, scene) || this;
  17598. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17599. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17600. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17601. _this.speed = 2.0;
  17602. _this.noRotationConstraint = false;
  17603. _this.lockedTarget = null;
  17604. _this._currentTarget = BABYLON.Vector3.Zero();
  17605. _this._viewMatrix = BABYLON.Matrix.Zero();
  17606. _this._camMatrix = BABYLON.Matrix.Zero();
  17607. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17608. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17609. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17610. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17611. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17612. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17613. _this._tempMatrix = BABYLON.Matrix.Zero();
  17614. return _this;
  17615. }
  17616. TargetCamera.prototype.getFrontPosition = function (distance) {
  17617. var direction = this.getTarget().subtract(this.position);
  17618. direction.normalize();
  17619. direction.scaleInPlace(distance);
  17620. return this.globalPosition.add(direction);
  17621. };
  17622. TargetCamera.prototype._getLockedTargetPosition = function () {
  17623. if (!this.lockedTarget) {
  17624. return null;
  17625. }
  17626. if (this.lockedTarget.absolutePosition) {
  17627. this.lockedTarget.computeWorldMatrix();
  17628. }
  17629. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17630. };
  17631. // Cache
  17632. TargetCamera.prototype._initCache = function () {
  17633. _super.prototype._initCache.call(this);
  17634. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17635. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17636. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17637. };
  17638. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17639. if (!ignoreParentClass) {
  17640. _super.prototype._updateCache.call(this);
  17641. }
  17642. var lockedTargetPosition = this._getLockedTargetPosition();
  17643. if (!lockedTargetPosition) {
  17644. this._cache.lockedTarget = null;
  17645. }
  17646. else {
  17647. if (!this._cache.lockedTarget) {
  17648. this._cache.lockedTarget = lockedTargetPosition.clone();
  17649. }
  17650. else {
  17651. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17652. }
  17653. }
  17654. this._cache.rotation.copyFrom(this.rotation);
  17655. if (this.rotationQuaternion)
  17656. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17657. };
  17658. // Synchronized
  17659. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17660. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17661. return false;
  17662. }
  17663. var lockedTargetPosition = this._getLockedTargetPosition();
  17664. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17665. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17666. };
  17667. // Methods
  17668. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17669. var engine = this.getEngine();
  17670. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17671. };
  17672. // Target
  17673. TargetCamera.prototype.setTarget = function (target) {
  17674. this.upVector.normalize();
  17675. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17676. this._camMatrix.invert();
  17677. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17678. var vDir = target.subtract(this.position);
  17679. if (vDir.x >= 0.0) {
  17680. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17681. }
  17682. else {
  17683. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17684. }
  17685. this.rotation.z = 0;
  17686. if (isNaN(this.rotation.x)) {
  17687. this.rotation.x = 0;
  17688. }
  17689. if (isNaN(this.rotation.y)) {
  17690. this.rotation.y = 0;
  17691. }
  17692. if (isNaN(this.rotation.z)) {
  17693. this.rotation.z = 0;
  17694. }
  17695. if (this.rotationQuaternion) {
  17696. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17697. }
  17698. };
  17699. /**
  17700. * Return the current target position of the camera. This value is expressed in local space.
  17701. */
  17702. TargetCamera.prototype.getTarget = function () {
  17703. return this._currentTarget;
  17704. };
  17705. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17706. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17707. };
  17708. TargetCamera.prototype._updatePosition = function () {
  17709. if (this.parent) {
  17710. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17711. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17712. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17713. return;
  17714. }
  17715. this.position.addInPlace(this.cameraDirection);
  17716. };
  17717. TargetCamera.prototype._checkInputs = function () {
  17718. var needToMove = this._decideIfNeedsToMove();
  17719. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17720. // Move
  17721. if (needToMove) {
  17722. this._updatePosition();
  17723. }
  17724. // Rotate
  17725. if (needToRotate) {
  17726. this.rotation.x += this.cameraRotation.x;
  17727. this.rotation.y += this.cameraRotation.y;
  17728. //rotate, if quaternion is set and rotation was used
  17729. if (this.rotationQuaternion) {
  17730. var len = this.rotation.lengthSquared();
  17731. if (len) {
  17732. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17733. }
  17734. }
  17735. if (!this.noRotationConstraint) {
  17736. var limit = (Math.PI / 2) * 0.95;
  17737. if (this.rotation.x > limit)
  17738. this.rotation.x = limit;
  17739. if (this.rotation.x < -limit)
  17740. this.rotation.x = -limit;
  17741. }
  17742. }
  17743. // Inertia
  17744. if (needToMove) {
  17745. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17746. this.cameraDirection.x = 0;
  17747. }
  17748. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17749. this.cameraDirection.y = 0;
  17750. }
  17751. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17752. this.cameraDirection.z = 0;
  17753. }
  17754. this.cameraDirection.scaleInPlace(this.inertia);
  17755. }
  17756. if (needToRotate) {
  17757. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17758. this.cameraRotation.x = 0;
  17759. }
  17760. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17761. this.cameraRotation.y = 0;
  17762. }
  17763. this.cameraRotation.scaleInPlace(this.inertia);
  17764. }
  17765. _super.prototype._checkInputs.call(this);
  17766. };
  17767. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17768. if (this.rotationQuaternion) {
  17769. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17770. //update the up vector!
  17771. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17772. }
  17773. else {
  17774. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17775. }
  17776. };
  17777. TargetCamera.prototype._getViewMatrix = function () {
  17778. if (!this.lockedTarget) {
  17779. // Compute
  17780. this._updateCameraRotationMatrix();
  17781. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17782. // Computing target and final matrix
  17783. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17784. }
  17785. else {
  17786. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17787. }
  17788. if (this.getScene().useRightHandedSystem) {
  17789. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17790. }
  17791. else {
  17792. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17793. }
  17794. return this._viewMatrix;
  17795. };
  17796. /**
  17797. * @override
  17798. * Override Camera.createRigCamera
  17799. */
  17800. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17801. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17802. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17803. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17804. if (!this.rotationQuaternion) {
  17805. this.rotationQuaternion = new BABYLON.Quaternion();
  17806. }
  17807. rigCamera._cameraRigParams = {};
  17808. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17809. }
  17810. return rigCamera;
  17811. }
  17812. return null;
  17813. };
  17814. /**
  17815. * @override
  17816. * Override Camera._updateRigCameras
  17817. */
  17818. TargetCamera.prototype._updateRigCameras = function () {
  17819. var camLeft = this._rigCameras[0];
  17820. var camRight = this._rigCameras[1];
  17821. switch (this.cameraRigMode) {
  17822. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17823. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17824. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17825. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17826. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17827. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17828. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17829. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17830. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17831. camLeft.setTarget(this.getTarget());
  17832. camRight.setTarget(this.getTarget());
  17833. break;
  17834. case BABYLON.Camera.RIG_MODE_VR:
  17835. if (camLeft.rotationQuaternion) {
  17836. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17837. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17838. }
  17839. else {
  17840. camLeft.rotation.copyFrom(this.rotation);
  17841. camRight.rotation.copyFrom(this.rotation);
  17842. }
  17843. camLeft.position.copyFrom(this.position);
  17844. camRight.position.copyFrom(this.position);
  17845. break;
  17846. }
  17847. _super.prototype._updateRigCameras.call(this);
  17848. };
  17849. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17850. if (!this._rigCamTransformMatrix) {
  17851. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17852. }
  17853. var target = this.getTarget();
  17854. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17855. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17856. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17857. };
  17858. TargetCamera.prototype.getClassName = function () {
  17859. return "TargetCamera";
  17860. };
  17861. return TargetCamera;
  17862. }(BABYLON.Camera));
  17863. __decorate([
  17864. BABYLON.serializeAsVector3()
  17865. ], TargetCamera.prototype, "rotation", void 0);
  17866. __decorate([
  17867. BABYLON.serialize()
  17868. ], TargetCamera.prototype, "speed", void 0);
  17869. __decorate([
  17870. BABYLON.serializeAsMeshReference("lockedTargetId")
  17871. ], TargetCamera.prototype, "lockedTarget", void 0);
  17872. BABYLON.TargetCamera = TargetCamera;
  17873. })(BABYLON || (BABYLON = {}));
  17874. //# sourceMappingURL=babylon.targetCamera.js.map
  17875. var BABYLON;
  17876. (function (BABYLON) {
  17877. var FreeCamera = (function (_super) {
  17878. __extends(FreeCamera, _super);
  17879. function FreeCamera(name, position, scene) {
  17880. var _this = _super.call(this, name, position, scene) || this;
  17881. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17882. _this.checkCollisions = false;
  17883. _this.applyGravity = false;
  17884. _this._collider = new BABYLON.Collider();
  17885. _this._needMoveForGravity = false;
  17886. _this._oldPosition = BABYLON.Vector3.Zero();
  17887. _this._diffPosition = BABYLON.Vector3.Zero();
  17888. _this._newPosition = BABYLON.Vector3.Zero();
  17889. // Collisions
  17890. _this._collisionMask = -1;
  17891. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17892. if (collidedMesh === void 0) { collidedMesh = null; }
  17893. //TODO move this to the collision coordinator!
  17894. if (_this.getScene().workerCollisions)
  17895. newPosition.multiplyInPlace(_this._collider.radius);
  17896. var updatePosition = function (newPos) {
  17897. _this._newPosition.copyFrom(newPos);
  17898. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17899. var oldPosition = _this.position.clone();
  17900. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17901. _this.position.addInPlace(_this._diffPosition);
  17902. if (_this.onCollide && collidedMesh) {
  17903. _this.onCollide(collidedMesh);
  17904. }
  17905. }
  17906. };
  17907. updatePosition(newPosition);
  17908. };
  17909. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17910. _this.inputs.addKeyboard().addMouse();
  17911. return _this;
  17912. }
  17913. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17914. //-- begin properties for backward compatibility for inputs
  17915. get: function () {
  17916. var mouse = this.inputs.attached["mouse"];
  17917. if (mouse)
  17918. return mouse.angularSensibility;
  17919. },
  17920. set: function (value) {
  17921. var mouse = this.inputs.attached["mouse"];
  17922. if (mouse)
  17923. mouse.angularSensibility = value;
  17924. },
  17925. enumerable: true,
  17926. configurable: true
  17927. });
  17928. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17929. get: function () {
  17930. var keyboard = this.inputs.attached["keyboard"];
  17931. if (keyboard)
  17932. return keyboard.keysUp;
  17933. },
  17934. set: function (value) {
  17935. var keyboard = this.inputs.attached["keyboard"];
  17936. if (keyboard)
  17937. keyboard.keysUp = value;
  17938. },
  17939. enumerable: true,
  17940. configurable: true
  17941. });
  17942. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17943. get: function () {
  17944. var keyboard = this.inputs.attached["keyboard"];
  17945. if (keyboard)
  17946. return keyboard.keysDown;
  17947. },
  17948. set: function (value) {
  17949. var keyboard = this.inputs.attached["keyboard"];
  17950. if (keyboard)
  17951. keyboard.keysDown = value;
  17952. },
  17953. enumerable: true,
  17954. configurable: true
  17955. });
  17956. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17957. get: function () {
  17958. var keyboard = this.inputs.attached["keyboard"];
  17959. if (keyboard)
  17960. return keyboard.keysLeft;
  17961. },
  17962. set: function (value) {
  17963. var keyboard = this.inputs.attached["keyboard"];
  17964. if (keyboard)
  17965. keyboard.keysLeft = value;
  17966. },
  17967. enumerable: true,
  17968. configurable: true
  17969. });
  17970. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17971. get: function () {
  17972. var keyboard = this.inputs.attached["keyboard"];
  17973. if (keyboard)
  17974. return keyboard.keysRight;
  17975. },
  17976. set: function (value) {
  17977. var keyboard = this.inputs.attached["keyboard"];
  17978. if (keyboard)
  17979. keyboard.keysRight = value;
  17980. },
  17981. enumerable: true,
  17982. configurable: true
  17983. });
  17984. // Controls
  17985. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17986. this.inputs.attachElement(element, noPreventDefault);
  17987. };
  17988. FreeCamera.prototype.detachControl = function (element) {
  17989. this.inputs.detachElement(element);
  17990. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17991. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17992. };
  17993. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17994. get: function () {
  17995. return this._collisionMask;
  17996. },
  17997. set: function (mask) {
  17998. this._collisionMask = !isNaN(mask) ? mask : -1;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. FreeCamera.prototype._collideWithWorld = function (velocity) {
  18004. var globalPosition;
  18005. if (this.parent) {
  18006. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  18007. }
  18008. else {
  18009. globalPosition = this.position;
  18010. }
  18011. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  18012. this._collider.radius = this.ellipsoid;
  18013. this._collider.collisionMask = this._collisionMask;
  18014. //no need for clone, as long as gravity is not on.
  18015. var actualVelocity = velocity;
  18016. //add gravity to the velocity to prevent the dual-collision checking
  18017. if (this.applyGravity) {
  18018. //this prevents mending with cameraDirection, a global variable of the free camera class.
  18019. actualVelocity = velocity.add(this.getScene().gravity);
  18020. }
  18021. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18022. };
  18023. FreeCamera.prototype._checkInputs = function () {
  18024. if (!this._localDirection) {
  18025. this._localDirection = BABYLON.Vector3.Zero();
  18026. this._transformedDirection = BABYLON.Vector3.Zero();
  18027. }
  18028. this.inputs.checkInputs();
  18029. _super.prototype._checkInputs.call(this);
  18030. };
  18031. FreeCamera.prototype._decideIfNeedsToMove = function () {
  18032. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18033. };
  18034. FreeCamera.prototype._updatePosition = function () {
  18035. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  18036. this._collideWithWorld(this.cameraDirection);
  18037. }
  18038. else {
  18039. _super.prototype._updatePosition.call(this);
  18040. }
  18041. };
  18042. FreeCamera.prototype.dispose = function () {
  18043. this.inputs.clear();
  18044. _super.prototype.dispose.call(this);
  18045. };
  18046. FreeCamera.prototype.getClassName = function () {
  18047. return "FreeCamera";
  18048. };
  18049. return FreeCamera;
  18050. }(BABYLON.TargetCamera));
  18051. __decorate([
  18052. BABYLON.serializeAsVector3()
  18053. ], FreeCamera.prototype, "ellipsoid", void 0);
  18054. __decorate([
  18055. BABYLON.serialize()
  18056. ], FreeCamera.prototype, "checkCollisions", void 0);
  18057. __decorate([
  18058. BABYLON.serialize()
  18059. ], FreeCamera.prototype, "applyGravity", void 0);
  18060. BABYLON.FreeCamera = FreeCamera;
  18061. })(BABYLON || (BABYLON = {}));
  18062. //# sourceMappingURL=babylon.freeCamera.js.map
  18063. var BABYLON;
  18064. (function (BABYLON) {
  18065. var FreeCameraInputsManager = (function (_super) {
  18066. __extends(FreeCameraInputsManager, _super);
  18067. function FreeCameraInputsManager(camera) {
  18068. return _super.call(this, camera) || this;
  18069. }
  18070. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18071. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18072. return this;
  18073. };
  18074. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18075. if (touchEnabled === void 0) { touchEnabled = true; }
  18076. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18077. return this;
  18078. };
  18079. FreeCameraInputsManager.prototype.addGamepad = function () {
  18080. this.add(new BABYLON.FreeCameraGamepadInput());
  18081. return this;
  18082. };
  18083. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18084. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18085. return this;
  18086. };
  18087. FreeCameraInputsManager.prototype.addTouch = function () {
  18088. this.add(new BABYLON.FreeCameraTouchInput());
  18089. return this;
  18090. };
  18091. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18092. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18093. return this;
  18094. };
  18095. return FreeCameraInputsManager;
  18096. }(BABYLON.CameraInputsManager));
  18097. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18098. })(BABYLON || (BABYLON = {}));
  18099. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18100. /// <reference path="babylon.targetCamera.ts" />
  18101. var BABYLON;
  18102. (function (BABYLON) {
  18103. var FollowCamera = (function (_super) {
  18104. __extends(FollowCamera, _super);
  18105. function FollowCamera(name, position, scene, lockedTarget) {
  18106. var _this = _super.call(this, name, position, scene) || this;
  18107. _this.radius = 12;
  18108. _this.rotationOffset = 0;
  18109. _this.heightOffset = 4;
  18110. _this.cameraAcceleration = 0.05;
  18111. _this.maxCameraSpeed = 20;
  18112. _this.lockedTarget = lockedTarget;
  18113. return _this;
  18114. }
  18115. FollowCamera.prototype.getRadians = function (degrees) {
  18116. return degrees * Math.PI / 180;
  18117. };
  18118. FollowCamera.prototype.follow = function (cameraTarget) {
  18119. if (!cameraTarget)
  18120. return;
  18121. var yRotation;
  18122. if (cameraTarget.rotationQuaternion) {
  18123. var rotMatrix = new BABYLON.Matrix();
  18124. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18125. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18126. }
  18127. else {
  18128. yRotation = cameraTarget.rotation.y;
  18129. }
  18130. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18131. var targetPosition = cameraTarget.getAbsolutePosition();
  18132. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18133. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18134. var dx = targetX - this.position.x;
  18135. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18136. var dz = (targetZ) - this.position.z;
  18137. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18138. var vy = dy * this.cameraAcceleration;
  18139. var vz = dz * this.cameraAcceleration * 2;
  18140. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18141. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18142. }
  18143. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18144. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18145. }
  18146. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18147. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18148. }
  18149. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18150. this.setTarget(targetPosition);
  18151. };
  18152. FollowCamera.prototype._checkInputs = function () {
  18153. _super.prototype._checkInputs.call(this);
  18154. this.follow(this.lockedTarget);
  18155. };
  18156. FollowCamera.prototype.getClassName = function () {
  18157. return "FollowCamera";
  18158. };
  18159. return FollowCamera;
  18160. }(BABYLON.TargetCamera));
  18161. __decorate([
  18162. BABYLON.serialize()
  18163. ], FollowCamera.prototype, "radius", void 0);
  18164. __decorate([
  18165. BABYLON.serialize()
  18166. ], FollowCamera.prototype, "rotationOffset", void 0);
  18167. __decorate([
  18168. BABYLON.serialize()
  18169. ], FollowCamera.prototype, "heightOffset", void 0);
  18170. __decorate([
  18171. BABYLON.serialize()
  18172. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18173. __decorate([
  18174. BABYLON.serialize()
  18175. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18176. __decorate([
  18177. BABYLON.serializeAsMeshReference("lockedTargetId")
  18178. ], FollowCamera.prototype, "lockedTarget", void 0);
  18179. BABYLON.FollowCamera = FollowCamera;
  18180. var ArcFollowCamera = (function (_super) {
  18181. __extends(ArcFollowCamera, _super);
  18182. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18183. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18184. _this.alpha = alpha;
  18185. _this.beta = beta;
  18186. _this.radius = radius;
  18187. _this.target = target;
  18188. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18189. _this.follow();
  18190. return _this;
  18191. }
  18192. ArcFollowCamera.prototype.follow = function () {
  18193. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18194. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18195. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18196. var targetPosition = this.target.getAbsolutePosition();
  18197. this.position = targetPosition.add(this._cartesianCoordinates);
  18198. this.setTarget(targetPosition);
  18199. };
  18200. ArcFollowCamera.prototype._checkInputs = function () {
  18201. _super.prototype._checkInputs.call(this);
  18202. this.follow();
  18203. };
  18204. ArcFollowCamera.prototype.getClassName = function () {
  18205. return "ArcFollowCamera";
  18206. };
  18207. return ArcFollowCamera;
  18208. }(BABYLON.TargetCamera));
  18209. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18210. })(BABYLON || (BABYLON = {}));
  18211. //# sourceMappingURL=babylon.followCamera.js.map
  18212. /// <reference path="babylon.freeCamera.ts" />
  18213. var BABYLON;
  18214. (function (BABYLON) {
  18215. // We're mainly based on the logic defined into the FreeCamera code
  18216. var TouchCamera = (function (_super) {
  18217. __extends(TouchCamera, _super);
  18218. //-- end properties for backward compatibility for inputs
  18219. function TouchCamera(name, position, scene) {
  18220. var _this = _super.call(this, name, position, scene) || this;
  18221. _this.inputs.addTouch();
  18222. _this._setupInputs();
  18223. return _this;
  18224. }
  18225. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18226. //-- Begin properties for backward compatibility for inputs
  18227. get: function () {
  18228. var touch = this.inputs.attached["touch"];
  18229. if (touch)
  18230. return touch.touchAngularSensibility;
  18231. },
  18232. set: function (value) {
  18233. var touch = this.inputs.attached["touch"];
  18234. if (touch)
  18235. touch.touchAngularSensibility = value;
  18236. },
  18237. enumerable: true,
  18238. configurable: true
  18239. });
  18240. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18241. get: function () {
  18242. var touch = this.inputs.attached["touch"];
  18243. if (touch)
  18244. return touch.touchMoveSensibility;
  18245. },
  18246. set: function (value) {
  18247. var touch = this.inputs.attached["touch"];
  18248. if (touch)
  18249. touch.touchMoveSensibility = value;
  18250. },
  18251. enumerable: true,
  18252. configurable: true
  18253. });
  18254. TouchCamera.prototype.getClassName = function () {
  18255. return "TouchCamera";
  18256. };
  18257. TouchCamera.prototype._setupInputs = function () {
  18258. var mouse = this.inputs.attached["mouse"];
  18259. if (mouse) {
  18260. mouse.touchEnabled = false;
  18261. }
  18262. };
  18263. return TouchCamera;
  18264. }(BABYLON.FreeCamera));
  18265. BABYLON.TouchCamera = TouchCamera;
  18266. })(BABYLON || (BABYLON = {}));
  18267. //# sourceMappingURL=babylon.touchCamera.js.map
  18268. /// <reference path="babylon.targetCamera.ts" />
  18269. /// <reference path="..\Tools\babylon.tools.ts" />
  18270. var BABYLON;
  18271. (function (BABYLON) {
  18272. var ArcRotateCamera = (function (_super) {
  18273. __extends(ArcRotateCamera, _super);
  18274. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18275. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18276. _this.inertialAlphaOffset = 0;
  18277. _this.inertialBetaOffset = 0;
  18278. _this.inertialRadiusOffset = 0;
  18279. _this.lowerAlphaLimit = null;
  18280. _this.upperAlphaLimit = null;
  18281. _this.lowerBetaLimit = 0.01;
  18282. _this.upperBetaLimit = Math.PI;
  18283. _this.lowerRadiusLimit = null;
  18284. _this.upperRadiusLimit = null;
  18285. _this.inertialPanningX = 0;
  18286. _this.inertialPanningY = 0;
  18287. //-- end properties for backward compatibility for inputs
  18288. _this.zoomOnFactor = 1;
  18289. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18290. _this.allowUpsideDown = true;
  18291. _this._viewMatrix = new BABYLON.Matrix();
  18292. // Panning
  18293. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18294. _this.checkCollisions = false;
  18295. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18296. _this._collider = new BABYLON.Collider();
  18297. _this._previousPosition = BABYLON.Vector3.Zero();
  18298. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18299. _this._newPosition = BABYLON.Vector3.Zero();
  18300. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18301. if (collidedMesh === void 0) { collidedMesh = null; }
  18302. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18303. newPosition.multiplyInPlace(_this._collider.radius);
  18304. }
  18305. if (!collidedMesh) {
  18306. _this._previousPosition.copyFrom(_this.position);
  18307. }
  18308. else {
  18309. _this.setPosition(newPosition);
  18310. if (_this.onCollide) {
  18311. _this.onCollide(collidedMesh);
  18312. }
  18313. }
  18314. // Recompute because of constraints
  18315. var cosa = Math.cos(_this.alpha);
  18316. var sina = Math.sin(_this.alpha);
  18317. var cosb = Math.cos(_this.beta);
  18318. var sinb = Math.sin(_this.beta);
  18319. if (sinb === 0) {
  18320. sinb = 0.0001;
  18321. }
  18322. var target = _this._getTargetPosition();
  18323. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18324. _this.position.copyFrom(_this._newPosition);
  18325. var up = _this.upVector;
  18326. if (_this.allowUpsideDown && _this.beta < 0) {
  18327. up = up.clone();
  18328. up = up.negate();
  18329. }
  18330. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18331. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18332. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18333. _this._collisionTriggered = false;
  18334. };
  18335. if (!target) {
  18336. _this.target = BABYLON.Vector3.Zero();
  18337. }
  18338. else {
  18339. _this.target = target;
  18340. }
  18341. _this.alpha = alpha;
  18342. _this.beta = beta;
  18343. _this.radius = radius;
  18344. _this.getViewMatrix();
  18345. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18346. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18347. return _this;
  18348. }
  18349. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18350. //-- begin properties for backward compatibility for inputs
  18351. get: function () {
  18352. var pointers = this.inputs.attached["pointers"];
  18353. if (pointers)
  18354. return pointers.angularSensibilityX;
  18355. },
  18356. set: function (value) {
  18357. var pointers = this.inputs.attached["pointers"];
  18358. if (pointers) {
  18359. pointers.angularSensibilityX = value;
  18360. }
  18361. },
  18362. enumerable: true,
  18363. configurable: true
  18364. });
  18365. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18366. get: function () {
  18367. var pointers = this.inputs.attached["pointers"];
  18368. if (pointers)
  18369. return pointers.angularSensibilityY;
  18370. },
  18371. set: function (value) {
  18372. var pointers = this.inputs.attached["pointers"];
  18373. if (pointers) {
  18374. pointers.angularSensibilityY = value;
  18375. }
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18381. get: function () {
  18382. var pointers = this.inputs.attached["pointers"];
  18383. if (pointers)
  18384. return pointers.pinchPrecision;
  18385. },
  18386. set: function (value) {
  18387. var pointers = this.inputs.attached["pointers"];
  18388. if (pointers) {
  18389. pointers.pinchPrecision = value;
  18390. }
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18396. get: function () {
  18397. var pointers = this.inputs.attached["pointers"];
  18398. if (pointers)
  18399. return pointers.panningSensibility;
  18400. },
  18401. set: function (value) {
  18402. var pointers = this.inputs.attached["pointers"];
  18403. if (pointers) {
  18404. pointers.panningSensibility = value;
  18405. }
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18411. get: function () {
  18412. var keyboard = this.inputs.attached["keyboard"];
  18413. if (keyboard)
  18414. return keyboard.keysUp;
  18415. },
  18416. set: function (value) {
  18417. var keyboard = this.inputs.attached["keyboard"];
  18418. if (keyboard)
  18419. keyboard.keysUp = value;
  18420. },
  18421. enumerable: true,
  18422. configurable: true
  18423. });
  18424. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18425. get: function () {
  18426. var keyboard = this.inputs.attached["keyboard"];
  18427. if (keyboard)
  18428. return keyboard.keysDown;
  18429. },
  18430. set: function (value) {
  18431. var keyboard = this.inputs.attached["keyboard"];
  18432. if (keyboard)
  18433. keyboard.keysDown = value;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18439. get: function () {
  18440. var keyboard = this.inputs.attached["keyboard"];
  18441. if (keyboard)
  18442. return keyboard.keysLeft;
  18443. },
  18444. set: function (value) {
  18445. var keyboard = this.inputs.attached["keyboard"];
  18446. if (keyboard)
  18447. keyboard.keysLeft = value;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18453. get: function () {
  18454. var keyboard = this.inputs.attached["keyboard"];
  18455. if (keyboard)
  18456. return keyboard.keysRight;
  18457. },
  18458. set: function (value) {
  18459. var keyboard = this.inputs.attached["keyboard"];
  18460. if (keyboard)
  18461. keyboard.keysRight = value;
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18467. get: function () {
  18468. var mousewheel = this.inputs.attached["mousewheel"];
  18469. if (mousewheel)
  18470. return mousewheel.wheelPrecision;
  18471. },
  18472. set: function (value) {
  18473. var mousewheel = this.inputs.attached["mousewheel"];
  18474. if (mousewheel)
  18475. mousewheel.wheelPrecision = value;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. // Cache
  18481. ArcRotateCamera.prototype._initCache = function () {
  18482. _super.prototype._initCache.call(this);
  18483. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18484. this._cache.alpha = undefined;
  18485. this._cache.beta = undefined;
  18486. this._cache.radius = undefined;
  18487. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18488. };
  18489. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18490. if (!ignoreParentClass) {
  18491. _super.prototype._updateCache.call(this);
  18492. }
  18493. this._cache.target.copyFrom(this._getTargetPosition());
  18494. this._cache.alpha = this.alpha;
  18495. this._cache.beta = this.beta;
  18496. this._cache.radius = this.radius;
  18497. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18498. };
  18499. ArcRotateCamera.prototype._getTargetPosition = function () {
  18500. if (this.target.getAbsolutePosition) {
  18501. var pos = this.target.getAbsolutePosition();
  18502. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18503. }
  18504. return this.target;
  18505. };
  18506. // Synchronized
  18507. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18508. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18509. return false;
  18510. return this._cache.target.equals(this.target)
  18511. && this._cache.alpha === this.alpha
  18512. && this._cache.beta === this.beta
  18513. && this._cache.radius === this.radius
  18514. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18515. };
  18516. // Methods
  18517. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18518. var _this = this;
  18519. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18520. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18521. this._useCtrlForPanning = useCtrlForPanning;
  18522. this._panningMouseButton = panningMouseButton;
  18523. this.inputs.attachElement(element, noPreventDefault);
  18524. this._reset = function () {
  18525. _this.inertialAlphaOffset = 0;
  18526. _this.inertialBetaOffset = 0;
  18527. _this.inertialRadiusOffset = 0;
  18528. };
  18529. };
  18530. ArcRotateCamera.prototype.detachControl = function (element) {
  18531. this.inputs.detachElement(element);
  18532. if (this._reset) {
  18533. this._reset();
  18534. }
  18535. };
  18536. ArcRotateCamera.prototype._checkInputs = function () {
  18537. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18538. if (this._collisionTriggered) {
  18539. return;
  18540. }
  18541. this.inputs.checkInputs();
  18542. // Inertia
  18543. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18544. if (this.getScene().useRightHandedSystem) {
  18545. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18546. }
  18547. else {
  18548. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18549. }
  18550. this.beta += this.inertialBetaOffset;
  18551. this.radius -= this.inertialRadiusOffset;
  18552. this.inertialAlphaOffset *= this.inertia;
  18553. this.inertialBetaOffset *= this.inertia;
  18554. this.inertialRadiusOffset *= this.inertia;
  18555. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18556. this.inertialAlphaOffset = 0;
  18557. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18558. this.inertialBetaOffset = 0;
  18559. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18560. this.inertialRadiusOffset = 0;
  18561. }
  18562. // Panning inertia
  18563. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18564. if (!this._localDirection) {
  18565. this._localDirection = BABYLON.Vector3.Zero();
  18566. this._transformedDirection = BABYLON.Vector3.Zero();
  18567. }
  18568. this.inertialPanningX *= this.inertia;
  18569. this.inertialPanningY *= this.inertia;
  18570. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18571. this.inertialPanningX = 0;
  18572. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18573. this.inertialPanningY = 0;
  18574. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18575. this._localDirection.multiplyInPlace(this.panningAxis);
  18576. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18577. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18578. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18579. if (!this.panningAxis.y) {
  18580. this._transformedDirection.y = 0;
  18581. }
  18582. if (!this.target.getAbsolutePosition) {
  18583. this.target.addInPlace(this._transformedDirection);
  18584. }
  18585. }
  18586. // Limits
  18587. this._checkLimits();
  18588. _super.prototype._checkInputs.call(this);
  18589. };
  18590. ArcRotateCamera.prototype._checkLimits = function () {
  18591. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18592. if (this.allowUpsideDown && this.beta > Math.PI) {
  18593. this.beta = this.beta - (2 * Math.PI);
  18594. }
  18595. }
  18596. else {
  18597. if (this.beta < this.lowerBetaLimit) {
  18598. this.beta = this.lowerBetaLimit;
  18599. }
  18600. }
  18601. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18602. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18603. this.beta = this.beta + (2 * Math.PI);
  18604. }
  18605. }
  18606. else {
  18607. if (this.beta > this.upperBetaLimit) {
  18608. this.beta = this.upperBetaLimit;
  18609. }
  18610. }
  18611. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18612. this.alpha = this.lowerAlphaLimit;
  18613. }
  18614. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18615. this.alpha = this.upperAlphaLimit;
  18616. }
  18617. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18618. this.radius = this.lowerRadiusLimit;
  18619. }
  18620. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18621. this.radius = this.upperRadiusLimit;
  18622. }
  18623. };
  18624. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18625. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18626. this.radius = radiusv3.length();
  18627. // Alpha
  18628. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18629. if (radiusv3.z < 0) {
  18630. this.alpha = 2 * Math.PI - this.alpha;
  18631. }
  18632. // Beta
  18633. this.beta = Math.acos(radiusv3.y / this.radius);
  18634. this._checkLimits();
  18635. };
  18636. ArcRotateCamera.prototype.setPosition = function (position) {
  18637. if (this.position.equals(position)) {
  18638. return;
  18639. }
  18640. this.position.copyFrom(position);
  18641. this.rebuildAnglesAndRadius();
  18642. };
  18643. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18644. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18645. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18646. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18647. return;
  18648. }
  18649. if (toBoundingCenter && target.getBoundingInfo) {
  18650. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18651. }
  18652. else {
  18653. this._targetBoundingCenter = null;
  18654. }
  18655. this.target = target;
  18656. this.rebuildAnglesAndRadius();
  18657. };
  18658. ArcRotateCamera.prototype._getViewMatrix = function () {
  18659. // Compute
  18660. var cosa = Math.cos(this.alpha);
  18661. var sina = Math.sin(this.alpha);
  18662. var cosb = Math.cos(this.beta);
  18663. var sinb = Math.sin(this.beta);
  18664. if (sinb === 0) {
  18665. sinb = 0.0001;
  18666. }
  18667. var target = this._getTargetPosition();
  18668. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18669. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18670. this._collider.radius = this.collisionRadius;
  18671. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18672. this._collisionTriggered = true;
  18673. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18674. }
  18675. else {
  18676. this.position.copyFrom(this._newPosition);
  18677. var up = this.upVector;
  18678. if (this.allowUpsideDown && sinb < 0) {
  18679. up = up.clone();
  18680. up = up.negate();
  18681. }
  18682. if (this.getScene().useRightHandedSystem) {
  18683. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18684. }
  18685. else {
  18686. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18687. }
  18688. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18689. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18690. }
  18691. this._currentTarget = target;
  18692. return this._viewMatrix;
  18693. };
  18694. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18695. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18696. meshes = meshes || this.getScene().meshes;
  18697. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18698. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18699. this.radius = distance * this.zoomOnFactor;
  18700. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18701. };
  18702. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18703. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18704. var meshesOrMinMaxVector;
  18705. var distance;
  18706. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18707. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18708. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18709. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18710. }
  18711. else {
  18712. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18713. distance = meshesOrMinMaxVectorAndDistance.distance;
  18714. }
  18715. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18716. if (!doNotUpdateMaxZ) {
  18717. this.maxZ = distance * 2;
  18718. }
  18719. };
  18720. /**
  18721. * @override
  18722. * Override Camera.createRigCamera
  18723. */
  18724. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18725. var alphaShift;
  18726. switch (this.cameraRigMode) {
  18727. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18728. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18730. case BABYLON.Camera.RIG_MODE_VR:
  18731. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18732. break;
  18733. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18734. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18735. break;
  18736. }
  18737. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18738. rigCam._cameraRigParams = {};
  18739. return rigCam;
  18740. };
  18741. /**
  18742. * @override
  18743. * Override Camera._updateRigCameras
  18744. */
  18745. ArcRotateCamera.prototype._updateRigCameras = function () {
  18746. var camLeft = this._rigCameras[0];
  18747. var camRight = this._rigCameras[1];
  18748. camLeft.beta = camRight.beta = this.beta;
  18749. camLeft.radius = camRight.radius = this.radius;
  18750. switch (this.cameraRigMode) {
  18751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18754. case BABYLON.Camera.RIG_MODE_VR:
  18755. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18756. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18757. break;
  18758. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18759. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18760. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18761. break;
  18762. }
  18763. _super.prototype._updateRigCameras.call(this);
  18764. };
  18765. ArcRotateCamera.prototype.dispose = function () {
  18766. this.inputs.clear();
  18767. _super.prototype.dispose.call(this);
  18768. };
  18769. ArcRotateCamera.prototype.getClassName = function () {
  18770. return "ArcRotateCamera";
  18771. };
  18772. return ArcRotateCamera;
  18773. }(BABYLON.TargetCamera));
  18774. __decorate([
  18775. BABYLON.serialize()
  18776. ], ArcRotateCamera.prototype, "alpha", void 0);
  18777. __decorate([
  18778. BABYLON.serialize()
  18779. ], ArcRotateCamera.prototype, "beta", void 0);
  18780. __decorate([
  18781. BABYLON.serialize()
  18782. ], ArcRotateCamera.prototype, "radius", void 0);
  18783. __decorate([
  18784. BABYLON.serializeAsVector3()
  18785. ], ArcRotateCamera.prototype, "target", void 0);
  18786. __decorate([
  18787. BABYLON.serialize()
  18788. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18789. __decorate([
  18790. BABYLON.serialize()
  18791. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18792. __decorate([
  18793. BABYLON.serialize()
  18794. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18795. __decorate([
  18796. BABYLON.serialize()
  18797. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18798. __decorate([
  18799. BABYLON.serialize()
  18800. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18801. __decorate([
  18802. BABYLON.serialize()
  18803. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18804. __decorate([
  18805. BABYLON.serialize()
  18806. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18807. __decorate([
  18808. BABYLON.serialize()
  18809. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18810. __decorate([
  18811. BABYLON.serialize()
  18812. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18813. __decorate([
  18814. BABYLON.serialize()
  18815. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18816. __decorate([
  18817. BABYLON.serialize()
  18818. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18819. __decorate([
  18820. BABYLON.serialize()
  18821. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18822. __decorate([
  18823. BABYLON.serialize()
  18824. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18825. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18826. })(BABYLON || (BABYLON = {}));
  18827. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18828. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18829. var BABYLON;
  18830. (function (BABYLON) {
  18831. var ArcRotateCameraInputsManager = (function (_super) {
  18832. __extends(ArcRotateCameraInputsManager, _super);
  18833. function ArcRotateCameraInputsManager(camera) {
  18834. return _super.call(this, camera) || this;
  18835. }
  18836. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18837. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18838. return this;
  18839. };
  18840. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18841. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18842. return this;
  18843. };
  18844. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18845. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18846. return this;
  18847. };
  18848. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18849. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18850. return this;
  18851. };
  18852. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18853. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18854. return this;
  18855. };
  18856. return ArcRotateCameraInputsManager;
  18857. }(BABYLON.CameraInputsManager));
  18858. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18859. })(BABYLON || (BABYLON = {}));
  18860. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18861. var BABYLON;
  18862. (function (BABYLON) {
  18863. var RenderingManager = (function () {
  18864. function RenderingManager(scene) {
  18865. this._renderingGroups = new Array();
  18866. this._autoClearDepthStencil = {};
  18867. this._customOpaqueSortCompareFn = {};
  18868. this._customAlphaTestSortCompareFn = {};
  18869. this._customTransparentSortCompareFn = {};
  18870. this._renderinGroupInfo = null;
  18871. this._scene = scene;
  18872. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18873. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18874. }
  18875. }
  18876. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18877. if (depth === void 0) { depth = true; }
  18878. if (stencil === void 0) { stencil = true; }
  18879. if (this._depthStencilBufferAlreadyCleaned) {
  18880. return;
  18881. }
  18882. this._scene.getEngine().clear(null, false, depth, stencil);
  18883. this._depthStencilBufferAlreadyCleaned = true;
  18884. };
  18885. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18886. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18887. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18888. var info = null;
  18889. if (observable) {
  18890. if (!this._renderinGroupInfo) {
  18891. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18892. }
  18893. info = this._renderinGroupInfo;
  18894. info.scene = this._scene;
  18895. info.camera = this._scene.activeCamera;
  18896. }
  18897. // Dispatch sprites
  18898. if (renderSprites) {
  18899. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18900. var manager = this._scene.spriteManagers[index];
  18901. this.dispatchSprites(manager);
  18902. }
  18903. }
  18904. // Render
  18905. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18906. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18907. var renderingGroup = this._renderingGroups[index];
  18908. if (!renderingGroup && !observable)
  18909. continue;
  18910. this._currentIndex = index;
  18911. var renderingGroupMask = 0;
  18912. // Fire PRECLEAR stage
  18913. if (observable) {
  18914. renderingGroupMask = Math.pow(2, index);
  18915. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18916. info.renderingGroupId = index;
  18917. observable.notifyObservers(info, renderingGroupMask);
  18918. }
  18919. // Clear depth/stencil if needed
  18920. var autoClear = this._autoClearDepthStencil[index];
  18921. if (autoClear && autoClear.autoClear) {
  18922. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18923. }
  18924. if (observable) {
  18925. // Fire PREOPAQUE stage
  18926. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18927. observable.notifyObservers(info, renderingGroupMask);
  18928. // Fire PRETRANSPARENT stage
  18929. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18930. observable.notifyObservers(info, renderingGroupMask);
  18931. }
  18932. if (renderingGroup)
  18933. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18934. // Fire POSTTRANSPARENT stage
  18935. if (observable) {
  18936. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18937. observable.notifyObservers(info, renderingGroupMask);
  18938. }
  18939. }
  18940. };
  18941. RenderingManager.prototype.reset = function () {
  18942. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18943. var renderingGroup = this._renderingGroups[index];
  18944. if (renderingGroup) {
  18945. renderingGroup.prepare();
  18946. }
  18947. }
  18948. };
  18949. RenderingManager.prototype.dispose = function () {
  18950. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18951. var renderingGroup = this._renderingGroups[index];
  18952. if (renderingGroup) {
  18953. renderingGroup.dispose();
  18954. }
  18955. }
  18956. this._renderingGroups.length = 0;
  18957. };
  18958. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18959. if (!this._renderingGroups[renderingGroupId]) {
  18960. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18961. }
  18962. };
  18963. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18964. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18965. this._prepareRenderingGroup(renderingGroupId);
  18966. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18967. };
  18968. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18969. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18970. this._prepareRenderingGroup(renderingGroupId);
  18971. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18972. };
  18973. RenderingManager.prototype.dispatch = function (subMesh) {
  18974. var mesh = subMesh.getMesh();
  18975. var renderingGroupId = mesh.renderingGroupId || 0;
  18976. this._prepareRenderingGroup(renderingGroupId);
  18977. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18978. };
  18979. /**
  18980. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18981. * This allowed control for front to back rendering or reversly depending of the special needs.
  18982. *
  18983. * @param renderingGroupId The rendering group id corresponding to its index
  18984. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18985. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18986. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18987. */
  18988. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18989. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18990. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18991. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18992. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18993. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18994. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18995. if (this._renderingGroups[renderingGroupId]) {
  18996. var group = this._renderingGroups[renderingGroupId];
  18997. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18998. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18999. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19000. }
  19001. };
  19002. /**
  19003. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19004. *
  19005. * @param renderingGroupId The rendering group id corresponding to its index
  19006. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19007. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19008. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19009. */
  19010. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19011. if (depth === void 0) { depth = true; }
  19012. if (stencil === void 0) { stencil = true; }
  19013. this._autoClearDepthStencil[renderingGroupId] = {
  19014. autoClear: autoClearDepthStencil,
  19015. depth: depth,
  19016. stencil: stencil
  19017. };
  19018. };
  19019. return RenderingManager;
  19020. }());
  19021. /**
  19022. * The max id used for rendering groups (not included)
  19023. */
  19024. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19025. /**
  19026. * The min id used for rendering groups (included)
  19027. */
  19028. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19029. BABYLON.RenderingManager = RenderingManager;
  19030. })(BABYLON || (BABYLON = {}));
  19031. //# sourceMappingURL=babylon.renderingManager.js.map
  19032. var BABYLON;
  19033. (function (BABYLON) {
  19034. var RenderingGroup = (function () {
  19035. /**
  19036. * Creates a new rendering group.
  19037. * @param index The rendering group index
  19038. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19039. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19040. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19041. */
  19042. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19043. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19044. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19045. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19046. this.index = index;
  19047. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19048. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19049. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19050. this._particleSystems = new BABYLON.SmartArray(256);
  19051. this._spriteManagers = new BABYLON.SmartArray(256);
  19052. this._scene = scene;
  19053. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19054. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19055. this.transparentSortCompareFn = transparentSortCompareFn;
  19056. }
  19057. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19058. /**
  19059. * Set the opaque sort comparison function.
  19060. * If null the sub meshes will be render in the order they were created
  19061. */
  19062. set: function (value) {
  19063. this._opaqueSortCompareFn = value;
  19064. if (value) {
  19065. this._renderOpaque = this.renderOpaqueSorted;
  19066. }
  19067. else {
  19068. this._renderOpaque = RenderingGroup.renderUnsorted;
  19069. }
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19075. /**
  19076. * Set the alpha test sort comparison function.
  19077. * If null the sub meshes will be render in the order they were created
  19078. */
  19079. set: function (value) {
  19080. this._alphaTestSortCompareFn = value;
  19081. if (value) {
  19082. this._renderAlphaTest = this.renderAlphaTestSorted;
  19083. }
  19084. else {
  19085. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19086. }
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19092. /**
  19093. * Set the transparent sort comparison function.
  19094. * If null the sub meshes will be render in the order they were created
  19095. */
  19096. set: function (value) {
  19097. if (value) {
  19098. this._transparentSortCompareFn = value;
  19099. }
  19100. else {
  19101. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19102. }
  19103. this._renderTransparent = this.renderTransparentSorted;
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. /**
  19109. * Render all the sub meshes contained in the group.
  19110. * @param customRenderFunction Used to override the default render behaviour of the group.
  19111. * @returns true if rendered some submeshes.
  19112. */
  19113. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19114. if (customRenderFunction) {
  19115. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19116. return;
  19117. }
  19118. var engine = this._scene.getEngine();
  19119. // Opaque
  19120. if (this._opaqueSubMeshes.length !== 0) {
  19121. this._renderOpaque(this._opaqueSubMeshes);
  19122. }
  19123. // Alpha test
  19124. if (this._alphaTestSubMeshes.length !== 0) {
  19125. engine.setAlphaTesting(true);
  19126. this._renderAlphaTest(this._alphaTestSubMeshes);
  19127. engine.setAlphaTesting(false);
  19128. }
  19129. // Sprites
  19130. if (renderSprites) {
  19131. this._renderSprites();
  19132. }
  19133. // Particles
  19134. if (renderParticles) {
  19135. this._renderParticles(activeMeshes);
  19136. }
  19137. if (this.onBeforeTransparentRendering) {
  19138. this.onBeforeTransparentRendering();
  19139. }
  19140. // Transparent
  19141. if (this._transparentSubMeshes.length !== 0) {
  19142. this._renderTransparent(this._transparentSubMeshes);
  19143. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19144. }
  19145. };
  19146. /**
  19147. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19148. * @param subMeshes The submeshes to render
  19149. */
  19150. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19151. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19152. };
  19153. /**
  19154. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19155. * @param subMeshes The submeshes to render
  19156. */
  19157. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19158. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19159. };
  19160. /**
  19161. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19162. * @param subMeshes The submeshes to render
  19163. */
  19164. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19165. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19166. };
  19167. /**
  19168. * Renders the submeshes in a specified order.
  19169. * @param subMeshes The submeshes to sort before render
  19170. * @param sortCompareFn The comparison function use to sort
  19171. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19172. * @param transparent Specifies to activate blending if true
  19173. */
  19174. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19175. var subIndex = 0;
  19176. var subMesh;
  19177. for (; subIndex < subMeshes.length; subIndex++) {
  19178. subMesh = subMeshes.data[subIndex];
  19179. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19180. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19181. }
  19182. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19183. sortedArray.sort(sortCompareFn);
  19184. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19185. subMesh = sortedArray[subIndex];
  19186. subMesh.render(transparent);
  19187. }
  19188. };
  19189. /**
  19190. * Renders the submeshes in the order they were dispatched (no sort applied).
  19191. * @param subMeshes The submeshes to render
  19192. */
  19193. RenderingGroup.renderUnsorted = function (subMeshes) {
  19194. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19195. var submesh = subMeshes.data[subIndex];
  19196. submesh.render(false);
  19197. }
  19198. };
  19199. /**
  19200. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19201. * are rendered back to front if in the same alpha index.
  19202. *
  19203. * @param a The first submesh
  19204. * @param b The second submesh
  19205. * @returns The result of the comparison
  19206. */
  19207. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19208. // Alpha index first
  19209. if (a._alphaIndex > b._alphaIndex) {
  19210. return 1;
  19211. }
  19212. if (a._alphaIndex < b._alphaIndex) {
  19213. return -1;
  19214. }
  19215. // Then distance to camera
  19216. return RenderingGroup.backToFrontSortCompare(a, b);
  19217. };
  19218. /**
  19219. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19220. * are rendered back to front.
  19221. *
  19222. * @param a The first submesh
  19223. * @param b The second submesh
  19224. * @returns The result of the comparison
  19225. */
  19226. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19227. // Then distance to camera
  19228. if (a._distanceToCamera < b._distanceToCamera) {
  19229. return 1;
  19230. }
  19231. if (a._distanceToCamera > b._distanceToCamera) {
  19232. return -1;
  19233. }
  19234. return 0;
  19235. };
  19236. /**
  19237. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19238. * are rendered front to back (prevent overdraw).
  19239. *
  19240. * @param a The first submesh
  19241. * @param b The second submesh
  19242. * @returns The result of the comparison
  19243. */
  19244. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19245. // Then distance to camera
  19246. if (a._distanceToCamera < b._distanceToCamera) {
  19247. return -1;
  19248. }
  19249. if (a._distanceToCamera > b._distanceToCamera) {
  19250. return 1;
  19251. }
  19252. return 0;
  19253. };
  19254. /**
  19255. * Resets the different lists of submeshes to prepare a new frame.
  19256. */
  19257. RenderingGroup.prototype.prepare = function () {
  19258. this._opaqueSubMeshes.reset();
  19259. this._transparentSubMeshes.reset();
  19260. this._alphaTestSubMeshes.reset();
  19261. this._particleSystems.reset();
  19262. this._spriteManagers.reset();
  19263. };
  19264. RenderingGroup.prototype.dispose = function () {
  19265. this._opaqueSubMeshes.dispose();
  19266. this._transparentSubMeshes.dispose();
  19267. this._alphaTestSubMeshes.dispose();
  19268. this._particleSystems.dispose();
  19269. this._spriteManagers.dispose();
  19270. };
  19271. /**
  19272. * Inserts the submesh in its correct queue depending on its material.
  19273. * @param subMesh The submesh to dispatch
  19274. */
  19275. RenderingGroup.prototype.dispatch = function (subMesh) {
  19276. var material = subMesh.getMaterial();
  19277. var mesh = subMesh.getMesh();
  19278. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19279. this._transparentSubMeshes.push(subMesh);
  19280. }
  19281. else if (material.needAlphaTesting()) {
  19282. this._alphaTestSubMeshes.push(subMesh);
  19283. }
  19284. else {
  19285. this._opaqueSubMeshes.push(subMesh); // Opaque
  19286. }
  19287. };
  19288. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19289. this._spriteManagers.push(spriteManager);
  19290. };
  19291. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19292. this._particleSystems.push(particleSystem);
  19293. };
  19294. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19295. if (this._particleSystems.length === 0) {
  19296. return;
  19297. }
  19298. // Particles
  19299. var activeCamera = this._scene.activeCamera;
  19300. this._scene._particlesDuration.beginMonitoring();
  19301. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19302. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19303. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19304. continue;
  19305. }
  19306. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19307. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19308. }
  19309. }
  19310. this._scene._particlesDuration.endMonitoring(false);
  19311. };
  19312. RenderingGroup.prototype._renderSprites = function () {
  19313. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19314. return;
  19315. }
  19316. // Sprites
  19317. var activeCamera = this._scene.activeCamera;
  19318. this._scene._spritesDuration.beginMonitoring();
  19319. for (var id = 0; id < this._spriteManagers.length; id++) {
  19320. var spriteManager = this._spriteManagers.data[id];
  19321. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19322. spriteManager.render();
  19323. }
  19324. }
  19325. this._scene._spritesDuration.endMonitoring(false);
  19326. };
  19327. return RenderingGroup;
  19328. }());
  19329. BABYLON.RenderingGroup = RenderingGroup;
  19330. })(BABYLON || (BABYLON = {}));
  19331. //# sourceMappingURL=babylon.renderingGroup.js.map
  19332. var BABYLON;
  19333. (function (BABYLON) {
  19334. var ClickInfo = (function () {
  19335. function ClickInfo() {
  19336. this._singleClick = false;
  19337. this._doubleClick = false;
  19338. this._hasSwiped = false;
  19339. this._ignore = false;
  19340. }
  19341. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19342. get: function () {
  19343. return this._singleClick;
  19344. },
  19345. set: function (b) {
  19346. this._singleClick = b;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19352. get: function () {
  19353. return this._doubleClick;
  19354. },
  19355. set: function (b) {
  19356. this._doubleClick = b;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19362. get: function () {
  19363. return this._hasSwiped;
  19364. },
  19365. set: function (b) {
  19366. this._hasSwiped = b;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19372. get: function () {
  19373. return this._ignore;
  19374. },
  19375. set: function (b) {
  19376. this._ignore = b;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. return ClickInfo;
  19382. }());
  19383. var PointerEventTypes = (function () {
  19384. function PointerEventTypes() {
  19385. }
  19386. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19387. get: function () {
  19388. return PointerEventTypes._POINTERDOWN;
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19394. get: function () {
  19395. return PointerEventTypes._POINTERUP;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19401. get: function () {
  19402. return PointerEventTypes._POINTERMOVE;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19408. get: function () {
  19409. return PointerEventTypes._POINTERWHEEL;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19415. get: function () {
  19416. return PointerEventTypes._POINTERPICK;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19422. get: function () {
  19423. return PointerEventTypes._POINTERTAP;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19429. get: function () {
  19430. return PointerEventTypes._POINTERDOUBLETAP;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. return PointerEventTypes;
  19436. }());
  19437. PointerEventTypes._POINTERDOWN = 0x01;
  19438. PointerEventTypes._POINTERUP = 0x02;
  19439. PointerEventTypes._POINTERMOVE = 0x04;
  19440. PointerEventTypes._POINTERWHEEL = 0x08;
  19441. PointerEventTypes._POINTERPICK = 0x10;
  19442. PointerEventTypes._POINTERTAP = 0x20;
  19443. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19444. BABYLON.PointerEventTypes = PointerEventTypes;
  19445. var PointerInfoBase = (function () {
  19446. function PointerInfoBase(type, event) {
  19447. this.type = type;
  19448. this.event = event;
  19449. }
  19450. return PointerInfoBase;
  19451. }());
  19452. BABYLON.PointerInfoBase = PointerInfoBase;
  19453. /**
  19454. * This class is used to store pointer related info for the onPrePointerObservable event.
  19455. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19456. */
  19457. var PointerInfoPre = (function (_super) {
  19458. __extends(PointerInfoPre, _super);
  19459. function PointerInfoPre(type, event, localX, localY) {
  19460. var _this = _super.call(this, type, event) || this;
  19461. _this.skipOnPointerObservable = false;
  19462. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19463. return _this;
  19464. }
  19465. return PointerInfoPre;
  19466. }(PointerInfoBase));
  19467. BABYLON.PointerInfoPre = PointerInfoPre;
  19468. /**
  19469. * This type contains all the data related to a pointer event in Babylon.js.
  19470. * 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.
  19471. */
  19472. var PointerInfo = (function (_super) {
  19473. __extends(PointerInfo, _super);
  19474. function PointerInfo(type, event, pickInfo) {
  19475. var _this = _super.call(this, type, event) || this;
  19476. _this.pickInfo = pickInfo;
  19477. return _this;
  19478. }
  19479. return PointerInfo;
  19480. }(PointerInfoBase));
  19481. BABYLON.PointerInfo = PointerInfo;
  19482. /**
  19483. * This class is used by the onRenderingGroupObservable
  19484. */
  19485. var RenderingGroupInfo = (function () {
  19486. function RenderingGroupInfo() {
  19487. }
  19488. return RenderingGroupInfo;
  19489. }());
  19490. /**
  19491. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19492. * This stage will be fired no matter what
  19493. */
  19494. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19495. /**
  19496. * Called before opaque object are rendered.
  19497. * This stage will be fired only if there's 3D Opaque content to render
  19498. */
  19499. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19500. /**
  19501. * Called after the opaque objects are rendered and before the transparent ones
  19502. * This stage will be fired only if there's 3D transparent content to render
  19503. */
  19504. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19505. /**
  19506. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19507. * This stage will be fired no matter what
  19508. */
  19509. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19510. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19511. /**
  19512. * Represents a scene to be rendered by the engine.
  19513. * @see http://doc.babylonjs.com/page.php?p=21911
  19514. */
  19515. var Scene = (function () {
  19516. /**
  19517. * @constructor
  19518. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19519. */
  19520. function Scene(engine) {
  19521. // Members
  19522. this.autoClear = true;
  19523. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19524. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19525. this.forceWireframe = false;
  19526. this.forcePointsCloud = false;
  19527. this.forceShowBoundingBoxes = false;
  19528. this.animationsEnabled = true;
  19529. this.constantlyUpdateMeshUnderPointer = false;
  19530. this.useRightHandedSystem = false;
  19531. this.hoverCursor = "pointer";
  19532. // Metadata
  19533. this.metadata = null;
  19534. // Events
  19535. /**
  19536. * An event triggered when the scene is disposed.
  19537. * @type {BABYLON.Observable}
  19538. */
  19539. this.onDisposeObservable = new BABYLON.Observable();
  19540. /**
  19541. * An event triggered before rendering the scene
  19542. * @type {BABYLON.Observable}
  19543. */
  19544. this.onBeforeRenderObservable = new BABYLON.Observable();
  19545. /**
  19546. * An event triggered after rendering the scene
  19547. * @type {BABYLON.Observable}
  19548. */
  19549. this.onAfterRenderObservable = new BABYLON.Observable();
  19550. /**
  19551. * An event triggered when the scene is ready
  19552. * @type {BABYLON.Observable}
  19553. */
  19554. this.onReadyObservable = new BABYLON.Observable();
  19555. /**
  19556. * An event triggered before rendering a camera
  19557. * @type {BABYLON.Observable}
  19558. */
  19559. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19560. /**
  19561. * An event triggered after rendering a camera
  19562. * @type {BABYLON.Observable}
  19563. */
  19564. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19565. /**
  19566. * An event triggered when a camera is created
  19567. * @type {BABYLON.Observable}
  19568. */
  19569. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19570. /**
  19571. * An event triggered when a camera is removed
  19572. * @type {BABYLON.Observable}
  19573. */
  19574. this.onCameraRemovedObservable = new BABYLON.Observable();
  19575. /**
  19576. * An event triggered when a light is created
  19577. * @type {BABYLON.Observable}
  19578. */
  19579. this.onNewLightAddedObservable = new BABYLON.Observable();
  19580. /**
  19581. * An event triggered when a light is removed
  19582. * @type {BABYLON.Observable}
  19583. */
  19584. this.onLightRemovedObservable = new BABYLON.Observable();
  19585. /**
  19586. * An event triggered when a geometry is created
  19587. * @type {BABYLON.Observable}
  19588. */
  19589. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19590. /**
  19591. * An event triggered when a geometry is removed
  19592. * @type {BABYLON.Observable}
  19593. */
  19594. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19595. /**
  19596. * An event triggered when a mesh is created
  19597. * @type {BABYLON.Observable}
  19598. */
  19599. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19600. /**
  19601. * An event triggered when a mesh is removed
  19602. * @type {BABYLON.Observable}
  19603. */
  19604. this.onMeshRemovedObservable = new BABYLON.Observable();
  19605. /**
  19606. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19607. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19608. * 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)
  19609. */
  19610. this.onRenderingGroupObservable = new BABYLON.Observable();
  19611. // Animations
  19612. this.animations = [];
  19613. /**
  19614. * 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).
  19615. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19616. */
  19617. this.onPrePointerObservable = new BABYLON.Observable();
  19618. /**
  19619. * Observable event triggered each time an input event is received from the rendering canvas
  19620. */
  19621. this.onPointerObservable = new BABYLON.Observable();
  19622. this._meshPickProceed = false;
  19623. this._previousHasSwiped = false;
  19624. this._currentPickResult = null;
  19625. this._previousPickResult = null;
  19626. this._isButtonPressed = false;
  19627. this._doubleClickOccured = false;
  19628. 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
  19629. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19630. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19631. this._startingPointerTime = 0;
  19632. this._previousStartingPointerTime = 0;
  19633. // Fog
  19634. /**
  19635. * is fog enabled on this scene.
  19636. * @type {boolean}
  19637. */
  19638. this.fogEnabled = true;
  19639. this.fogMode = Scene.FOGMODE_NONE;
  19640. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19641. this.fogDensity = 0.1;
  19642. this.fogStart = 0;
  19643. this.fogEnd = 1000.0;
  19644. // Lights
  19645. /**
  19646. * is shadow enabled on this scene.
  19647. * @type {boolean}
  19648. */
  19649. this.shadowsEnabled = true;
  19650. /**
  19651. * is light enabled on this scene.
  19652. * @type {boolean}
  19653. */
  19654. this.lightsEnabled = true;
  19655. /**
  19656. * All of the lights added to this scene.
  19657. * @see BABYLON.Light
  19658. * @type {BABYLON.Light[]}
  19659. */
  19660. this.lights = new Array();
  19661. // Cameras
  19662. /**
  19663. * All of the cameras added to this scene.
  19664. * @see BABYLON.Camera
  19665. * @type {BABYLON.Camera[]}
  19666. */
  19667. this.cameras = new Array();
  19668. this.activeCameras = new Array();
  19669. // Meshes
  19670. /**
  19671. * All of the (abstract) meshes added to this scene.
  19672. * @see BABYLON.AbstractMesh
  19673. * @type {BABYLON.AbstractMesh[]}
  19674. */
  19675. this.meshes = new Array();
  19676. // Geometries
  19677. this._geometries = new Array();
  19678. this.materials = new Array();
  19679. this.multiMaterials = new Array();
  19680. // Textures
  19681. this.texturesEnabled = true;
  19682. this.textures = new Array();
  19683. // Particles
  19684. this.particlesEnabled = true;
  19685. this.particleSystems = new Array();
  19686. // Sprites
  19687. this.spritesEnabled = true;
  19688. this.spriteManagers = new Array();
  19689. // Layers
  19690. this.layers = new Array();
  19691. this.highlightLayers = new Array();
  19692. // Skeletons
  19693. this.skeletonsEnabled = true;
  19694. this.skeletons = new Array();
  19695. // Lens flares
  19696. this.lensFlaresEnabled = true;
  19697. this.lensFlareSystems = new Array();
  19698. // Collisions
  19699. this.collisionsEnabled = true;
  19700. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19701. // Postprocesses
  19702. this.postProcessesEnabled = true;
  19703. // Customs render targets
  19704. this.renderTargetsEnabled = true;
  19705. this.dumpNextRenderTargets = false;
  19706. this.customRenderTargets = new Array();
  19707. // Imported meshes
  19708. this.importedMeshesFiles = new Array();
  19709. // Probes
  19710. this.probesEnabled = true;
  19711. this.reflectionProbes = new Array();
  19712. this._actionManagers = new Array();
  19713. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19714. // Procedural textures
  19715. this.proceduralTexturesEnabled = true;
  19716. this._proceduralTextures = new Array();
  19717. this.soundTracks = new Array();
  19718. this._audioEnabled = true;
  19719. this._headphone = false;
  19720. // Performance counters
  19721. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19722. this._totalLightsCounter = new BABYLON.PerfCounter();
  19723. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19724. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19725. this._totalVertices = new BABYLON.PerfCounter();
  19726. this._activeIndices = new BABYLON.PerfCounter();
  19727. this._activeParticles = new BABYLON.PerfCounter();
  19728. this._lastFrameDuration = new BABYLON.PerfCounter();
  19729. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19730. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19731. this._particlesDuration = new BABYLON.PerfCounter();
  19732. this._renderDuration = new BABYLON.PerfCounter();
  19733. this._spritesDuration = new BABYLON.PerfCounter();
  19734. this._activeBones = new BABYLON.PerfCounter();
  19735. this._animationTime = 0;
  19736. this.animationTimeScale = 1;
  19737. this._renderId = 0;
  19738. this._executeWhenReadyTimeoutId = -1;
  19739. this._intermediateRendering = false;
  19740. this._toBeDisposed = new BABYLON.SmartArray(256);
  19741. this._pendingData = []; //ANY
  19742. this._activeMeshes = new BABYLON.SmartArray(256);
  19743. this._processedMaterials = new BABYLON.SmartArray(256);
  19744. this._renderTargets = new BABYLON.SmartArray(256);
  19745. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19746. this._activeSkeletons = new BABYLON.SmartArray(32);
  19747. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19748. this._activeAnimatables = new Array();
  19749. this._transformMatrix = BABYLON.Matrix.Zero();
  19750. this._edgesRenderers = new BABYLON.SmartArray(16);
  19751. this._uniqueIdCounter = 0;
  19752. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19753. this._engine.scenes.push(this);
  19754. this._externalData = new BABYLON.StringDictionary();
  19755. this._uid = null;
  19756. this._renderingManager = new BABYLON.RenderingManager(this);
  19757. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19758. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19759. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19760. if (BABYLON.OutlineRenderer) {
  19761. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19762. }
  19763. this.attachControl();
  19764. if (BABYLON.SoundTrack) {
  19765. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19766. }
  19767. //simplification queue
  19768. if (BABYLON.SimplificationQueue) {
  19769. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19770. }
  19771. //collision coordinator initialization. For now legacy per default.
  19772. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19773. }
  19774. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19775. get: function () {
  19776. return Scene._FOGMODE_NONE;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19782. get: function () {
  19783. return Scene._FOGMODE_EXP;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19789. get: function () {
  19790. return Scene._FOGMODE_EXP2;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19796. get: function () {
  19797. return Scene._FOGMODE_LINEAR;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(Scene.prototype, "onDispose", {
  19803. set: function (callback) {
  19804. if (this._onDisposeObserver) {
  19805. this.onDisposeObservable.remove(this._onDisposeObserver);
  19806. }
  19807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(Scene.prototype, "beforeRender", {
  19813. set: function (callback) {
  19814. if (this._onBeforeRenderObserver) {
  19815. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19816. }
  19817. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Scene.prototype, "afterRender", {
  19823. set: function (callback) {
  19824. if (this._onAfterRenderObserver) {
  19825. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19826. }
  19827. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19833. set: function (callback) {
  19834. if (this._onBeforeCameraRenderObserver) {
  19835. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19836. }
  19837. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19843. set: function (callback) {
  19844. if (this._onAfterCameraRenderObserver) {
  19845. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19846. }
  19847. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19853. get: function () {
  19854. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19860. get: function () {
  19861. if (!this._defaultMaterial) {
  19862. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19863. }
  19864. return this._defaultMaterial;
  19865. },
  19866. enumerable: true,
  19867. configurable: true
  19868. });
  19869. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19870. get: function () {
  19871. return this._frustumPlanes;
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(Scene.prototype, "debugLayer", {
  19877. // Properties
  19878. get: function () {
  19879. if (!this._debugLayer) {
  19880. this._debugLayer = new BABYLON.DebugLayer(this);
  19881. }
  19882. return this._debugLayer;
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19888. get: function () {
  19889. return this._workerCollisions;
  19890. },
  19891. set: function (enabled) {
  19892. enabled = (enabled && !!Worker);
  19893. this._workerCollisions = enabled;
  19894. if (this.collisionCoordinator) {
  19895. this.collisionCoordinator.destroy();
  19896. }
  19897. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19898. this.collisionCoordinator.init(this);
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19904. get: function () {
  19905. return this._selectionOctree;
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19911. /**
  19912. * The mesh that is currently under the pointer.
  19913. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19914. */
  19915. get: function () {
  19916. return this._pointerOverMesh;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(Scene.prototype, "pointerX", {
  19922. /**
  19923. * Current on-screen X position of the pointer
  19924. * @return {number} X position of the pointer
  19925. */
  19926. get: function () {
  19927. return this._pointerX;
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Object.defineProperty(Scene.prototype, "pointerY", {
  19933. /**
  19934. * Current on-screen Y position of the pointer
  19935. * @return {number} Y position of the pointer
  19936. */
  19937. get: function () {
  19938. return this._pointerY;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. Scene.prototype.getCachedMaterial = function () {
  19944. return this._cachedMaterial;
  19945. };
  19946. Scene.prototype.getBoundingBoxRenderer = function () {
  19947. return this._boundingBoxRenderer;
  19948. };
  19949. Scene.prototype.getOutlineRenderer = function () {
  19950. return this._outlineRenderer;
  19951. };
  19952. Scene.prototype.getEngine = function () {
  19953. return this._engine;
  19954. };
  19955. Scene.prototype.getTotalVertices = function () {
  19956. return this._totalVertices.current;
  19957. };
  19958. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19959. get: function () {
  19960. return this._totalVertices;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Scene.prototype.getActiveIndices = function () {
  19966. return this._activeIndices.current;
  19967. };
  19968. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19969. get: function () {
  19970. return this._activeIndices;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Scene.prototype.getActiveParticles = function () {
  19976. return this._activeParticles.current;
  19977. };
  19978. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19979. get: function () {
  19980. return this._activeParticles;
  19981. },
  19982. enumerable: true,
  19983. configurable: true
  19984. });
  19985. Scene.prototype.getActiveBones = function () {
  19986. return this._activeBones.current;
  19987. };
  19988. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19989. get: function () {
  19990. return this._activeBones;
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. // Stats
  19996. Scene.prototype.getLastFrameDuration = function () {
  19997. return this._lastFrameDuration.current;
  19998. };
  19999. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20000. get: function () {
  20001. return this._lastFrameDuration;
  20002. },
  20003. enumerable: true,
  20004. configurable: true
  20005. });
  20006. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20007. return this._evaluateActiveMeshesDuration.current;
  20008. };
  20009. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20010. get: function () {
  20011. return this._evaluateActiveMeshesDuration;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Scene.prototype.getActiveMeshes = function () {
  20017. return this._activeMeshes;
  20018. };
  20019. Scene.prototype.getRenderTargetsDuration = function () {
  20020. return this._renderTargetsDuration.current;
  20021. };
  20022. Scene.prototype.getRenderDuration = function () {
  20023. return this._renderDuration.current;
  20024. };
  20025. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20026. get: function () {
  20027. return this._renderDuration;
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Scene.prototype.getParticlesDuration = function () {
  20033. return this._particlesDuration.current;
  20034. };
  20035. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20036. get: function () {
  20037. return this._particlesDuration;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Scene.prototype.getSpritesDuration = function () {
  20043. return this._spritesDuration.current;
  20044. };
  20045. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20046. get: function () {
  20047. return this._spritesDuration;
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Scene.prototype.getAnimationRatio = function () {
  20053. return this._animationRatio;
  20054. };
  20055. Scene.prototype.getRenderId = function () {
  20056. return this._renderId;
  20057. };
  20058. Scene.prototype.incrementRenderId = function () {
  20059. this._renderId++;
  20060. };
  20061. Scene.prototype._updatePointerPosition = function (evt) {
  20062. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20063. this._pointerX = evt.clientX - canvasRect.left;
  20064. this._pointerY = evt.clientY - canvasRect.top;
  20065. this._unTranslatedPointerX = this._pointerX;
  20066. this._unTranslatedPointerY = this._pointerY;
  20067. if (this.cameraToUseForPointers) {
  20068. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  20069. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  20070. }
  20071. };
  20072. // Pointers handling
  20073. /**
  20074. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20075. * @param attachUp defines if you want to attach events to pointerup
  20076. * @param attachDown defines if you want to attach events to pointerdown
  20077. * @param attachMove defines if you want to attach events to pointermove
  20078. */
  20079. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20080. var _this = this;
  20081. if (attachUp === void 0) { attachUp = true; }
  20082. if (attachDown === void 0) { attachDown = true; }
  20083. if (attachMove === void 0) { attachMove = true; }
  20084. this._initActionManager = function (act, clickInfo) {
  20085. if (!_this._meshPickProceed) {
  20086. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20087. _this._currentPickResult = pickResult;
  20088. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20089. _this._meshPickProceed = true;
  20090. }
  20091. return act;
  20092. };
  20093. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20094. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20095. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20096. btn !== _this._previousButtonPressed) {
  20097. _this._doubleClickOccured = false;
  20098. clickInfo.singleClick = true;
  20099. clickInfo.ignore = false;
  20100. cb(clickInfo, _this._currentPickResult);
  20101. }
  20102. };
  20103. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20104. var clickInfo = new ClickInfo();
  20105. _this._currentPickResult = null;
  20106. var act;
  20107. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20108. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20109. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20110. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20111. act = _this._initActionManager(act, clickInfo);
  20112. if (act)
  20113. checkPicking = act.hasPickTriggers;
  20114. }
  20115. if (checkPicking) {
  20116. var btn = evt.button;
  20117. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20118. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20119. if (!clickInfo.hasSwiped) {
  20120. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20121. if (!checkSingleClickImmediately) {
  20122. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20123. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20124. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20125. act = _this._initActionManager(act, clickInfo);
  20126. if (act)
  20127. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20128. }
  20129. }
  20130. if (checkSingleClickImmediately) {
  20131. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20132. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20133. btn !== _this._previousButtonPressed) {
  20134. clickInfo.singleClick = true;
  20135. cb(clickInfo, _this._currentPickResult);
  20136. }
  20137. }
  20138. else {
  20139. // wait that no double click has been raised during the double click delay
  20140. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20141. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20142. }
  20143. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20144. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20145. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20146. act = _this._initActionManager(act, clickInfo);
  20147. if (act)
  20148. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20149. }
  20150. if (checkDoubleClick) {
  20151. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20152. if (btn === _this._previousButtonPressed &&
  20153. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20154. !_this._doubleClickOccured) {
  20155. // pointer has not moved for 2 clicks, it's a double click
  20156. if (!clickInfo.hasSwiped &&
  20157. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20158. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20159. _this._previousStartingPointerTime = 0;
  20160. _this._doubleClickOccured = true;
  20161. clickInfo.doubleClick = true;
  20162. clickInfo.ignore = false;
  20163. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20164. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20165. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20166. cb(clickInfo, _this._currentPickResult);
  20167. }
  20168. else {
  20169. _this._doubleClickOccured = false;
  20170. _this._previousStartingPointerTime = _this._startingPointerTime;
  20171. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20172. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20173. _this._previousButtonPressed = btn;
  20174. _this._previousHasSwiped = clickInfo.hasSwiped;
  20175. if (Scene.ExclusiveDoubleClickMode) {
  20176. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20177. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20178. }
  20179. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20180. cb(clickInfo, _this._previousPickResult);
  20181. }
  20182. else {
  20183. cb(clickInfo, _this._currentPickResult);
  20184. }
  20185. }
  20186. }
  20187. else {
  20188. _this._doubleClickOccured = false;
  20189. _this._previousStartingPointerTime = _this._startingPointerTime;
  20190. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20191. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20192. _this._previousButtonPressed = btn;
  20193. _this._previousHasSwiped = clickInfo.hasSwiped;
  20194. }
  20195. }
  20196. }
  20197. }
  20198. clickInfo.ignore = true;
  20199. cb(clickInfo, _this._currentPickResult);
  20200. };
  20201. var spritePredicate = function (sprite) {
  20202. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20203. };
  20204. this._onPointerMove = function (evt) {
  20205. _this._updatePointerPosition(evt);
  20206. // PreObservable support
  20207. if (_this.onPrePointerObservable.hasObservers()) {
  20208. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20209. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20210. _this.onPrePointerObservable.notifyObservers(pi, type);
  20211. if (pi.skipOnPointerObservable) {
  20212. return;
  20213. }
  20214. }
  20215. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20216. return;
  20217. }
  20218. var canvas = _this._engine.getRenderingCanvas();
  20219. if (!_this.pointerMovePredicate) {
  20220. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20221. }
  20222. // Meshes
  20223. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20224. if (pickResult.hit && pickResult.pickedMesh) {
  20225. _this.setPointerOverSprite(null);
  20226. _this.setPointerOverMesh(pickResult.pickedMesh);
  20227. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20228. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20229. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20230. }
  20231. else {
  20232. canvas.style.cursor = _this.hoverCursor;
  20233. }
  20234. }
  20235. else {
  20236. canvas.style.cursor = "";
  20237. }
  20238. }
  20239. else {
  20240. _this.setPointerOverMesh(null);
  20241. // Sprites
  20242. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20243. if (pickResult.hit && pickResult.pickedSprite) {
  20244. _this.setPointerOverSprite(pickResult.pickedSprite);
  20245. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20246. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20247. }
  20248. else {
  20249. canvas.style.cursor = _this.hoverCursor;
  20250. }
  20251. }
  20252. else {
  20253. _this.setPointerOverSprite(null);
  20254. // Restore pointer
  20255. canvas.style.cursor = "";
  20256. }
  20257. }
  20258. if (_this.onPointerMove) {
  20259. _this.onPointerMove(evt, pickResult);
  20260. }
  20261. if (_this.onPointerObservable.hasObservers()) {
  20262. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20263. var pi = new PointerInfo(type, evt, pickResult);
  20264. _this.onPointerObservable.notifyObservers(pi, type);
  20265. }
  20266. };
  20267. this._onPointerDown = function (evt) {
  20268. _this._isButtonPressed = true;
  20269. _this._pickedDownMesh = null;
  20270. _this._meshPickProceed = false;
  20271. _this._updatePointerPosition(evt);
  20272. // PreObservable support
  20273. if (_this.onPrePointerObservable.hasObservers()) {
  20274. var type = PointerEventTypes.POINTERDOWN;
  20275. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20276. _this.onPrePointerObservable.notifyObservers(pi, type);
  20277. if (pi.skipOnPointerObservable) {
  20278. return;
  20279. }
  20280. }
  20281. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20282. return;
  20283. }
  20284. _this._startingPointerPosition.x = _this._pointerX;
  20285. _this._startingPointerPosition.y = _this._pointerY;
  20286. _this._startingPointerTime = new Date().getTime();
  20287. if (!_this.pointerDownPredicate) {
  20288. _this.pointerDownPredicate = function (mesh) {
  20289. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20290. };
  20291. }
  20292. // Meshes
  20293. _this._pickedDownMesh = null;
  20294. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20295. if (pickResult.hit && pickResult.pickedMesh) {
  20296. _this._pickedDownMesh = pickResult.pickedMesh;
  20297. var actionManager = pickResult.pickedMesh.actionManager;
  20298. if (actionManager) {
  20299. if (actionManager.hasPickTriggers) {
  20300. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20301. switch (evt.button) {
  20302. case 0:
  20303. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20304. break;
  20305. case 1:
  20306. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20307. break;
  20308. case 2:
  20309. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20310. break;
  20311. }
  20312. }
  20313. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20314. window.setTimeout((function () {
  20315. var _this = this;
  20316. 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);
  20317. if (pickResult.hit && pickResult.pickedMesh) {
  20318. if (this._isButtonPressed &&
  20319. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20320. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20321. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20322. this._startingPointerTime = 0;
  20323. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20324. }
  20325. }
  20326. }).bind(_this), Scene.LongPressDelay);
  20327. }
  20328. }
  20329. }
  20330. if (_this.onPointerDown) {
  20331. _this.onPointerDown(evt, pickResult);
  20332. }
  20333. if (_this.onPointerObservable.hasObservers()) {
  20334. var type = PointerEventTypes.POINTERDOWN;
  20335. var pi = new PointerInfo(type, evt, pickResult);
  20336. _this.onPointerObservable.notifyObservers(pi, type);
  20337. }
  20338. // Sprites
  20339. _this._pickedDownSprite = null;
  20340. if (_this.spriteManagers.length > 0) {
  20341. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20342. if (pickResult.hit && pickResult.pickedSprite) {
  20343. if (pickResult.pickedSprite.actionManager) {
  20344. _this._pickedDownSprite = pickResult.pickedSprite;
  20345. switch (evt.button) {
  20346. case 0:
  20347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20348. break;
  20349. case 1:
  20350. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20351. break;
  20352. case 2:
  20353. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20354. break;
  20355. }
  20356. if (pickResult.pickedSprite.actionManager) {
  20357. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20358. }
  20359. }
  20360. }
  20361. }
  20362. };
  20363. this._onPointerUp = function (evt) {
  20364. _this._isButtonPressed = false;
  20365. _this._pickedUpMesh = null;
  20366. _this._meshPickProceed = false;
  20367. _this._updatePointerPosition(evt);
  20368. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20369. // PreObservable support
  20370. if (this.onPrePointerObservable.hasObservers()) {
  20371. if (!clickInfo.ignore) {
  20372. if (!clickInfo.hasSwiped) {
  20373. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20374. var type = PointerEventTypes.POINTERTAP;
  20375. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20376. this.onPrePointerObservable.notifyObservers(pi, type);
  20377. if (pi.skipOnPointerObservable) {
  20378. return;
  20379. }
  20380. }
  20381. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20382. var type = PointerEventTypes.POINTERDOUBLETAP;
  20383. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20384. this.onPrePointerObservable.notifyObservers(pi, type);
  20385. if (pi.skipOnPointerObservable) {
  20386. return;
  20387. }
  20388. }
  20389. }
  20390. }
  20391. else {
  20392. var type = PointerEventTypes.POINTERUP;
  20393. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20394. this.onPrePointerObservable.notifyObservers(pi, type);
  20395. if (pi.skipOnPointerObservable) {
  20396. return;
  20397. }
  20398. }
  20399. }
  20400. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20401. return;
  20402. }
  20403. if (!this.pointerUpPredicate) {
  20404. this.pointerUpPredicate = function (mesh) {
  20405. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20406. };
  20407. }
  20408. // Meshes
  20409. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  20410. this._initActionManager(null, clickInfo);
  20411. }
  20412. if (!pickResult) {
  20413. pickResult = this._currentPickResult;
  20414. }
  20415. if (pickResult && pickResult.pickedMesh) {
  20416. this._pickedUpMesh = pickResult.pickedMesh;
  20417. if (this._pickedDownMesh === this._pickedUpMesh) {
  20418. if (this.onPointerPick) {
  20419. this.onPointerPick(evt, pickResult);
  20420. }
  20421. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20422. var type = PointerEventTypes.POINTERPICK;
  20423. var pi = new PointerInfo(type, evt, pickResult);
  20424. this.onPointerObservable.notifyObservers(pi, type);
  20425. }
  20426. }
  20427. if (pickResult.pickedMesh.actionManager) {
  20428. if (clickInfo.ignore) {
  20429. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20430. }
  20431. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20433. }
  20434. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20436. }
  20437. }
  20438. }
  20439. if (this._pickedDownMesh &&
  20440. this._pickedDownMesh.actionManager &&
  20441. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20442. this._pickedDownMesh !== this._pickedUpMesh) {
  20443. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20444. }
  20445. if (this.onPointerUp) {
  20446. this.onPointerUp(evt, pickResult);
  20447. }
  20448. if (this.onPointerObservable.hasObservers()) {
  20449. if (!clickInfo.ignore) {
  20450. if (!clickInfo.hasSwiped) {
  20451. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20452. var type = PointerEventTypes.POINTERTAP;
  20453. var pi = new PointerInfo(type, evt, pickResult);
  20454. this.onPointerObservable.notifyObservers(pi, type);
  20455. }
  20456. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20457. var type = PointerEventTypes.POINTERDOUBLETAP;
  20458. var pi = new PointerInfo(type, evt, pickResult);
  20459. this.onPointerObservable.notifyObservers(pi, type);
  20460. }
  20461. }
  20462. }
  20463. else {
  20464. var type = PointerEventTypes.POINTERUP;
  20465. var pi = new PointerInfo(type, evt, pickResult);
  20466. this.onPointerObservable.notifyObservers(pi, type);
  20467. }
  20468. }
  20469. // Sprites
  20470. if (this.spriteManagers.length > 0) {
  20471. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20472. if (pickResult.hit && pickResult.pickedSprite) {
  20473. if (pickResult.pickedSprite.actionManager) {
  20474. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20475. if (pickResult.pickedSprite.actionManager) {
  20476. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20477. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20478. }
  20479. }
  20480. }
  20481. }
  20482. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20483. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20484. }
  20485. }
  20486. this._previousPickResult = this._currentPickResult;
  20487. }).bind(_this));
  20488. };
  20489. this._onKeyDown = function (evt) {
  20490. if (_this.actionManager) {
  20491. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20492. }
  20493. };
  20494. this._onKeyUp = function (evt) {
  20495. if (_this.actionManager) {
  20496. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20497. }
  20498. };
  20499. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20500. var canvas = this._engine.getRenderingCanvas();
  20501. if (attachMove) {
  20502. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20503. // Wheel
  20504. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20505. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20506. }
  20507. if (attachDown) {
  20508. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20509. }
  20510. if (attachUp) {
  20511. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20512. }
  20513. canvas.tabIndex = 1;
  20514. canvas.addEventListener("keydown", this._onKeyDown, false);
  20515. canvas.addEventListener("keyup", this._onKeyUp, false);
  20516. };
  20517. Scene.prototype.detachControl = function () {
  20518. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20519. var canvas = this._engine.getRenderingCanvas();
  20520. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20521. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20522. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20523. // Wheel
  20524. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20525. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20526. canvas.removeEventListener("keydown", this._onKeyDown);
  20527. canvas.removeEventListener("keyup", this._onKeyUp);
  20528. };
  20529. // Ready
  20530. Scene.prototype.isReady = function () {
  20531. if (this._pendingData.length > 0) {
  20532. return false;
  20533. }
  20534. var index;
  20535. for (index = 0; index < this._geometries.length; index++) {
  20536. var geometry = this._geometries[index];
  20537. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20538. return false;
  20539. }
  20540. }
  20541. for (index = 0; index < this.meshes.length; index++) {
  20542. var mesh = this.meshes[index];
  20543. if (!mesh.isEnabled()) {
  20544. continue;
  20545. }
  20546. if (!mesh.isReady()) {
  20547. return false;
  20548. }
  20549. var mat = mesh.material;
  20550. if (mat) {
  20551. if (!mat.isReady(mesh)) {
  20552. return false;
  20553. }
  20554. }
  20555. }
  20556. return true;
  20557. };
  20558. Scene.prototype.resetCachedMaterial = function () {
  20559. this._cachedMaterial = null;
  20560. };
  20561. Scene.prototype.registerBeforeRender = function (func) {
  20562. this.onBeforeRenderObservable.add(func);
  20563. };
  20564. Scene.prototype.unregisterBeforeRender = function (func) {
  20565. this.onBeforeRenderObservable.removeCallback(func);
  20566. };
  20567. Scene.prototype.registerAfterRender = function (func) {
  20568. this.onAfterRenderObservable.add(func);
  20569. };
  20570. Scene.prototype.unregisterAfterRender = function (func) {
  20571. this.onAfterRenderObservable.removeCallback(func);
  20572. };
  20573. Scene.prototype._addPendingData = function (data) {
  20574. this._pendingData.push(data);
  20575. };
  20576. Scene.prototype._removePendingData = function (data) {
  20577. var index = this._pendingData.indexOf(data);
  20578. if (index !== -1) {
  20579. this._pendingData.splice(index, 1);
  20580. }
  20581. };
  20582. Scene.prototype.getWaitingItemsCount = function () {
  20583. return this._pendingData.length;
  20584. };
  20585. /**
  20586. * Registers a function to be executed when the scene is ready.
  20587. * @param {Function} func - the function to be executed.
  20588. */
  20589. Scene.prototype.executeWhenReady = function (func) {
  20590. var _this = this;
  20591. this.onReadyObservable.add(func);
  20592. if (this._executeWhenReadyTimeoutId !== -1) {
  20593. return;
  20594. }
  20595. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20596. _this._checkIsReady();
  20597. }, 150);
  20598. };
  20599. Scene.prototype._checkIsReady = function () {
  20600. var _this = this;
  20601. if (this.isReady()) {
  20602. this.onReadyObservable.notifyObservers(this);
  20603. this.onReadyObservable.clear();
  20604. this._executeWhenReadyTimeoutId = -1;
  20605. return;
  20606. }
  20607. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20608. _this._checkIsReady();
  20609. }, 150);
  20610. };
  20611. // Animations
  20612. /**
  20613. * Will start the animation sequence of a given target
  20614. * @param target - the target
  20615. * @param {number} from - from which frame should animation start
  20616. * @param {number} to - till which frame should animation run.
  20617. * @param {boolean} [loop] - should the animation loop
  20618. * @param {number} [speedRatio] - the speed in which to run the animation
  20619. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20620. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20621. * @return {BABYLON.Animatable} the animatable object created for this animation
  20622. * @see BABYLON.Animatable
  20623. * @see http://doc.babylonjs.com/page.php?p=22081
  20624. */
  20625. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20626. if (speedRatio === void 0) { speedRatio = 1.0; }
  20627. this.stopAnimation(target);
  20628. if (!animatable) {
  20629. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20630. }
  20631. // Local animations
  20632. if (target.animations) {
  20633. animatable.appendAnimations(target, target.animations);
  20634. }
  20635. // Children animations
  20636. if (target.getAnimatables) {
  20637. var animatables = target.getAnimatables();
  20638. for (var index = 0; index < animatables.length; index++) {
  20639. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20640. }
  20641. }
  20642. animatable.reset();
  20643. return animatable;
  20644. };
  20645. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20646. if (speedRatio === undefined) {
  20647. speedRatio = 1.0;
  20648. }
  20649. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20650. return animatable;
  20651. };
  20652. Scene.prototype.getAnimatableByTarget = function (target) {
  20653. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20654. if (this._activeAnimatables[index].target === target) {
  20655. return this._activeAnimatables[index];
  20656. }
  20657. }
  20658. return null;
  20659. };
  20660. Object.defineProperty(Scene.prototype, "Animatables", {
  20661. get: function () {
  20662. return this._activeAnimatables;
  20663. },
  20664. enumerable: true,
  20665. configurable: true
  20666. });
  20667. /**
  20668. * Will stop the animation of the given target
  20669. * @param target - the target
  20670. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20671. * @see beginAnimation
  20672. */
  20673. Scene.prototype.stopAnimation = function (target, animationName) {
  20674. var animatable = this.getAnimatableByTarget(target);
  20675. if (animatable) {
  20676. animatable.stop(animationName);
  20677. }
  20678. };
  20679. Scene.prototype._animate = function () {
  20680. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20681. return;
  20682. }
  20683. // Getting time
  20684. var now = BABYLON.Tools.Now;
  20685. if (!this._animationTimeLast) {
  20686. if (this._pendingData.length > 0) {
  20687. return;
  20688. }
  20689. this._animationTimeLast = now;
  20690. }
  20691. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20692. this._animationTime += deltaTime;
  20693. this._animationTimeLast = now;
  20694. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20695. this._activeAnimatables[index]._animate(this._animationTime);
  20696. }
  20697. };
  20698. // Matrix
  20699. Scene.prototype.getViewMatrix = function () {
  20700. return this._viewMatrix;
  20701. };
  20702. Scene.prototype.getProjectionMatrix = function () {
  20703. return this._projectionMatrix;
  20704. };
  20705. Scene.prototype.getTransformMatrix = function () {
  20706. return this._transformMatrix;
  20707. };
  20708. Scene.prototype.setTransformMatrix = function (view, projection) {
  20709. this._viewMatrix = view;
  20710. this._projectionMatrix = projection;
  20711. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20712. // Update frustum
  20713. if (!this._frustumPlanes) {
  20714. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20715. }
  20716. else {
  20717. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20718. }
  20719. };
  20720. // Methods
  20721. Scene.prototype.addMesh = function (newMesh) {
  20722. newMesh.uniqueId = this._uniqueIdCounter++;
  20723. var position = this.meshes.push(newMesh);
  20724. //notify the collision coordinator
  20725. this.collisionCoordinator.onMeshAdded(newMesh);
  20726. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20727. };
  20728. Scene.prototype.removeMesh = function (toRemove) {
  20729. var index = this.meshes.indexOf(toRemove);
  20730. if (index !== -1) {
  20731. // Remove from the scene if mesh found
  20732. this.meshes.splice(index, 1);
  20733. }
  20734. //notify the collision coordinator
  20735. this.collisionCoordinator.onMeshRemoved(toRemove);
  20736. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20737. return index;
  20738. };
  20739. Scene.prototype.removeSkeleton = function (toRemove) {
  20740. var index = this.skeletons.indexOf(toRemove);
  20741. if (index !== -1) {
  20742. // Remove from the scene if mesh found
  20743. this.skeletons.splice(index, 1);
  20744. }
  20745. return index;
  20746. };
  20747. Scene.prototype.removeLight = function (toRemove) {
  20748. var index = this.lights.indexOf(toRemove);
  20749. if (index !== -1) {
  20750. // Remove from the scene if mesh found
  20751. this.lights.splice(index, 1);
  20752. }
  20753. this.onLightRemovedObservable.notifyObservers(toRemove);
  20754. return index;
  20755. };
  20756. Scene.prototype.removeCamera = function (toRemove) {
  20757. var index = this.cameras.indexOf(toRemove);
  20758. if (index !== -1) {
  20759. // Remove from the scene if mesh found
  20760. this.cameras.splice(index, 1);
  20761. }
  20762. // Remove from activeCameras
  20763. var index2 = this.activeCameras.indexOf(toRemove);
  20764. if (index2 !== -1) {
  20765. // Remove from the scene if mesh found
  20766. this.activeCameras.splice(index2, 1);
  20767. }
  20768. // Reset the activeCamera
  20769. if (this.activeCamera === toRemove) {
  20770. if (this.cameras.length > 0) {
  20771. this.activeCamera = this.cameras[0];
  20772. }
  20773. else {
  20774. this.activeCamera = null;
  20775. }
  20776. }
  20777. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20778. return index;
  20779. };
  20780. Scene.prototype.addLight = function (newLight) {
  20781. newLight.uniqueId = this._uniqueIdCounter++;
  20782. var position = this.lights.push(newLight);
  20783. this.onNewLightAddedObservable.notifyObservers(newLight);
  20784. };
  20785. Scene.prototype.addCamera = function (newCamera) {
  20786. newCamera.uniqueId = this._uniqueIdCounter++;
  20787. var position = this.cameras.push(newCamera);
  20788. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20789. };
  20790. /**
  20791. * Switch active camera
  20792. * @param {Camera} newCamera - new active camera
  20793. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20794. */
  20795. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20796. if (attachControl === void 0) { attachControl = true; }
  20797. var canvas = this._engine.getRenderingCanvas();
  20798. this.activeCamera.detachControl(canvas);
  20799. this.activeCamera = newCamera;
  20800. if (attachControl) {
  20801. newCamera.attachControl(canvas);
  20802. }
  20803. };
  20804. /**
  20805. * sets the active camera of the scene using its ID
  20806. * @param {string} id - the camera's ID
  20807. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20808. * @see activeCamera
  20809. */
  20810. Scene.prototype.setActiveCameraByID = function (id) {
  20811. var camera = this.getCameraByID(id);
  20812. if (camera) {
  20813. this.activeCamera = camera;
  20814. return camera;
  20815. }
  20816. return null;
  20817. };
  20818. /**
  20819. * sets the active camera of the scene using its name
  20820. * @param {string} name - the camera's name
  20821. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20822. * @see activeCamera
  20823. */
  20824. Scene.prototype.setActiveCameraByName = function (name) {
  20825. var camera = this.getCameraByName(name);
  20826. if (camera) {
  20827. this.activeCamera = camera;
  20828. return camera;
  20829. }
  20830. return null;
  20831. };
  20832. /**
  20833. * get a material using its id
  20834. * @param {string} the material's ID
  20835. * @return {BABYLON.Material|null} the material or null if none found.
  20836. */
  20837. Scene.prototype.getMaterialByID = function (id) {
  20838. for (var index = 0; index < this.materials.length; index++) {
  20839. if (this.materials[index].id === id) {
  20840. return this.materials[index];
  20841. }
  20842. }
  20843. return null;
  20844. };
  20845. /**
  20846. * get a material using its name
  20847. * @param {string} the material's name
  20848. * @return {BABYLON.Material|null} the material or null if none found.
  20849. */
  20850. Scene.prototype.getMaterialByName = function (name) {
  20851. for (var index = 0; index < this.materials.length; index++) {
  20852. if (this.materials[index].name === name) {
  20853. return this.materials[index];
  20854. }
  20855. }
  20856. return null;
  20857. };
  20858. Scene.prototype.getLensFlareSystemByName = function (name) {
  20859. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20860. if (this.lensFlareSystems[index].name === name) {
  20861. return this.lensFlareSystems[index];
  20862. }
  20863. }
  20864. return null;
  20865. };
  20866. Scene.prototype.getLensFlareSystemByID = function (id) {
  20867. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20868. if (this.lensFlareSystems[index].id === id) {
  20869. return this.lensFlareSystems[index];
  20870. }
  20871. }
  20872. return null;
  20873. };
  20874. Scene.prototype.getCameraByID = function (id) {
  20875. for (var index = 0; index < this.cameras.length; index++) {
  20876. if (this.cameras[index].id === id) {
  20877. return this.cameras[index];
  20878. }
  20879. }
  20880. return null;
  20881. };
  20882. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20883. for (var index = 0; index < this.cameras.length; index++) {
  20884. if (this.cameras[index].uniqueId === uniqueId) {
  20885. return this.cameras[index];
  20886. }
  20887. }
  20888. return null;
  20889. };
  20890. /**
  20891. * get a camera using its name
  20892. * @param {string} the camera's name
  20893. * @return {BABYLON.Camera|null} the camera or null if none found.
  20894. */
  20895. Scene.prototype.getCameraByName = function (name) {
  20896. for (var index = 0; index < this.cameras.length; index++) {
  20897. if (this.cameras[index].name === name) {
  20898. return this.cameras[index];
  20899. }
  20900. }
  20901. return null;
  20902. };
  20903. /**
  20904. * get a bone using its id
  20905. * @param {string} the bone's id
  20906. * @return {BABYLON.Bone|null} the bone or null if not found
  20907. */
  20908. Scene.prototype.getBoneByID = function (id) {
  20909. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20910. var skeleton = this.skeletons[skeletonIndex];
  20911. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20912. if (skeleton.bones[boneIndex].id === id) {
  20913. return skeleton.bones[boneIndex];
  20914. }
  20915. }
  20916. }
  20917. return null;
  20918. };
  20919. /**
  20920. * get a bone using its id
  20921. * @param {string} the bone's name
  20922. * @return {BABYLON.Bone|null} the bone or null if not found
  20923. */
  20924. Scene.prototype.getBoneByName = function (name) {
  20925. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20926. var skeleton = this.skeletons[skeletonIndex];
  20927. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20928. if (skeleton.bones[boneIndex].name === name) {
  20929. return skeleton.bones[boneIndex];
  20930. }
  20931. }
  20932. }
  20933. return null;
  20934. };
  20935. /**
  20936. * get a light node using its name
  20937. * @param {string} the light's name
  20938. * @return {BABYLON.Light|null} the light or null if none found.
  20939. */
  20940. Scene.prototype.getLightByName = function (name) {
  20941. for (var index = 0; index < this.lights.length; index++) {
  20942. if (this.lights[index].name === name) {
  20943. return this.lights[index];
  20944. }
  20945. }
  20946. return null;
  20947. };
  20948. /**
  20949. * get a light node using its ID
  20950. * @param {string} the light's id
  20951. * @return {BABYLON.Light|null} the light or null if none found.
  20952. */
  20953. Scene.prototype.getLightByID = function (id) {
  20954. for (var index = 0; index < this.lights.length; index++) {
  20955. if (this.lights[index].id === id) {
  20956. return this.lights[index];
  20957. }
  20958. }
  20959. return null;
  20960. };
  20961. /**
  20962. * get a light node using its scene-generated unique ID
  20963. * @param {number} the light's unique id
  20964. * @return {BABYLON.Light|null} the light or null if none found.
  20965. */
  20966. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20967. for (var index = 0; index < this.lights.length; index++) {
  20968. if (this.lights[index].uniqueId === uniqueId) {
  20969. return this.lights[index];
  20970. }
  20971. }
  20972. return null;
  20973. };
  20974. /**
  20975. * get a particle system by id
  20976. * @param id {number} the particle system id
  20977. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20978. */
  20979. Scene.prototype.getParticleSystemByID = function (id) {
  20980. for (var index = 0; index < this.particleSystems.length; index++) {
  20981. if (this.particleSystems[index].id === id) {
  20982. return this.particleSystems[index];
  20983. }
  20984. }
  20985. return null;
  20986. };
  20987. /**
  20988. * get a geometry using its ID
  20989. * @param {string} the geometry's id
  20990. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20991. */
  20992. Scene.prototype.getGeometryByID = function (id) {
  20993. for (var index = 0; index < this._geometries.length; index++) {
  20994. if (this._geometries[index].id === id) {
  20995. return this._geometries[index];
  20996. }
  20997. }
  20998. return null;
  20999. };
  21000. /**
  21001. * add a new geometry to this scene.
  21002. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21003. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21004. * @return {boolean} was the geometry added or not
  21005. */
  21006. Scene.prototype.pushGeometry = function (geometry, force) {
  21007. if (!force && this.getGeometryByID(geometry.id)) {
  21008. return false;
  21009. }
  21010. this._geometries.push(geometry);
  21011. //notify the collision coordinator
  21012. this.collisionCoordinator.onGeometryAdded(geometry);
  21013. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21014. return true;
  21015. };
  21016. /**
  21017. * Removes an existing geometry
  21018. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21019. * @return {boolean} was the geometry removed or not
  21020. */
  21021. Scene.prototype.removeGeometry = function (geometry) {
  21022. var index = this._geometries.indexOf(geometry);
  21023. if (index > -1) {
  21024. this._geometries.splice(index, 1);
  21025. //notify the collision coordinator
  21026. this.collisionCoordinator.onGeometryDeleted(geometry);
  21027. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21028. return true;
  21029. }
  21030. return false;
  21031. };
  21032. Scene.prototype.getGeometries = function () {
  21033. return this._geometries;
  21034. };
  21035. /**
  21036. * Get the first added mesh found of a given ID
  21037. * @param {string} id - the id to search for
  21038. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21039. */
  21040. Scene.prototype.getMeshByID = function (id) {
  21041. for (var index = 0; index < this.meshes.length; index++) {
  21042. if (this.meshes[index].id === id) {
  21043. return this.meshes[index];
  21044. }
  21045. }
  21046. return null;
  21047. };
  21048. Scene.prototype.getMeshesByID = function (id) {
  21049. return this.meshes.filter(function (m) {
  21050. return m.id === id;
  21051. });
  21052. };
  21053. /**
  21054. * Get a mesh with its auto-generated unique id
  21055. * @param {number} uniqueId - the unique id to search for
  21056. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21057. */
  21058. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21059. for (var index = 0; index < this.meshes.length; index++) {
  21060. if (this.meshes[index].uniqueId === uniqueId) {
  21061. return this.meshes[index];
  21062. }
  21063. }
  21064. return null;
  21065. };
  21066. /**
  21067. * Get a the last added mesh found of a given ID
  21068. * @param {string} id - the id to search for
  21069. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21070. */
  21071. Scene.prototype.getLastMeshByID = function (id) {
  21072. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21073. if (this.meshes[index].id === id) {
  21074. return this.meshes[index];
  21075. }
  21076. }
  21077. return null;
  21078. };
  21079. /**
  21080. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21081. * @param {string} id - the id to search for
  21082. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21083. */
  21084. Scene.prototype.getLastEntryByID = function (id) {
  21085. var index;
  21086. for (index = this.meshes.length - 1; index >= 0; index--) {
  21087. if (this.meshes[index].id === id) {
  21088. return this.meshes[index];
  21089. }
  21090. }
  21091. for (index = this.cameras.length - 1; index >= 0; index--) {
  21092. if (this.cameras[index].id === id) {
  21093. return this.cameras[index];
  21094. }
  21095. }
  21096. for (index = this.lights.length - 1; index >= 0; index--) {
  21097. if (this.lights[index].id === id) {
  21098. return this.lights[index];
  21099. }
  21100. }
  21101. return null;
  21102. };
  21103. Scene.prototype.getNodeByID = function (id) {
  21104. var mesh = this.getMeshByID(id);
  21105. if (mesh) {
  21106. return mesh;
  21107. }
  21108. var light = this.getLightByID(id);
  21109. if (light) {
  21110. return light;
  21111. }
  21112. var camera = this.getCameraByID(id);
  21113. if (camera) {
  21114. return camera;
  21115. }
  21116. var bone = this.getBoneByID(id);
  21117. return bone;
  21118. };
  21119. Scene.prototype.getNodeByName = function (name) {
  21120. var mesh = this.getMeshByName(name);
  21121. if (mesh) {
  21122. return mesh;
  21123. }
  21124. var light = this.getLightByName(name);
  21125. if (light) {
  21126. return light;
  21127. }
  21128. var camera = this.getCameraByName(name);
  21129. if (camera) {
  21130. return camera;
  21131. }
  21132. var bone = this.getBoneByName(name);
  21133. return bone;
  21134. };
  21135. Scene.prototype.getMeshByName = function (name) {
  21136. for (var index = 0; index < this.meshes.length; index++) {
  21137. if (this.meshes[index].name === name) {
  21138. return this.meshes[index];
  21139. }
  21140. }
  21141. return null;
  21142. };
  21143. Scene.prototype.getSoundByName = function (name) {
  21144. var index;
  21145. if (BABYLON.AudioEngine) {
  21146. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21147. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21148. return this.mainSoundTrack.soundCollection[index];
  21149. }
  21150. }
  21151. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21152. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21153. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21154. return this.soundTracks[sdIndex].soundCollection[index];
  21155. }
  21156. }
  21157. }
  21158. }
  21159. return null;
  21160. };
  21161. Scene.prototype.getLastSkeletonByID = function (id) {
  21162. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21163. if (this.skeletons[index].id === id) {
  21164. return this.skeletons[index];
  21165. }
  21166. }
  21167. return null;
  21168. };
  21169. Scene.prototype.getSkeletonById = function (id) {
  21170. for (var index = 0; index < this.skeletons.length; index++) {
  21171. if (this.skeletons[index].id === id) {
  21172. return this.skeletons[index];
  21173. }
  21174. }
  21175. return null;
  21176. };
  21177. Scene.prototype.getSkeletonByName = function (name) {
  21178. for (var index = 0; index < this.skeletons.length; index++) {
  21179. if (this.skeletons[index].name === name) {
  21180. return this.skeletons[index];
  21181. }
  21182. }
  21183. return null;
  21184. };
  21185. Scene.prototype.isActiveMesh = function (mesh) {
  21186. return (this._activeMeshes.indexOf(mesh) !== -1);
  21187. };
  21188. /**
  21189. * Return a the first highlight layer of the scene with a given name.
  21190. * @param name The name of the highlight layer to look for.
  21191. * @return The highlight layer if found otherwise null.
  21192. */
  21193. Scene.prototype.getHighlightLayerByName = function (name) {
  21194. for (var index = 0; index < this.highlightLayers.length; index++) {
  21195. if (this.highlightLayers[index].name === name) {
  21196. return this.highlightLayers[index];
  21197. }
  21198. }
  21199. return null;
  21200. };
  21201. Object.defineProperty(Scene.prototype, "uid", {
  21202. /**
  21203. * Return a unique id as a string which can serve as an identifier for the scene
  21204. */
  21205. get: function () {
  21206. if (!this._uid) {
  21207. this._uid = BABYLON.Tools.RandomId();
  21208. }
  21209. return this._uid;
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. /**
  21215. * Add an externaly attached data from its key.
  21216. * This method call will fail and return false, if such key already exists.
  21217. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21218. * @param key the unique key that identifies the data
  21219. * @param data the data object to associate to the key for this Engine instance
  21220. * @return true if no such key were already present and the data was added successfully, false otherwise
  21221. */
  21222. Scene.prototype.addExternalData = function (key, data) {
  21223. return this._externalData.add(key, data);
  21224. };
  21225. /**
  21226. * Get an externaly attached data from its key
  21227. * @param key the unique key that identifies the data
  21228. * @return the associated data, if present (can be null), or undefined if not present
  21229. */
  21230. Scene.prototype.getExternalData = function (key) {
  21231. return this._externalData.get(key);
  21232. };
  21233. /**
  21234. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21235. * @param key the unique key that identifies the data
  21236. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21237. * @return the associated data, can be null if the factory returned null.
  21238. */
  21239. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21240. return this._externalData.getOrAddWithFactory(key, factory);
  21241. };
  21242. /**
  21243. * Remove an externaly attached data from the Engine instance
  21244. * @param key the unique key that identifies the data
  21245. * @return true if the data was successfully removed, false if it doesn't exist
  21246. */
  21247. Scene.prototype.removeExternalData = function (key) {
  21248. return this._externalData.remove(key);
  21249. };
  21250. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21251. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21252. var material = subMesh.getMaterial();
  21253. if (mesh.showSubMeshesBoundingBox) {
  21254. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21255. }
  21256. if (material) {
  21257. // Render targets
  21258. if (material.getRenderTargetTextures) {
  21259. if (this._processedMaterials.indexOf(material) === -1) {
  21260. this._processedMaterials.push(material);
  21261. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21262. }
  21263. }
  21264. // Dispatch
  21265. this._activeIndices.addCount(subMesh.indexCount, false);
  21266. this._renderingManager.dispatch(subMesh);
  21267. }
  21268. }
  21269. };
  21270. Scene.prototype._isInIntermediateRendering = function () {
  21271. return this._intermediateRendering;
  21272. };
  21273. Scene.prototype._evaluateActiveMeshes = function () {
  21274. this.activeCamera._activeMeshes.reset();
  21275. this._activeMeshes.reset();
  21276. this._renderingManager.reset();
  21277. this._processedMaterials.reset();
  21278. this._activeParticleSystems.reset();
  21279. this._activeSkeletons.reset();
  21280. this._softwareSkinnedMeshes.reset();
  21281. this._boundingBoxRenderer.reset();
  21282. this._edgesRenderers.reset();
  21283. // Meshes
  21284. var meshes;
  21285. var len;
  21286. if (this._selectionOctree) {
  21287. var selection = this._selectionOctree.select(this._frustumPlanes);
  21288. meshes = selection.data;
  21289. len = selection.length;
  21290. }
  21291. else {
  21292. len = this.meshes.length;
  21293. meshes = this.meshes;
  21294. }
  21295. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21296. var mesh = meshes[meshIndex];
  21297. if (mesh.isBlocked) {
  21298. continue;
  21299. }
  21300. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21301. if (!mesh.isReady() || !mesh.isEnabled()) {
  21302. continue;
  21303. }
  21304. mesh.computeWorldMatrix();
  21305. // Intersections
  21306. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21307. this._meshesForIntersections.pushNoDuplicate(mesh);
  21308. }
  21309. // Switch to current LOD
  21310. var meshLOD = mesh.getLOD(this.activeCamera);
  21311. if (!meshLOD) {
  21312. continue;
  21313. }
  21314. mesh._preActivate();
  21315. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21316. this._activeMeshes.push(mesh);
  21317. this.activeCamera._activeMeshes.push(mesh);
  21318. mesh._activate(this._renderId);
  21319. this._activeMesh(mesh, meshLOD);
  21320. }
  21321. }
  21322. // Particle systems
  21323. this._particlesDuration.beginMonitoring();
  21324. var beforeParticlesDate = BABYLON.Tools.Now;
  21325. if (this.particlesEnabled) {
  21326. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21327. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21328. var particleSystem = this.particleSystems[particleIndex];
  21329. if (!particleSystem.isStarted()) {
  21330. continue;
  21331. }
  21332. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21333. this._activeParticleSystems.push(particleSystem);
  21334. particleSystem.animate();
  21335. this._renderingManager.dispatchParticles(particleSystem);
  21336. }
  21337. }
  21338. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21339. }
  21340. this._particlesDuration.endMonitoring(false);
  21341. };
  21342. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21343. if (mesh.skeleton && this.skeletonsEnabled) {
  21344. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21345. mesh.skeleton.prepare();
  21346. }
  21347. if (!mesh.computeBonesUsingShaders) {
  21348. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21349. }
  21350. }
  21351. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21352. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21353. }
  21354. if (sourceMesh._edgesRenderer) {
  21355. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21356. }
  21357. if (mesh && mesh.subMeshes) {
  21358. // Submeshes Octrees
  21359. var len;
  21360. var subMeshes;
  21361. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21362. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21363. len = intersections.length;
  21364. subMeshes = intersections.data;
  21365. }
  21366. else {
  21367. subMeshes = mesh.subMeshes;
  21368. len = subMeshes.length;
  21369. }
  21370. for (var subIndex = 0; subIndex < len; subIndex++) {
  21371. var subMesh = subMeshes[subIndex];
  21372. this._evaluateSubMesh(subMesh, mesh);
  21373. }
  21374. }
  21375. };
  21376. Scene.prototype.updateTransformMatrix = function (force) {
  21377. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21378. };
  21379. Scene.prototype._renderForCamera = function (camera) {
  21380. var engine = this._engine;
  21381. var startTime = BABYLON.Tools.Now;
  21382. this.activeCamera = camera;
  21383. if (!this.activeCamera)
  21384. throw new Error("Active camera not set");
  21385. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21386. // Viewport
  21387. engine.setViewport(this.activeCamera.viewport);
  21388. // Camera
  21389. this.resetCachedMaterial();
  21390. this._renderId++;
  21391. this.updateTransformMatrix();
  21392. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21393. // Meshes
  21394. this._evaluateActiveMeshesDuration.beginMonitoring();
  21395. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21396. this._evaluateActiveMeshes();
  21397. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21398. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21399. // Software skinning
  21400. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21401. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21402. mesh.applySkeleton(mesh.skeleton);
  21403. }
  21404. // Render targets
  21405. this._renderTargetsDuration.beginMonitoring();
  21406. var needsRestoreFrameBuffer = false;
  21407. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21408. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21409. this._intermediateRendering = true;
  21410. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21411. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21412. var renderTarget = this._renderTargets.data[renderIndex];
  21413. if (renderTarget._shouldRender()) {
  21414. this._renderId++;
  21415. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21416. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21417. }
  21418. }
  21419. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21420. this._intermediateRendering = false;
  21421. this._renderId++;
  21422. needsRestoreFrameBuffer = true; // Restore back buffer
  21423. }
  21424. // Render HighlightLayer Texture
  21425. var stencilState = this._engine.getStencilBuffer();
  21426. var renderhighlights = false;
  21427. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21428. this._intermediateRendering = true;
  21429. for (var i = 0; i < this.highlightLayers.length; i++) {
  21430. var highlightLayer = this.highlightLayers[i];
  21431. if (highlightLayer.shouldRender() &&
  21432. (!highlightLayer.camera ||
  21433. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21434. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21435. renderhighlights = true;
  21436. var renderTarget = highlightLayer._mainTexture;
  21437. if (renderTarget._shouldRender()) {
  21438. this._renderId++;
  21439. renderTarget.render(false, false);
  21440. needsRestoreFrameBuffer = true;
  21441. }
  21442. }
  21443. }
  21444. this._intermediateRendering = false;
  21445. this._renderId++;
  21446. }
  21447. if (needsRestoreFrameBuffer) {
  21448. engine.restoreDefaultFramebuffer();
  21449. }
  21450. this._renderTargetsDuration.endMonitoring(false);
  21451. // Prepare Frame
  21452. this.postProcessManager._prepareFrame();
  21453. this._renderDuration.beginMonitoring();
  21454. // Backgrounds
  21455. var layerIndex;
  21456. var layer;
  21457. if (this.layers.length) {
  21458. engine.setDepthBuffer(false);
  21459. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21460. layer = this.layers[layerIndex];
  21461. if (layer.isBackground) {
  21462. layer.render();
  21463. }
  21464. }
  21465. engine.setDepthBuffer(true);
  21466. }
  21467. // Render
  21468. BABYLON.Tools.StartPerformanceCounter("Main render");
  21469. // Activate HighlightLayer stencil
  21470. if (renderhighlights) {
  21471. this._engine.setStencilBuffer(true);
  21472. }
  21473. this._renderingManager.render(null, null, true, true);
  21474. // Restore HighlightLayer stencil
  21475. if (renderhighlights) {
  21476. this._engine.setStencilBuffer(stencilState);
  21477. }
  21478. BABYLON.Tools.EndPerformanceCounter("Main render");
  21479. // Bounding boxes
  21480. this._boundingBoxRenderer.render();
  21481. // Edges
  21482. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21483. this._edgesRenderers.data[edgesRendererIndex].render();
  21484. }
  21485. // Lens flares
  21486. if (this.lensFlaresEnabled) {
  21487. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21488. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21489. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21490. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21491. lensFlareSystem.render();
  21492. }
  21493. }
  21494. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21495. }
  21496. // Foregrounds
  21497. if (this.layers.length) {
  21498. engine.setDepthBuffer(false);
  21499. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21500. layer = this.layers[layerIndex];
  21501. if (!layer.isBackground) {
  21502. layer.render();
  21503. }
  21504. }
  21505. engine.setDepthBuffer(true);
  21506. }
  21507. // Highlight Layer
  21508. if (renderhighlights) {
  21509. engine.setDepthBuffer(false);
  21510. for (var i = 0; i < this.highlightLayers.length; i++) {
  21511. if (this.highlightLayers[i].shouldRender()) {
  21512. this.highlightLayers[i].render();
  21513. }
  21514. }
  21515. engine.setDepthBuffer(true);
  21516. }
  21517. this._renderDuration.endMonitoring(false);
  21518. // Finalize frame
  21519. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21520. // Update camera
  21521. this.activeCamera._updateFromScene();
  21522. // Reset some special arrays
  21523. this._renderTargets.reset();
  21524. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21525. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21526. };
  21527. Scene.prototype._processSubCameras = function (camera) {
  21528. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21529. this._renderForCamera(camera);
  21530. return;
  21531. }
  21532. // rig cameras
  21533. for (var index = 0; index < camera._rigCameras.length; index++) {
  21534. this._renderForCamera(camera._rigCameras[index]);
  21535. }
  21536. this.activeCamera = camera;
  21537. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21538. // Update camera
  21539. this.activeCamera._updateFromScene();
  21540. };
  21541. Scene.prototype._checkIntersections = function () {
  21542. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21543. var sourceMesh = this._meshesForIntersections.data[index];
  21544. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21545. var action = sourceMesh.actionManager.actions[actionIndex];
  21546. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21547. var parameters = action.getTriggerParameter();
  21548. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21549. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21550. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21551. if (areIntersecting && currentIntersectionInProgress === -1) {
  21552. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21553. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21554. sourceMesh._intersectionsInProgress.push(otherMesh);
  21555. }
  21556. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21557. sourceMesh._intersectionsInProgress.push(otherMesh);
  21558. }
  21559. }
  21560. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21561. //They intersected, and now they don't.
  21562. //is this trigger an exit trigger? execute an event.
  21563. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21564. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21565. }
  21566. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21567. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21568. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21569. }
  21570. }
  21571. }
  21572. }
  21573. }
  21574. };
  21575. Scene.prototype.render = function () {
  21576. if (this.isDisposed) {
  21577. return;
  21578. }
  21579. this._lastFrameDuration.beginMonitoring();
  21580. this._particlesDuration.fetchNewFrame();
  21581. this._spritesDuration.fetchNewFrame();
  21582. this._activeParticles.fetchNewFrame();
  21583. this._renderDuration.fetchNewFrame();
  21584. this._renderTargetsDuration.fetchNewFrame();
  21585. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21586. this._totalVertices.fetchNewFrame();
  21587. this._activeIndices.fetchNewFrame();
  21588. this._activeBones.fetchNewFrame();
  21589. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21590. this._meshesForIntersections.reset();
  21591. this.resetCachedMaterial();
  21592. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21593. // Actions
  21594. if (this.actionManager) {
  21595. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21596. }
  21597. //Simplification Queue
  21598. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21599. this.simplificationQueue.executeNext();
  21600. }
  21601. // Animations
  21602. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21603. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21604. this._animate();
  21605. // Physics
  21606. if (this._physicsEngine) {
  21607. BABYLON.Tools.StartPerformanceCounter("Physics");
  21608. this._physicsEngine._step(deltaTime / 1000.0);
  21609. BABYLON.Tools.EndPerformanceCounter("Physics");
  21610. }
  21611. // Before render
  21612. this.onBeforeRenderObservable.notifyObservers(this);
  21613. // Customs render targets
  21614. this._renderTargetsDuration.beginMonitoring();
  21615. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21616. var engine = this.getEngine();
  21617. var currentActiveCamera = this.activeCamera;
  21618. if (this.renderTargetsEnabled) {
  21619. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21620. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21621. var renderTarget = this.customRenderTargets[customIndex];
  21622. if (renderTarget._shouldRender()) {
  21623. this._renderId++;
  21624. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21625. if (!this.activeCamera)
  21626. throw new Error("Active camera not set");
  21627. // Viewport
  21628. engine.setViewport(this.activeCamera.viewport);
  21629. // Camera
  21630. this.updateTransformMatrix();
  21631. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21632. }
  21633. }
  21634. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21635. this._renderId++;
  21636. }
  21637. if (this.customRenderTargets.length > 0) {
  21638. engine.restoreDefaultFramebuffer();
  21639. }
  21640. this._renderTargetsDuration.endMonitoring();
  21641. this.activeCamera = currentActiveCamera;
  21642. // Procedural textures
  21643. if (this.proceduralTexturesEnabled) {
  21644. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21645. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21646. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21647. if (proceduralTexture._shouldRender()) {
  21648. proceduralTexture.render();
  21649. }
  21650. }
  21651. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21652. }
  21653. // Clear
  21654. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21655. // Shadows
  21656. if (this.shadowsEnabled) {
  21657. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21658. var light = this.lights[lightIndex];
  21659. var shadowGenerator = light.getShadowGenerator();
  21660. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21661. this._renderTargets.push(shadowGenerator.getShadowMap());
  21662. }
  21663. }
  21664. }
  21665. // Depth renderer
  21666. if (this._depthRenderer) {
  21667. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21668. }
  21669. // RenderPipeline
  21670. this.postProcessRenderPipelineManager.update();
  21671. // Multi-cameras?
  21672. if (this.activeCameras.length > 0) {
  21673. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21674. if (cameraIndex > 0) {
  21675. this._engine.clear(null, false, true, true);
  21676. }
  21677. this._processSubCameras(this.activeCameras[cameraIndex]);
  21678. }
  21679. }
  21680. else {
  21681. if (!this.activeCamera) {
  21682. throw new Error("No camera defined");
  21683. }
  21684. this._processSubCameras(this.activeCamera);
  21685. }
  21686. // Intersection checks
  21687. this._checkIntersections();
  21688. // Update the audio listener attached to the camera
  21689. if (BABYLON.AudioEngine) {
  21690. this._updateAudioParameters();
  21691. }
  21692. // After render
  21693. if (this.afterRender) {
  21694. this.afterRender();
  21695. }
  21696. this.onAfterRenderObservable.notifyObservers(this);
  21697. // Cleaning
  21698. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21699. this._toBeDisposed.data[index].dispose();
  21700. this._toBeDisposed[index] = null;
  21701. }
  21702. this._toBeDisposed.reset();
  21703. if (this.dumpNextRenderTargets) {
  21704. this.dumpNextRenderTargets = false;
  21705. }
  21706. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21707. this._lastFrameDuration.endMonitoring();
  21708. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21709. this._totalLightsCounter.addCount(this.lights.length, true);
  21710. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21711. this._totalTexturesCounter.addCount(this.textures.length, true);
  21712. this._activeBones.addCount(0, true);
  21713. this._activeIndices.addCount(0, true);
  21714. this._activeParticles.addCount(0, true);
  21715. };
  21716. Scene.prototype._updateAudioParameters = function () {
  21717. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21718. return;
  21719. }
  21720. var listeningCamera;
  21721. var audioEngine = BABYLON.Engine.audioEngine;
  21722. if (this.activeCameras.length > 0) {
  21723. listeningCamera = this.activeCameras[0];
  21724. }
  21725. else {
  21726. listeningCamera = this.activeCamera;
  21727. }
  21728. if (listeningCamera && audioEngine.canUseWebAudio) {
  21729. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21730. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21731. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21732. cameraDirection.normalize();
  21733. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21734. var i;
  21735. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21736. var sound = this.mainSoundTrack.soundCollection[i];
  21737. if (sound.useCustomAttenuation) {
  21738. sound.updateDistanceFromListener();
  21739. }
  21740. }
  21741. for (i = 0; i < this.soundTracks.length; i++) {
  21742. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21743. sound = this.soundTracks[i].soundCollection[j];
  21744. if (sound.useCustomAttenuation) {
  21745. sound.updateDistanceFromListener();
  21746. }
  21747. }
  21748. }
  21749. }
  21750. };
  21751. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21752. // Audio
  21753. get: function () {
  21754. return this._audioEnabled;
  21755. },
  21756. set: function (value) {
  21757. this._audioEnabled = value;
  21758. if (BABYLON.AudioEngine) {
  21759. if (this._audioEnabled) {
  21760. this._enableAudio();
  21761. }
  21762. else {
  21763. this._disableAudio();
  21764. }
  21765. }
  21766. },
  21767. enumerable: true,
  21768. configurable: true
  21769. });
  21770. Scene.prototype._disableAudio = function () {
  21771. var i;
  21772. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21773. this.mainSoundTrack.soundCollection[i].pause();
  21774. }
  21775. for (i = 0; i < this.soundTracks.length; i++) {
  21776. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21777. this.soundTracks[i].soundCollection[j].pause();
  21778. }
  21779. }
  21780. };
  21781. Scene.prototype._enableAudio = function () {
  21782. var i;
  21783. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21784. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21785. this.mainSoundTrack.soundCollection[i].play();
  21786. }
  21787. }
  21788. for (i = 0; i < this.soundTracks.length; i++) {
  21789. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21790. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21791. this.soundTracks[i].soundCollection[j].play();
  21792. }
  21793. }
  21794. }
  21795. };
  21796. Object.defineProperty(Scene.prototype, "headphone", {
  21797. get: function () {
  21798. return this._headphone;
  21799. },
  21800. set: function (value) {
  21801. this._headphone = value;
  21802. if (BABYLON.AudioEngine) {
  21803. if (this._headphone) {
  21804. this._switchAudioModeForHeadphones();
  21805. }
  21806. else {
  21807. this._switchAudioModeForNormalSpeakers();
  21808. }
  21809. }
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. Scene.prototype._switchAudioModeForHeadphones = function () {
  21815. this.mainSoundTrack.switchPanningModelToHRTF();
  21816. for (var i = 0; i < this.soundTracks.length; i++) {
  21817. this.soundTracks[i].switchPanningModelToHRTF();
  21818. }
  21819. };
  21820. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21821. this.mainSoundTrack.switchPanningModelToEqualPower();
  21822. for (var i = 0; i < this.soundTracks.length; i++) {
  21823. this.soundTracks[i].switchPanningModelToEqualPower();
  21824. }
  21825. };
  21826. Scene.prototype.enableDepthRenderer = function () {
  21827. if (this._depthRenderer) {
  21828. return this._depthRenderer;
  21829. }
  21830. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21831. return this._depthRenderer;
  21832. };
  21833. Scene.prototype.disableDepthRenderer = function () {
  21834. if (!this._depthRenderer) {
  21835. return;
  21836. }
  21837. this._depthRenderer.dispose();
  21838. this._depthRenderer = null;
  21839. };
  21840. Scene.prototype.freezeMaterials = function () {
  21841. for (var i = 0; i < this.materials.length; i++) {
  21842. this.materials[i].freeze();
  21843. }
  21844. };
  21845. Scene.prototype.unfreezeMaterials = function () {
  21846. for (var i = 0; i < this.materials.length; i++) {
  21847. this.materials[i].unfreeze();
  21848. }
  21849. };
  21850. Scene.prototype.dispose = function () {
  21851. this.beforeRender = null;
  21852. this.afterRender = null;
  21853. this.skeletons = [];
  21854. this._boundingBoxRenderer.dispose();
  21855. if (this._depthRenderer) {
  21856. this._depthRenderer.dispose();
  21857. }
  21858. // Smart arrays
  21859. if (this.activeCamera) {
  21860. this.activeCamera._activeMeshes.dispose();
  21861. this.activeCamera = null;
  21862. }
  21863. this._activeMeshes.dispose();
  21864. this._renderingManager.dispose();
  21865. this._processedMaterials.dispose();
  21866. this._activeParticleSystems.dispose();
  21867. this._activeSkeletons.dispose();
  21868. this._softwareSkinnedMeshes.dispose();
  21869. this._boundingBoxRenderer.dispose();
  21870. this._edgesRenderers.dispose();
  21871. this._meshesForIntersections.dispose();
  21872. this._toBeDisposed.dispose();
  21873. // Debug layer
  21874. if (this._debugLayer) {
  21875. this._debugLayer.hide();
  21876. }
  21877. // Events
  21878. this.onDisposeObservable.notifyObservers(this);
  21879. this.onDisposeObservable.clear();
  21880. this.onBeforeRenderObservable.clear();
  21881. this.onAfterRenderObservable.clear();
  21882. this.detachControl();
  21883. // Release sounds & sounds tracks
  21884. if (BABYLON.AudioEngine) {
  21885. this.disposeSounds();
  21886. }
  21887. // Detach cameras
  21888. var canvas = this._engine.getRenderingCanvas();
  21889. var index;
  21890. for (index = 0; index < this.cameras.length; index++) {
  21891. this.cameras[index].detachControl(canvas);
  21892. }
  21893. // Release lights
  21894. while (this.lights.length) {
  21895. this.lights[0].dispose();
  21896. }
  21897. // Release meshes
  21898. while (this.meshes.length) {
  21899. this.meshes[0].dispose(true);
  21900. }
  21901. // Release cameras
  21902. while (this.cameras.length) {
  21903. this.cameras[0].dispose();
  21904. }
  21905. // Release materials
  21906. while (this.materials.length) {
  21907. this.materials[0].dispose();
  21908. }
  21909. // Release particles
  21910. while (this.particleSystems.length) {
  21911. this.particleSystems[0].dispose();
  21912. }
  21913. // Release sprites
  21914. while (this.spriteManagers.length) {
  21915. this.spriteManagers[0].dispose();
  21916. }
  21917. // Release layers
  21918. while (this.layers.length) {
  21919. this.layers[0].dispose();
  21920. }
  21921. while (this.highlightLayers.length) {
  21922. this.highlightLayers[0].dispose();
  21923. }
  21924. // Release textures
  21925. while (this.textures.length) {
  21926. this.textures[0].dispose();
  21927. }
  21928. // Post-processes
  21929. this.postProcessManager.dispose();
  21930. // Physics
  21931. if (this._physicsEngine) {
  21932. this.disablePhysicsEngine();
  21933. }
  21934. // Remove from engine
  21935. index = this._engine.scenes.indexOf(this);
  21936. if (index > -1) {
  21937. this._engine.scenes.splice(index, 1);
  21938. }
  21939. this._engine.wipeCaches();
  21940. this._engine = null;
  21941. };
  21942. Object.defineProperty(Scene.prototype, "isDisposed", {
  21943. get: function () {
  21944. return !this._engine;
  21945. },
  21946. enumerable: true,
  21947. configurable: true
  21948. });
  21949. // Release sounds & sounds tracks
  21950. Scene.prototype.disposeSounds = function () {
  21951. this.mainSoundTrack.dispose();
  21952. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21953. this.soundTracks[scIndex].dispose();
  21954. }
  21955. };
  21956. // Octrees
  21957. Scene.prototype.getWorldExtends = function () {
  21958. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21959. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21960. for (var index = 0; index < this.meshes.length; index++) {
  21961. var mesh = this.meshes[index];
  21962. mesh.computeWorldMatrix(true);
  21963. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21964. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21965. BABYLON.Tools.CheckExtends(minBox, min, max);
  21966. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21967. }
  21968. return {
  21969. min: min,
  21970. max: max
  21971. };
  21972. };
  21973. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21974. if (maxCapacity === void 0) { maxCapacity = 64; }
  21975. if (maxDepth === void 0) { maxDepth = 2; }
  21976. if (!this._selectionOctree) {
  21977. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21978. }
  21979. var worldExtends = this.getWorldExtends();
  21980. // Update octree
  21981. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21982. return this._selectionOctree;
  21983. };
  21984. // Picking
  21985. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21986. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21987. var engine = this._engine;
  21988. if (!camera) {
  21989. if (!this.activeCamera)
  21990. throw new Error("Active camera not set");
  21991. camera = this.activeCamera;
  21992. }
  21993. var cameraViewport = camera.viewport;
  21994. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21995. // Moving coordinates to local viewport world
  21996. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21997. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21998. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21999. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  22000. };
  22001. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22002. var engine = this._engine;
  22003. if (!camera) {
  22004. if (!this.activeCamera)
  22005. throw new Error("Active camera not set");
  22006. camera = this.activeCamera;
  22007. }
  22008. var cameraViewport = camera.viewport;
  22009. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22010. var identity = BABYLON.Matrix.Identity();
  22011. // Moving coordinates to local viewport world
  22012. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22013. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22014. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22015. };
  22016. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22017. var pickingInfo = null;
  22018. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22019. var mesh = this.meshes[meshIndex];
  22020. if (predicate) {
  22021. if (!predicate(mesh)) {
  22022. continue;
  22023. }
  22024. }
  22025. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22026. continue;
  22027. }
  22028. var world = mesh.getWorldMatrix();
  22029. var ray = rayFunction(world);
  22030. var result = mesh.intersects(ray, fastCheck);
  22031. if (!result || !result.hit)
  22032. continue;
  22033. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22034. continue;
  22035. pickingInfo = result;
  22036. if (fastCheck) {
  22037. break;
  22038. }
  22039. }
  22040. return pickingInfo || new BABYLON.PickingInfo();
  22041. };
  22042. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22043. var pickingInfos = new Array();
  22044. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22045. var mesh = this.meshes[meshIndex];
  22046. if (predicate) {
  22047. if (!predicate(mesh)) {
  22048. continue;
  22049. }
  22050. }
  22051. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22052. continue;
  22053. }
  22054. var world = mesh.getWorldMatrix();
  22055. var ray = rayFunction(world);
  22056. var result = mesh.intersects(ray, false);
  22057. if (!result || !result.hit)
  22058. continue;
  22059. pickingInfos.push(result);
  22060. }
  22061. return pickingInfos;
  22062. };
  22063. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22064. var pickingInfo = null;
  22065. camera = camera || this.activeCamera;
  22066. if (this.spriteManagers.length > 0) {
  22067. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22068. var spriteManager = this.spriteManagers[spriteIndex];
  22069. if (!spriteManager.isPickable) {
  22070. continue;
  22071. }
  22072. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22073. if (!result || !result.hit)
  22074. continue;
  22075. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22076. continue;
  22077. pickingInfo = result;
  22078. if (fastCheck) {
  22079. break;
  22080. }
  22081. }
  22082. }
  22083. return pickingInfo || new BABYLON.PickingInfo();
  22084. };
  22085. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22086. /// <param name="x">X position on screen</param>
  22087. /// <param name="y">Y position on screen</param>
  22088. /// <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>
  22089. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22090. /// <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>
  22091. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22092. var _this = this;
  22093. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22094. };
  22095. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22096. /// <param name="x">X position on screen</param>
  22097. /// <param name="y">Y position on screen</param>
  22098. /// <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>
  22099. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22100. /// <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>
  22101. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22102. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22103. };
  22104. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22105. var _this = this;
  22106. return this._internalPick(function (world) {
  22107. if (!_this._pickWithRayInverseMatrix) {
  22108. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22109. }
  22110. world.invertToRef(_this._pickWithRayInverseMatrix);
  22111. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22112. }, predicate, fastCheck);
  22113. };
  22114. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22115. /// <param name="x">X position on screen</param>
  22116. /// <param name="y">Y position on screen</param>
  22117. /// <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>
  22118. /// <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>
  22119. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22120. var _this = this;
  22121. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22122. };
  22123. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22124. /// <param name="ray">Ray to use</param>
  22125. /// <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>
  22126. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22127. var _this = this;
  22128. return this._internalMultiPick(function (world) {
  22129. if (!_this._pickWithRayInverseMatrix) {
  22130. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22131. }
  22132. world.invertToRef(_this._pickWithRayInverseMatrix);
  22133. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22134. }, predicate);
  22135. };
  22136. Scene.prototype.setPointerOverMesh = function (mesh) {
  22137. if (this._pointerOverMesh === mesh) {
  22138. return;
  22139. }
  22140. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22141. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22142. }
  22143. this._pointerOverMesh = mesh;
  22144. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22145. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22146. }
  22147. };
  22148. Scene.prototype.getPointerOverMesh = function () {
  22149. return this._pointerOverMesh;
  22150. };
  22151. Scene.prototype.setPointerOverSprite = function (sprite) {
  22152. if (this._pointerOverSprite === sprite) {
  22153. return;
  22154. }
  22155. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22156. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22157. }
  22158. this._pointerOverSprite = sprite;
  22159. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22160. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22161. }
  22162. };
  22163. Scene.prototype.getPointerOverSprite = function () {
  22164. return this._pointerOverSprite;
  22165. };
  22166. // Physics
  22167. Scene.prototype.getPhysicsEngine = function () {
  22168. return this._physicsEngine;
  22169. };
  22170. /**
  22171. * Enables physics to the current scene
  22172. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22173. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22174. * @return {boolean} was the physics engine initialized
  22175. */
  22176. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22177. if (this._physicsEngine) {
  22178. return true;
  22179. }
  22180. try {
  22181. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22182. return true;
  22183. }
  22184. catch (e) {
  22185. BABYLON.Tools.Error(e.message);
  22186. return false;
  22187. }
  22188. };
  22189. Scene.prototype.disablePhysicsEngine = function () {
  22190. if (!this._physicsEngine) {
  22191. return;
  22192. }
  22193. this._physicsEngine.dispose();
  22194. this._physicsEngine = undefined;
  22195. };
  22196. Scene.prototype.isPhysicsEnabled = function () {
  22197. return this._physicsEngine !== undefined;
  22198. };
  22199. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22200. var mesh = compound.parts[0].mesh;
  22201. mesh.physicsImpostor.dispose();
  22202. mesh.physicsImpostor = null;
  22203. };
  22204. // Misc.
  22205. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22206. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22207. // Light
  22208. if (this.lights.length === 0) {
  22209. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22210. }
  22211. // Camera
  22212. if (!this.activeCamera) {
  22213. // Compute position
  22214. var worldExtends = this.getWorldExtends();
  22215. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22216. var camera;
  22217. if (createArcRotateCamera) {
  22218. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22219. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22220. camera.setTarget(worldCenter);
  22221. }
  22222. else {
  22223. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22224. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22225. camera.setTarget(worldCenter);
  22226. }
  22227. this.activeCamera = camera;
  22228. }
  22229. };
  22230. // Tags
  22231. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22232. if (tagsQuery === undefined) {
  22233. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22234. return list;
  22235. }
  22236. var listByTags = [];
  22237. forEach = forEach || (function (item) { return; });
  22238. for (var i in list) {
  22239. var item = list[i];
  22240. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22241. listByTags.push(item);
  22242. forEach(item);
  22243. }
  22244. }
  22245. return listByTags;
  22246. };
  22247. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22248. return this._getByTags(this.meshes, tagsQuery, forEach);
  22249. };
  22250. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22251. return this._getByTags(this.cameras, tagsQuery, forEach);
  22252. };
  22253. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22254. return this._getByTags(this.lights, tagsQuery, forEach);
  22255. };
  22256. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22257. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22258. };
  22259. /**
  22260. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22261. * This allowed control for front to back rendering or reversly depending of the special needs.
  22262. *
  22263. * @param renderingGroupId The rendering group id corresponding to its index
  22264. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22265. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22266. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22267. */
  22268. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22269. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22270. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22271. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22272. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22273. };
  22274. /**
  22275. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22276. *
  22277. * @param renderingGroupId The rendering group id corresponding to its index
  22278. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22279. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22280. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22281. */
  22282. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22283. if (depth === void 0) { depth = true; }
  22284. if (stencil === void 0) { stencil = true; }
  22285. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22286. };
  22287. return Scene;
  22288. }());
  22289. // Statics
  22290. Scene._FOGMODE_NONE = 0;
  22291. Scene._FOGMODE_EXP = 1;
  22292. Scene._FOGMODE_EXP2 = 2;
  22293. Scene._FOGMODE_LINEAR = 3;
  22294. Scene.MinDeltaTime = 1.0;
  22295. Scene.MaxDeltaTime = 1000.0;
  22296. Scene.DragMovementThreshold = 10; // in pixels
  22297. Scene.LongPressDelay = 500; // in milliseconds
  22298. Scene.DoubleClickDelay = 300; // in milliseconds
  22299. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22300. BABYLON.Scene = Scene;
  22301. })(BABYLON || (BABYLON = {}));
  22302. //# sourceMappingURL=babylon.scene.js.map
  22303. var BABYLON;
  22304. (function (BABYLON) {
  22305. var Buffer = (function () {
  22306. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22307. if (engine instanceof BABYLON.Mesh) {
  22308. this._engine = engine.getScene().getEngine();
  22309. }
  22310. else {
  22311. this._engine = engine;
  22312. }
  22313. this._updatable = updatable;
  22314. this._data = data;
  22315. this._strideSize = stride;
  22316. if (!postponeInternalCreation) {
  22317. this.create();
  22318. }
  22319. this._instanced = instanced;
  22320. }
  22321. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22322. // a lot of these parameters are ignored as they are overriden by the buffer
  22323. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22324. };
  22325. // Properties
  22326. Buffer.prototype.isUpdatable = function () {
  22327. return this._updatable;
  22328. };
  22329. Buffer.prototype.getData = function () {
  22330. return this._data;
  22331. };
  22332. Buffer.prototype.getBuffer = function () {
  22333. return this._buffer;
  22334. };
  22335. Buffer.prototype.getStrideSize = function () {
  22336. return this._strideSize;
  22337. };
  22338. Buffer.prototype.getIsInstanced = function () {
  22339. return this._instanced;
  22340. };
  22341. // Methods
  22342. Buffer.prototype.create = function (data) {
  22343. if (!data && this._buffer) {
  22344. return; // nothing to do
  22345. }
  22346. data = data || this._data;
  22347. if (!this._buffer) {
  22348. if (this._updatable) {
  22349. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22350. this._data = data;
  22351. }
  22352. else {
  22353. this._buffer = this._engine.createVertexBuffer(data);
  22354. }
  22355. }
  22356. else if (this._updatable) {
  22357. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22358. this._data = data;
  22359. }
  22360. };
  22361. Buffer.prototype.update = function (data) {
  22362. this.create(data);
  22363. };
  22364. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22365. if (!this._buffer) {
  22366. return;
  22367. }
  22368. if (this._updatable) {
  22369. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22370. this._data = null;
  22371. }
  22372. };
  22373. Buffer.prototype.dispose = function () {
  22374. if (!this._buffer) {
  22375. return;
  22376. }
  22377. if (this._engine._releaseBuffer(this._buffer)) {
  22378. this._buffer = null;
  22379. }
  22380. };
  22381. return Buffer;
  22382. }());
  22383. BABYLON.Buffer = Buffer;
  22384. })(BABYLON || (BABYLON = {}));
  22385. //# sourceMappingURL=babylon.buffer.js.map
  22386. var BABYLON;
  22387. (function (BABYLON) {
  22388. var VertexBuffer = (function () {
  22389. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22390. if (!stride) {
  22391. // Deduce stride from kind
  22392. switch (kind) {
  22393. case VertexBuffer.PositionKind:
  22394. stride = 3;
  22395. break;
  22396. case VertexBuffer.NormalKind:
  22397. stride = 3;
  22398. break;
  22399. case VertexBuffer.UVKind:
  22400. case VertexBuffer.UV2Kind:
  22401. case VertexBuffer.UV3Kind:
  22402. case VertexBuffer.UV4Kind:
  22403. case VertexBuffer.UV5Kind:
  22404. case VertexBuffer.UV6Kind:
  22405. stride = 2;
  22406. break;
  22407. case VertexBuffer.TangentKind:
  22408. case VertexBuffer.ColorKind:
  22409. stride = 4;
  22410. break;
  22411. case VertexBuffer.MatricesIndicesKind:
  22412. case VertexBuffer.MatricesIndicesExtraKind:
  22413. stride = 4;
  22414. break;
  22415. case VertexBuffer.MatricesWeightsKind:
  22416. case VertexBuffer.MatricesWeightsExtraKind:
  22417. stride = 4;
  22418. break;
  22419. }
  22420. }
  22421. if (data instanceof BABYLON.Buffer) {
  22422. if (!stride) {
  22423. stride = data.getStrideSize();
  22424. }
  22425. this._buffer = data;
  22426. this._ownsBuffer = false;
  22427. }
  22428. else {
  22429. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22430. this._ownsBuffer = true;
  22431. }
  22432. this._stride = stride;
  22433. this._offset = offset ? offset : 0;
  22434. this._size = size ? size : stride;
  22435. this._kind = kind;
  22436. }
  22437. /**
  22438. * Returns the kind of the VertexBuffer (string).
  22439. */
  22440. VertexBuffer.prototype.getKind = function () {
  22441. return this._kind;
  22442. };
  22443. // Properties
  22444. /**
  22445. * Boolean : is the VertexBuffer updatable ?
  22446. */
  22447. VertexBuffer.prototype.isUpdatable = function () {
  22448. return this._buffer.isUpdatable();
  22449. };
  22450. /**
  22451. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22452. */
  22453. VertexBuffer.prototype.getData = function () {
  22454. return this._buffer.getData();
  22455. };
  22456. /**
  22457. * Returns the WebGLBuffer associated to the VertexBuffer.
  22458. */
  22459. VertexBuffer.prototype.getBuffer = function () {
  22460. return this._buffer.getBuffer();
  22461. };
  22462. /**
  22463. * Returns the stride of the VertexBuffer (integer).
  22464. */
  22465. VertexBuffer.prototype.getStrideSize = function () {
  22466. return this._stride;
  22467. };
  22468. /**
  22469. * Returns the offset (integer).
  22470. */
  22471. VertexBuffer.prototype.getOffset = function () {
  22472. return this._offset;
  22473. };
  22474. /**
  22475. * Returns the VertexBuffer total size (integer).
  22476. */
  22477. VertexBuffer.prototype.getSize = function () {
  22478. return this._size;
  22479. };
  22480. /**
  22481. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22482. */
  22483. VertexBuffer.prototype.getIsInstanced = function () {
  22484. return this._buffer.getIsInstanced();
  22485. };
  22486. // Methods
  22487. /**
  22488. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22489. * Returns the created WebGLBuffer.
  22490. */
  22491. VertexBuffer.prototype.create = function (data) {
  22492. return this._buffer.create(data);
  22493. };
  22494. /**
  22495. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22496. * Returns the updated WebGLBuffer.
  22497. */
  22498. VertexBuffer.prototype.update = function (data) {
  22499. return this._buffer.update(data);
  22500. };
  22501. /**
  22502. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22503. * Returns the directly updated WebGLBuffer.
  22504. */
  22505. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22506. return this._buffer.updateDirectly(data, offset);
  22507. };
  22508. /**
  22509. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22510. */
  22511. VertexBuffer.prototype.dispose = function () {
  22512. if (this._ownsBuffer) {
  22513. this._buffer.dispose();
  22514. }
  22515. };
  22516. Object.defineProperty(VertexBuffer, "PositionKind", {
  22517. get: function () {
  22518. return VertexBuffer._PositionKind;
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Object.defineProperty(VertexBuffer, "NormalKind", {
  22524. get: function () {
  22525. return VertexBuffer._NormalKind;
  22526. },
  22527. enumerable: true,
  22528. configurable: true
  22529. });
  22530. Object.defineProperty(VertexBuffer, "TangentKind", {
  22531. get: function () {
  22532. return VertexBuffer._TangentKind;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. Object.defineProperty(VertexBuffer, "UVKind", {
  22538. get: function () {
  22539. return VertexBuffer._UVKind;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22545. get: function () {
  22546. return VertexBuffer._UV2Kind;
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22552. get: function () {
  22553. return VertexBuffer._UV3Kind;
  22554. },
  22555. enumerable: true,
  22556. configurable: true
  22557. });
  22558. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22559. get: function () {
  22560. return VertexBuffer._UV4Kind;
  22561. },
  22562. enumerable: true,
  22563. configurable: true
  22564. });
  22565. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22566. get: function () {
  22567. return VertexBuffer._UV5Kind;
  22568. },
  22569. enumerable: true,
  22570. configurable: true
  22571. });
  22572. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22573. get: function () {
  22574. return VertexBuffer._UV6Kind;
  22575. },
  22576. enumerable: true,
  22577. configurable: true
  22578. });
  22579. Object.defineProperty(VertexBuffer, "ColorKind", {
  22580. get: function () {
  22581. return VertexBuffer._ColorKind;
  22582. },
  22583. enumerable: true,
  22584. configurable: true
  22585. });
  22586. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22587. get: function () {
  22588. return VertexBuffer._MatricesIndicesKind;
  22589. },
  22590. enumerable: true,
  22591. configurable: true
  22592. });
  22593. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22594. get: function () {
  22595. return VertexBuffer._MatricesWeightsKind;
  22596. },
  22597. enumerable: true,
  22598. configurable: true
  22599. });
  22600. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22601. get: function () {
  22602. return VertexBuffer._MatricesIndicesExtraKind;
  22603. },
  22604. enumerable: true,
  22605. configurable: true
  22606. });
  22607. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22608. get: function () {
  22609. return VertexBuffer._MatricesWeightsExtraKind;
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. return VertexBuffer;
  22615. }());
  22616. // Enums
  22617. VertexBuffer._PositionKind = "position";
  22618. VertexBuffer._NormalKind = "normal";
  22619. VertexBuffer._TangentKind = "tangent";
  22620. VertexBuffer._UVKind = "uv";
  22621. VertexBuffer._UV2Kind = "uv2";
  22622. VertexBuffer._UV3Kind = "uv3";
  22623. VertexBuffer._UV4Kind = "uv4";
  22624. VertexBuffer._UV5Kind = "uv5";
  22625. VertexBuffer._UV6Kind = "uv6";
  22626. VertexBuffer._ColorKind = "color";
  22627. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22628. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22629. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22630. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22631. BABYLON.VertexBuffer = VertexBuffer;
  22632. })(BABYLON || (BABYLON = {}));
  22633. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22634. var BABYLON;
  22635. (function (BABYLON) {
  22636. /**
  22637. * Creates an instance based on a source mesh.
  22638. */
  22639. var InstancedMesh = (function (_super) {
  22640. __extends(InstancedMesh, _super);
  22641. function InstancedMesh(name, source) {
  22642. var _this = _super.call(this, name, source.getScene()) || this;
  22643. source.instances.push(_this);
  22644. _this._sourceMesh = source;
  22645. _this.position.copyFrom(source.position);
  22646. _this.rotation.copyFrom(source.rotation);
  22647. _this.scaling.copyFrom(source.scaling);
  22648. if (source.rotationQuaternion) {
  22649. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22650. }
  22651. _this.infiniteDistance = source.infiniteDistance;
  22652. _this.setPivotMatrix(source.getPivotMatrix());
  22653. _this.refreshBoundingInfo();
  22654. _this._syncSubMeshes();
  22655. return _this;
  22656. }
  22657. /**
  22658. * Returns the string "InstancedMesh".
  22659. */
  22660. InstancedMesh.prototype.getClassName = function () {
  22661. return "InstancedMesh";
  22662. };
  22663. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22664. // Methods
  22665. get: function () {
  22666. return this._sourceMesh.receiveShadows;
  22667. },
  22668. enumerable: true,
  22669. configurable: true
  22670. });
  22671. Object.defineProperty(InstancedMesh.prototype, "material", {
  22672. get: function () {
  22673. return this._sourceMesh.material;
  22674. },
  22675. enumerable: true,
  22676. configurable: true
  22677. });
  22678. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22679. get: function () {
  22680. return this._sourceMesh.visibility;
  22681. },
  22682. enumerable: true,
  22683. configurable: true
  22684. });
  22685. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22686. get: function () {
  22687. return this._sourceMesh.skeleton;
  22688. },
  22689. enumerable: true,
  22690. configurable: true
  22691. });
  22692. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22693. get: function () {
  22694. return this._sourceMesh.renderingGroupId;
  22695. },
  22696. enumerable: true,
  22697. configurable: true
  22698. });
  22699. /**
  22700. * Returns the total number of vertices (integer).
  22701. */
  22702. InstancedMesh.prototype.getTotalVertices = function () {
  22703. return this._sourceMesh.getTotalVertices();
  22704. };
  22705. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22706. get: function () {
  22707. return this._sourceMesh;
  22708. },
  22709. enumerable: true,
  22710. configurable: true
  22711. });
  22712. /**
  22713. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22714. */
  22715. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22716. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22717. };
  22718. /**
  22719. * Boolean : True if the mesh owns the requested kind of data.
  22720. */
  22721. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22722. return this._sourceMesh.isVerticesDataPresent(kind);
  22723. };
  22724. /**
  22725. * Returns an array of indices (IndicesArray).
  22726. */
  22727. InstancedMesh.prototype.getIndices = function () {
  22728. return this._sourceMesh.getIndices();
  22729. };
  22730. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22731. get: function () {
  22732. return this._sourceMesh._positions;
  22733. },
  22734. enumerable: true,
  22735. configurable: true
  22736. });
  22737. /**
  22738. * Sets a new updated BoundingInfo to the mesh.
  22739. * Returns the mesh.
  22740. */
  22741. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22742. var meshBB = this._sourceMesh.getBoundingInfo();
  22743. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22744. this._updateBoundingInfo();
  22745. return this;
  22746. };
  22747. InstancedMesh.prototype._preActivate = function () {
  22748. if (this._currentLOD) {
  22749. this._currentLOD._preActivate();
  22750. }
  22751. return this;
  22752. };
  22753. InstancedMesh.prototype._activate = function (renderId) {
  22754. if (this._currentLOD) {
  22755. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22756. }
  22757. return this;
  22758. };
  22759. /**
  22760. * Returns the current associated LOD AbstractMesh.
  22761. */
  22762. InstancedMesh.prototype.getLOD = function (camera) {
  22763. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22764. if (this._currentLOD === this.sourceMesh) {
  22765. return this;
  22766. }
  22767. return this._currentLOD;
  22768. };
  22769. InstancedMesh.prototype._syncSubMeshes = function () {
  22770. this.releaseSubMeshes();
  22771. if (this._sourceMesh.subMeshes) {
  22772. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22773. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22774. }
  22775. }
  22776. return this;
  22777. };
  22778. InstancedMesh.prototype._generatePointsArray = function () {
  22779. return this._sourceMesh._generatePointsArray();
  22780. };
  22781. /**
  22782. * Creates a new InstancedMesh from the current mesh.
  22783. * - name (string) : the cloned mesh name
  22784. * - newParent (optional Node) : the optional Node to parent the clone to.
  22785. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22786. *
  22787. * Returns the clone.
  22788. */
  22789. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22790. var result = this._sourceMesh.createInstance(name);
  22791. // Deep copy
  22792. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  22793. // Bounding info
  22794. this.refreshBoundingInfo();
  22795. // Parent
  22796. if (newParent) {
  22797. result.parent = newParent;
  22798. }
  22799. if (!doNotCloneChildren) {
  22800. // Children
  22801. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22802. var mesh = this.getScene().meshes[index];
  22803. if (mesh.parent === this) {
  22804. mesh.clone(mesh.name, result);
  22805. }
  22806. }
  22807. }
  22808. result.computeWorldMatrix(true);
  22809. return result;
  22810. };
  22811. /**
  22812. * Disposes the InstancedMesh.
  22813. * Returns nothing.
  22814. */
  22815. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22816. // Remove from mesh
  22817. var index = this._sourceMesh.instances.indexOf(this);
  22818. this._sourceMesh.instances.splice(index, 1);
  22819. _super.prototype.dispose.call(this, doNotRecurse);
  22820. };
  22821. return InstancedMesh;
  22822. }(BABYLON.AbstractMesh));
  22823. BABYLON.InstancedMesh = InstancedMesh;
  22824. })(BABYLON || (BABYLON = {}));
  22825. //# sourceMappingURL=babylon.instancedMesh.js.map
  22826. var BABYLON;
  22827. (function (BABYLON) {
  22828. var _InstancesBatch = (function () {
  22829. function _InstancesBatch() {
  22830. this.mustReturn = false;
  22831. this.visibleInstances = new Array();
  22832. this.renderSelf = new Array();
  22833. }
  22834. return _InstancesBatch;
  22835. }());
  22836. BABYLON._InstancesBatch = _InstancesBatch;
  22837. var Mesh = (function (_super) {
  22838. __extends(Mesh, _super);
  22839. /**
  22840. * @constructor
  22841. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22842. * @param {Scene} scene The scene to add this mesh to.
  22843. * @param {Node} parent The parent of this mesh, if it has one
  22844. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22845. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22846. * When false, achieved by calling a clone(), also passing False.
  22847. * This will make creation of children, recursive.
  22848. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22849. */
  22850. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22851. if (parent === void 0) { parent = null; }
  22852. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22853. var _this = _super.call(this, name, scene) || this;
  22854. // Events
  22855. /**
  22856. * An event triggered before rendering the mesh
  22857. * @type {BABYLON.Observable}
  22858. */
  22859. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22860. /**
  22861. * An event triggered after rendering the mesh
  22862. * @type {BABYLON.Observable}
  22863. */
  22864. _this.onAfterRenderObservable = new BABYLON.Observable();
  22865. /**
  22866. * An event triggered before drawing the mesh
  22867. * @type {BABYLON.Observable}
  22868. */
  22869. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22870. // Members
  22871. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22872. _this.instances = new Array();
  22873. _this._LODLevels = new Array();
  22874. _this._visibleInstances = {};
  22875. _this._renderIdForInstances = new Array();
  22876. _this._batchCache = new _InstancesBatch();
  22877. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22878. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22879. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22880. // Will be used to save a source mesh reference, If any
  22881. _this._source = null;
  22882. if (source) {
  22883. // Source mesh
  22884. _this._source = source;
  22885. // Geometry
  22886. if (source._geometry) {
  22887. source._geometry.applyToMesh(_this);
  22888. }
  22889. // Deep copy
  22890. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22891. // Parent
  22892. _this.parent = source.parent;
  22893. // Pivot
  22894. _this.setPivotMatrix(source.getPivotMatrix());
  22895. _this.id = name + "." + source.id;
  22896. // Material
  22897. _this.material = source.material;
  22898. var index;
  22899. if (!doNotCloneChildren) {
  22900. // Children
  22901. for (index = 0; index < scene.meshes.length; index++) {
  22902. var mesh = scene.meshes[index];
  22903. if (mesh.parent === source) {
  22904. // doNotCloneChildren is always going to be False
  22905. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22906. }
  22907. }
  22908. }
  22909. // Physics clone
  22910. var physicsEngine = _this.getScene().getPhysicsEngine();
  22911. if (clonePhysicsImpostor && physicsEngine) {
  22912. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22913. if (impostor) {
  22914. _this.physicsImpostor = impostor.clone(_this);
  22915. }
  22916. }
  22917. // Particles
  22918. for (index = 0; index < scene.particleSystems.length; index++) {
  22919. var system = scene.particleSystems[index];
  22920. if (system.emitter === source) {
  22921. system.clone(system.name, _this);
  22922. }
  22923. }
  22924. _this.computeWorldMatrix(true);
  22925. }
  22926. // Parent
  22927. if (parent !== null) {
  22928. _this.parent = parent;
  22929. }
  22930. return _this;
  22931. }
  22932. Object.defineProperty(Mesh, "FRONTSIDE", {
  22933. /**
  22934. * Mesh side orientation : usually the external or front surface
  22935. */
  22936. get: function () {
  22937. return Mesh._FRONTSIDE;
  22938. },
  22939. enumerable: true,
  22940. configurable: true
  22941. });
  22942. Object.defineProperty(Mesh, "BACKSIDE", {
  22943. /**
  22944. * Mesh side orientation : usually the internal or back surface
  22945. */
  22946. get: function () {
  22947. return Mesh._BACKSIDE;
  22948. },
  22949. enumerable: true,
  22950. configurable: true
  22951. });
  22952. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22953. /**
  22954. * Mesh side orientation : both internal and external or front and back surfaces
  22955. */
  22956. get: function () {
  22957. return Mesh._DOUBLESIDE;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22963. /**
  22964. * Mesh side orientation : by default, `FRONTSIDE`
  22965. */
  22966. get: function () {
  22967. return Mesh._DEFAULTSIDE;
  22968. },
  22969. enumerable: true,
  22970. configurable: true
  22971. });
  22972. Object.defineProperty(Mesh, "NO_CAP", {
  22973. /**
  22974. * Mesh cap setting : no cap
  22975. */
  22976. get: function () {
  22977. return Mesh._NO_CAP;
  22978. },
  22979. enumerable: true,
  22980. configurable: true
  22981. });
  22982. Object.defineProperty(Mesh, "CAP_START", {
  22983. /**
  22984. * Mesh cap setting : one cap at the beginning of the mesh
  22985. */
  22986. get: function () {
  22987. return Mesh._CAP_START;
  22988. },
  22989. enumerable: true,
  22990. configurable: true
  22991. });
  22992. Object.defineProperty(Mesh, "CAP_END", {
  22993. /**
  22994. * Mesh cap setting : one cap at the end of the mesh
  22995. */
  22996. get: function () {
  22997. return Mesh._CAP_END;
  22998. },
  22999. enumerable: true,
  23000. configurable: true
  23001. });
  23002. Object.defineProperty(Mesh, "CAP_ALL", {
  23003. /**
  23004. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23005. */
  23006. get: function () {
  23007. return Mesh._CAP_ALL;
  23008. },
  23009. enumerable: true,
  23010. configurable: true
  23011. });
  23012. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23013. set: function (callback) {
  23014. if (this._onBeforeDrawObserver) {
  23015. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23016. }
  23017. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23018. },
  23019. enumerable: true,
  23020. configurable: true
  23021. });
  23022. Object.defineProperty(Mesh.prototype, "source", {
  23023. get: function () {
  23024. return this._source;
  23025. },
  23026. enumerable: true,
  23027. configurable: true
  23028. });
  23029. // Methods
  23030. /**
  23031. * Returns the string "Mesh".
  23032. */
  23033. Mesh.prototype.getClassName = function () {
  23034. return "Mesh";
  23035. };
  23036. /**
  23037. * Returns a string.
  23038. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23039. */
  23040. Mesh.prototype.toString = function (fullDetails) {
  23041. var ret = _super.prototype.toString.call(this, fullDetails);
  23042. ret += ", n vertices: " + this.getTotalVertices();
  23043. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23044. if (this.animations) {
  23045. for (var i = 0; i < this.animations.length; i++) {
  23046. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23047. }
  23048. }
  23049. if (fullDetails) {
  23050. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  23051. }
  23052. return ret;
  23053. };
  23054. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23055. /**
  23056. * True if the mesh has some Levels Of Details (LOD).
  23057. * Returns a boolean.
  23058. */
  23059. get: function () {
  23060. return this._LODLevels.length > 0;
  23061. },
  23062. enumerable: true,
  23063. configurable: true
  23064. });
  23065. Mesh.prototype._sortLODLevels = function () {
  23066. this._LODLevels.sort(function (a, b) {
  23067. if (a.distance < b.distance) {
  23068. return 1;
  23069. }
  23070. if (a.distance > b.distance) {
  23071. return -1;
  23072. }
  23073. return 0;
  23074. });
  23075. };
  23076. /**
  23077. * Add a mesh as LOD level triggered at the given distance.
  23078. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23079. * @param {number} distance The distance from the center of the object to show this level
  23080. * @param {Mesh} mesh The mesh to be added as LOD level
  23081. * @return {Mesh} This mesh (for chaining)
  23082. */
  23083. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23084. if (mesh && mesh._masterMesh) {
  23085. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23086. return this;
  23087. }
  23088. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23089. this._LODLevels.push(level);
  23090. if (mesh) {
  23091. mesh._masterMesh = this;
  23092. }
  23093. this._sortLODLevels();
  23094. return this;
  23095. };
  23096. /**
  23097. * Returns the LOD level mesh at the passed distance or null if not found.
  23098. * It is related to the method `addLODLevel(distance, mesh)`.
  23099. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23100. * Returns an object Mesh or `null`.
  23101. */
  23102. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23103. for (var index = 0; index < this._LODLevels.length; index++) {
  23104. var level = this._LODLevels[index];
  23105. if (level.distance === distance) {
  23106. return level.mesh;
  23107. }
  23108. }
  23109. return null;
  23110. };
  23111. /**
  23112. * Remove a mesh from the LOD array
  23113. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23114. * @param {Mesh} mesh The mesh to be removed.
  23115. * @return {Mesh} This mesh (for chaining)
  23116. */
  23117. Mesh.prototype.removeLODLevel = function (mesh) {
  23118. for (var index = 0; index < this._LODLevels.length; index++) {
  23119. if (this._LODLevels[index].mesh === mesh) {
  23120. this._LODLevels.splice(index, 1);
  23121. if (mesh) {
  23122. mesh._masterMesh = null;
  23123. }
  23124. }
  23125. }
  23126. this._sortLODLevels();
  23127. return this;
  23128. };
  23129. /**
  23130. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23131. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23132. */
  23133. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23134. if (!this._LODLevels || this._LODLevels.length === 0) {
  23135. return this;
  23136. }
  23137. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23138. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23139. if (this.onLODLevelSelection) {
  23140. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23141. }
  23142. return this;
  23143. }
  23144. for (var index = 0; index < this._LODLevels.length; index++) {
  23145. var level = this._LODLevels[index];
  23146. if (level.distance < distanceToCamera) {
  23147. if (level.mesh) {
  23148. level.mesh._preActivate();
  23149. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23150. }
  23151. if (this.onLODLevelSelection) {
  23152. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23153. }
  23154. return level.mesh;
  23155. }
  23156. }
  23157. if (this.onLODLevelSelection) {
  23158. this.onLODLevelSelection(distanceToCamera, this, this);
  23159. }
  23160. return this;
  23161. };
  23162. Object.defineProperty(Mesh.prototype, "geometry", {
  23163. /**
  23164. * Returns the mesh internal Geometry object.
  23165. */
  23166. get: function () {
  23167. return this._geometry;
  23168. },
  23169. enumerable: true,
  23170. configurable: true
  23171. });
  23172. /**
  23173. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23174. */
  23175. Mesh.prototype.getTotalVertices = function () {
  23176. if (!this._geometry) {
  23177. return 0;
  23178. }
  23179. return this._geometry.getTotalVertices();
  23180. };
  23181. /**
  23182. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23183. * 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.
  23184. * Returns null if the mesh has no geometry or no vertex buffer.
  23185. * Possible `kind` values :
  23186. * - BABYLON.VertexBuffer.PositionKind
  23187. * - BABYLON.VertexBuffer.UVKind
  23188. * - BABYLON.VertexBuffer.UV2Kind
  23189. * - BABYLON.VertexBuffer.UV3Kind
  23190. * - BABYLON.VertexBuffer.UV4Kind
  23191. * - BABYLON.VertexBuffer.UV5Kind
  23192. * - BABYLON.VertexBuffer.UV6Kind
  23193. * - BABYLON.VertexBuffer.ColorKind
  23194. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23195. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23196. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23197. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23198. */
  23199. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23200. if (!this._geometry) {
  23201. return null;
  23202. }
  23203. return this._geometry.getVerticesData(kind, copyWhenShared);
  23204. };
  23205. /**
  23206. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23207. * Returns `undefined` if the mesh has no geometry.
  23208. * Possible `kind` values :
  23209. * - BABYLON.VertexBuffer.PositionKind
  23210. * - BABYLON.VertexBuffer.UVKind
  23211. * - BABYLON.VertexBuffer.UV2Kind
  23212. * - BABYLON.VertexBuffer.UV3Kind
  23213. * - BABYLON.VertexBuffer.UV4Kind
  23214. * - BABYLON.VertexBuffer.UV5Kind
  23215. * - BABYLON.VertexBuffer.UV6Kind
  23216. * - BABYLON.VertexBuffer.ColorKind
  23217. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23218. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23219. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23220. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23221. */
  23222. Mesh.prototype.getVertexBuffer = function (kind) {
  23223. if (!this._geometry) {
  23224. return undefined;
  23225. }
  23226. return this._geometry.getVertexBuffer(kind);
  23227. };
  23228. /**
  23229. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23230. * Possible `kind` values :
  23231. * - BABYLON.VertexBuffer.PositionKind
  23232. * - BABYLON.VertexBuffer.UVKind
  23233. * - BABYLON.VertexBuffer.UV2Kind
  23234. * - BABYLON.VertexBuffer.UV3Kind
  23235. * - BABYLON.VertexBuffer.UV4Kind
  23236. * - BABYLON.VertexBuffer.UV5Kind
  23237. * - BABYLON.VertexBuffer.UV6Kind
  23238. * - BABYLON.VertexBuffer.ColorKind
  23239. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23240. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23241. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23242. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23243. */
  23244. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23245. if (!this._geometry) {
  23246. if (this._delayInfo) {
  23247. return this._delayInfo.indexOf(kind) !== -1;
  23248. }
  23249. return false;
  23250. }
  23251. return this._geometry.isVerticesDataPresent(kind);
  23252. };
  23253. /**
  23254. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23255. * Possible `kind` values :
  23256. * - BABYLON.VertexBuffer.PositionKind
  23257. * - BABYLON.VertexBuffer.UVKind
  23258. * - BABYLON.VertexBuffer.UV2Kind
  23259. * - BABYLON.VertexBuffer.UV3Kind
  23260. * - BABYLON.VertexBuffer.UV4Kind
  23261. * - BABYLON.VertexBuffer.UV5Kind
  23262. * - BABYLON.VertexBuffer.UV6Kind
  23263. * - BABYLON.VertexBuffer.ColorKind
  23264. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23265. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23266. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23267. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23268. */
  23269. Mesh.prototype.getVerticesDataKinds = function () {
  23270. if (!this._geometry) {
  23271. var result = [];
  23272. if (this._delayInfo) {
  23273. this._delayInfo.forEach(function (kind, index, array) {
  23274. result.push(kind);
  23275. });
  23276. }
  23277. return result;
  23278. }
  23279. return this._geometry.getVerticesDataKinds();
  23280. };
  23281. /**
  23282. * Returns a positive integer : the total number of indices in this mesh geometry.
  23283. * Returns zero if the mesh has no geometry.
  23284. */
  23285. Mesh.prototype.getTotalIndices = function () {
  23286. if (!this._geometry) {
  23287. return 0;
  23288. }
  23289. return this._geometry.getTotalIndices();
  23290. };
  23291. /**
  23292. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23293. * 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.
  23294. * Returns an empty array if the mesh has no geometry.
  23295. */
  23296. Mesh.prototype.getIndices = function (copyWhenShared) {
  23297. if (!this._geometry) {
  23298. return [];
  23299. }
  23300. return this._geometry.getIndices(copyWhenShared);
  23301. };
  23302. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23303. get: function () {
  23304. return this._masterMesh !== null && this._masterMesh !== undefined;
  23305. },
  23306. enumerable: true,
  23307. configurable: true
  23308. });
  23309. /**
  23310. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23311. */
  23312. Mesh.prototype.isReady = function () {
  23313. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23314. return false;
  23315. }
  23316. return _super.prototype.isReady.call(this);
  23317. };
  23318. /**
  23319. * Boolean : true if the mesh has been disposed.
  23320. */
  23321. Mesh.prototype.isDisposed = function () {
  23322. return this._isDisposed;
  23323. };
  23324. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23325. get: function () {
  23326. return this._sideOrientation;
  23327. },
  23328. /**
  23329. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23330. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23331. */
  23332. set: function (sideO) {
  23333. this._sideOrientation = sideO;
  23334. },
  23335. enumerable: true,
  23336. configurable: true
  23337. });
  23338. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23339. /**
  23340. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23341. * This property is pertinent only for updatable parametric shapes.
  23342. */
  23343. get: function () {
  23344. return this._areNormalsFrozen;
  23345. },
  23346. enumerable: true,
  23347. configurable: true
  23348. });
  23349. /**
  23350. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23351. * It has no effect at all on other shapes.
  23352. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23353. * Returns the Mesh.
  23354. */
  23355. Mesh.prototype.freezeNormals = function () {
  23356. this._areNormalsFrozen = true;
  23357. return this;
  23358. };
  23359. /**
  23360. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23361. * It has no effect at all on other shapes.
  23362. * It reactivates the mesh normals computation if it was previously frozen.
  23363. * Returns the Mesh.
  23364. */
  23365. Mesh.prototype.unfreezeNormals = function () {
  23366. this._areNormalsFrozen = false;
  23367. return this;
  23368. };
  23369. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23370. /**
  23371. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23372. */
  23373. set: function (count) {
  23374. this._overridenInstanceCount = count;
  23375. },
  23376. enumerable: true,
  23377. configurable: true
  23378. });
  23379. // Methods
  23380. Mesh.prototype._preActivate = function () {
  23381. var sceneRenderId = this.getScene().getRenderId();
  23382. if (this._preActivateId === sceneRenderId) {
  23383. return this;
  23384. }
  23385. this._preActivateId = sceneRenderId;
  23386. this._visibleInstances = null;
  23387. return this;
  23388. };
  23389. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23390. if (this._visibleInstances) {
  23391. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23392. }
  23393. return this;
  23394. };
  23395. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23396. if (!this._visibleInstances) {
  23397. this._visibleInstances = {};
  23398. this._visibleInstances.defaultRenderId = renderId;
  23399. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23400. }
  23401. if (!this._visibleInstances[renderId]) {
  23402. this._visibleInstances[renderId] = new Array();
  23403. }
  23404. this._visibleInstances[renderId].push(instance);
  23405. return this;
  23406. };
  23407. /**
  23408. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23409. * This means the mesh underlying bounding box and sphere are recomputed.
  23410. * Returns the Mesh.
  23411. */
  23412. Mesh.prototype.refreshBoundingInfo = function () {
  23413. if (this._boundingInfo.isLocked) {
  23414. return;
  23415. }
  23416. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23417. if (data) {
  23418. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23419. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23420. }
  23421. if (this.subMeshes) {
  23422. for (var index = 0; index < this.subMeshes.length; index++) {
  23423. this.subMeshes[index].refreshBoundingInfo();
  23424. }
  23425. }
  23426. this._updateBoundingInfo();
  23427. return this;
  23428. };
  23429. Mesh.prototype._createGlobalSubMesh = function () {
  23430. var totalVertices = this.getTotalVertices();
  23431. if (!totalVertices || !this.getIndices()) {
  23432. return null;
  23433. }
  23434. this.releaseSubMeshes();
  23435. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23436. };
  23437. Mesh.prototype.subdivide = function (count) {
  23438. if (count < 1) {
  23439. return;
  23440. }
  23441. var totalIndices = this.getTotalIndices();
  23442. var subdivisionSize = (totalIndices / count) | 0;
  23443. var offset = 0;
  23444. // Ensure that subdivisionSize is a multiple of 3
  23445. while (subdivisionSize % 3 !== 0) {
  23446. subdivisionSize++;
  23447. }
  23448. this.releaseSubMeshes();
  23449. for (var index = 0; index < count; index++) {
  23450. if (offset >= totalIndices) {
  23451. break;
  23452. }
  23453. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23454. offset += subdivisionSize;
  23455. }
  23456. this.synchronizeInstances();
  23457. };
  23458. /**
  23459. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23460. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23461. * The `data` are either a numeric array either a Float32Array.
  23462. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23463. * 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).
  23464. * Note that a new underlying VertexBuffer object is created each call.
  23465. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23466. *
  23467. * Possible `kind` values :
  23468. * - BABYLON.VertexBuffer.PositionKind
  23469. * - BABYLON.VertexBuffer.UVKind
  23470. * - BABYLON.VertexBuffer.UV2Kind
  23471. * - BABYLON.VertexBuffer.UV3Kind
  23472. * - BABYLON.VertexBuffer.UV4Kind
  23473. * - BABYLON.VertexBuffer.UV5Kind
  23474. * - BABYLON.VertexBuffer.UV6Kind
  23475. * - BABYLON.VertexBuffer.ColorKind
  23476. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23477. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23478. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23479. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23480. *
  23481. * Returns the Mesh.
  23482. */
  23483. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23484. if (!this._geometry) {
  23485. var vertexData = new BABYLON.VertexData();
  23486. vertexData.set(data, kind);
  23487. var scene = this.getScene();
  23488. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23489. }
  23490. else {
  23491. this._geometry.setVerticesData(kind, data, updatable, stride);
  23492. }
  23493. return this;
  23494. };
  23495. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23496. if (updatable === void 0) { updatable = true; }
  23497. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23498. return;
  23499. }
  23500. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23501. };
  23502. /**
  23503. * Sets the mesh VertexBuffer.
  23504. * Returns the Mesh.
  23505. */
  23506. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23507. if (!this._geometry) {
  23508. var scene = this.getScene();
  23509. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23510. }
  23511. this._geometry.setVerticesBuffer(buffer);
  23512. return this;
  23513. };
  23514. /**
  23515. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23516. * If the mesh has no geometry, it is simply returned as it is.
  23517. * The `data` are either a numeric array either a Float32Array.
  23518. * No new underlying VertexBuffer object is created.
  23519. * 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.
  23520. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23521. *
  23522. * Possible `kind` values :
  23523. * - BABYLON.VertexBuffer.PositionKind
  23524. * - BABYLON.VertexBuffer.UVKind
  23525. * - BABYLON.VertexBuffer.UV2Kind
  23526. * - BABYLON.VertexBuffer.UV3Kind
  23527. * - BABYLON.VertexBuffer.UV4Kind
  23528. * - BABYLON.VertexBuffer.UV5Kind
  23529. * - BABYLON.VertexBuffer.UV6Kind
  23530. * - BABYLON.VertexBuffer.ColorKind
  23531. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23532. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23533. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23534. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23535. *
  23536. * Returns the Mesh.
  23537. */
  23538. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23539. if (!this._geometry) {
  23540. return;
  23541. }
  23542. if (!makeItUnique) {
  23543. this._geometry.updateVerticesData(kind, data, updateExtends);
  23544. }
  23545. else {
  23546. this.makeGeometryUnique();
  23547. this.updateVerticesData(kind, data, updateExtends, false);
  23548. }
  23549. return this;
  23550. };
  23551. /**
  23552. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23553. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23554. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23555. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23556. * Returns the Mesh.
  23557. */
  23558. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23559. if (computeNormals === void 0) { computeNormals = true; }
  23560. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23561. positionFunction(positions);
  23562. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23563. if (computeNormals) {
  23564. var indices = this.getIndices();
  23565. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23566. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23567. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23568. }
  23569. return this;
  23570. };
  23571. /**
  23572. * Creates a un-shared specific occurence of the geometry for the mesh.
  23573. * Returns the Mesh.
  23574. */
  23575. Mesh.prototype.makeGeometryUnique = function () {
  23576. if (!this._geometry) {
  23577. return;
  23578. }
  23579. var oldGeometry = this._geometry;
  23580. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23581. oldGeometry.releaseForMesh(this, true);
  23582. geometry.applyToMesh(this);
  23583. return this;
  23584. };
  23585. /**
  23586. * Sets the mesh indices.
  23587. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23588. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23589. * This method creates a new index buffer each call.
  23590. * Returns the Mesh.
  23591. */
  23592. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23593. if (!this._geometry) {
  23594. var vertexData = new BABYLON.VertexData();
  23595. vertexData.indices = indices;
  23596. var scene = this.getScene();
  23597. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23598. }
  23599. else {
  23600. this._geometry.setIndices(indices, totalVertices);
  23601. }
  23602. return this;
  23603. };
  23604. /**
  23605. * Invert the geometry to move from a right handed system to a left handed one.
  23606. * Returns the Mesh.
  23607. */
  23608. Mesh.prototype.toLeftHanded = function () {
  23609. if (!this._geometry) {
  23610. return;
  23611. }
  23612. this._geometry.toLeftHanded();
  23613. return this;
  23614. };
  23615. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23616. var engine = this.getScene().getEngine();
  23617. // Wireframe
  23618. var indexToBind;
  23619. if (this._unIndexed) {
  23620. indexToBind = null;
  23621. }
  23622. else {
  23623. switch (fillMode) {
  23624. case BABYLON.Material.PointFillMode:
  23625. indexToBind = null;
  23626. break;
  23627. case BABYLON.Material.WireFrameFillMode:
  23628. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23629. break;
  23630. default:
  23631. case BABYLON.Material.TriangleFillMode:
  23632. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23633. break;
  23634. }
  23635. }
  23636. // VBOs
  23637. this._geometry._bind(effect, indexToBind);
  23638. return this;
  23639. };
  23640. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23641. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23642. return this;
  23643. }
  23644. this.onBeforeDrawObservable.notifyObservers(this);
  23645. var engine = this.getScene().getEngine();
  23646. // Draw order
  23647. switch (fillMode) {
  23648. case BABYLON.Material.PointFillMode:
  23649. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23650. break;
  23651. case BABYLON.Material.WireFrameFillMode:
  23652. if (this._unIndexed) {
  23653. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23654. }
  23655. else {
  23656. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23657. }
  23658. break;
  23659. default:
  23660. if (this._unIndexed) {
  23661. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23662. }
  23663. else {
  23664. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23665. }
  23666. }
  23667. return this;
  23668. };
  23669. /**
  23670. * Registers for this mesh a javascript function called just before the rendering process.
  23671. * This function is passed the current mesh.
  23672. * Return the Mesh.
  23673. */
  23674. Mesh.prototype.registerBeforeRender = function (func) {
  23675. this.onBeforeRenderObservable.add(func);
  23676. return this;
  23677. };
  23678. /**
  23679. * Disposes a previously registered javascript function called before the rendering.
  23680. * This function is passed the current mesh.
  23681. * Returns the Mesh.
  23682. */
  23683. Mesh.prototype.unregisterBeforeRender = function (func) {
  23684. this.onBeforeRenderObservable.removeCallback(func);
  23685. return this;
  23686. };
  23687. /**
  23688. * Registers for this mesh a javascript function called just after the rendering is complete.
  23689. * This function is passed the current mesh.
  23690. * Returns the Mesh.
  23691. */
  23692. Mesh.prototype.registerAfterRender = function (func) {
  23693. this.onAfterRenderObservable.add(func);
  23694. return this;
  23695. };
  23696. /**
  23697. * Disposes a previously registered javascript function called after the rendering.
  23698. * This function is passed the current mesh.
  23699. * Return the Mesh.
  23700. */
  23701. Mesh.prototype.unregisterAfterRender = function (func) {
  23702. this.onAfterRenderObservable.removeCallback(func);
  23703. return this;
  23704. };
  23705. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23706. var scene = this.getScene();
  23707. this._batchCache.mustReturn = false;
  23708. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23709. this._batchCache.visibleInstances[subMeshId] = null;
  23710. if (this._visibleInstances) {
  23711. var currentRenderId = scene.getRenderId();
  23712. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23713. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23714. var selfRenderId = this._renderId;
  23715. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23716. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23717. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23718. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23719. }
  23720. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23721. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23722. this._batchCache.mustReturn = true;
  23723. return this._batchCache;
  23724. }
  23725. if (currentRenderId !== selfRenderId) {
  23726. this._batchCache.renderSelf[subMeshId] = false;
  23727. }
  23728. }
  23729. this._renderIdForInstances[subMeshId] = currentRenderId;
  23730. }
  23731. return this._batchCache;
  23732. };
  23733. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23734. var visibleInstances = batch.visibleInstances[subMesh._id];
  23735. var matricesCount = visibleInstances.length + 1;
  23736. var bufferSize = matricesCount * 16 * 4;
  23737. var currentInstancesBufferSize = this._instancesBufferSize;
  23738. var instancesBuffer = this._instancesBuffer;
  23739. while (this._instancesBufferSize < bufferSize) {
  23740. this._instancesBufferSize *= 2;
  23741. }
  23742. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23743. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23744. }
  23745. var offset = 0;
  23746. var instancesCount = 0;
  23747. var world = this.getWorldMatrix();
  23748. if (batch.renderSelf[subMesh._id]) {
  23749. world.copyToArray(this._instancesData, offset);
  23750. offset += 16;
  23751. instancesCount++;
  23752. }
  23753. if (visibleInstances) {
  23754. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23755. var instance = visibleInstances[instanceIndex];
  23756. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23757. offset += 16;
  23758. instancesCount++;
  23759. }
  23760. }
  23761. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23762. if (instancesBuffer) {
  23763. instancesBuffer.dispose();
  23764. }
  23765. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23766. this._instancesBuffer = instancesBuffer;
  23767. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23768. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23769. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23770. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23771. }
  23772. else {
  23773. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23774. }
  23775. this.geometry._bind(effect);
  23776. this._draw(subMesh, fillMode, instancesCount);
  23777. engine.unbindInstanceAttributes();
  23778. return this;
  23779. };
  23780. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23781. var scene = this.getScene();
  23782. var engine = scene.getEngine();
  23783. if (hardwareInstancedRendering) {
  23784. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23785. }
  23786. else {
  23787. if (batch.renderSelf[subMesh._id]) {
  23788. // Draw
  23789. if (onBeforeDraw) {
  23790. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23791. }
  23792. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23793. }
  23794. if (batch.visibleInstances[subMesh._id]) {
  23795. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23796. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23797. // World
  23798. var world = instance.getWorldMatrix();
  23799. if (onBeforeDraw) {
  23800. onBeforeDraw(true, world, effectiveMaterial);
  23801. }
  23802. // Draw
  23803. this._draw(subMesh, fillMode);
  23804. }
  23805. }
  23806. }
  23807. return this;
  23808. };
  23809. /**
  23810. * Triggers the draw call for the mesh.
  23811. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23812. * Returns the Mesh.
  23813. */
  23814. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23815. var scene = this.getScene();
  23816. // Managing instances
  23817. var batch = this._getInstancesRenderList(subMesh._id);
  23818. if (batch.mustReturn) {
  23819. return this;
  23820. }
  23821. // Checking geometry state
  23822. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23823. return this;
  23824. }
  23825. var callbackIndex;
  23826. this.onBeforeRenderObservable.notifyObservers(this);
  23827. var engine = scene.getEngine();
  23828. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23829. // Material
  23830. var effectiveMaterial = subMesh.getMaterial();
  23831. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23832. return this;
  23833. }
  23834. // Outline - step 1
  23835. var savedDepthWrite = engine.getDepthWrite();
  23836. if (this.renderOutline) {
  23837. engine.setDepthWrite(false);
  23838. scene.getOutlineRenderer().render(subMesh, batch);
  23839. engine.setDepthWrite(savedDepthWrite);
  23840. }
  23841. effectiveMaterial._preBind();
  23842. var effect = effectiveMaterial.getEffect();
  23843. // Bind
  23844. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23845. this._bind(subMesh, effect, fillMode);
  23846. var world = this.getWorldMatrix();
  23847. effectiveMaterial.bind(world, this);
  23848. // Alpha mode
  23849. if (enableAlphaMode) {
  23850. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23851. }
  23852. // Draw
  23853. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23854. // Unbind
  23855. effectiveMaterial.unbind();
  23856. // Outline - step 2
  23857. if (this.renderOutline && savedDepthWrite) {
  23858. engine.setDepthWrite(true);
  23859. engine.setColorWrite(false);
  23860. scene.getOutlineRenderer().render(subMesh, batch);
  23861. engine.setColorWrite(true);
  23862. }
  23863. // Overlay
  23864. if (this.renderOverlay) {
  23865. var currentMode = engine.getAlphaMode();
  23866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23867. scene.getOutlineRenderer().render(subMesh, batch, true);
  23868. engine.setAlphaMode(currentMode);
  23869. }
  23870. this.onAfterRenderObservable.notifyObservers(this);
  23871. return this;
  23872. };
  23873. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23874. if (isInstance) {
  23875. effectiveMaterial.bindOnlyWorldMatrix(world);
  23876. }
  23877. return this;
  23878. };
  23879. /**
  23880. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23881. */
  23882. Mesh.prototype.getEmittedParticleSystems = function () {
  23883. var results = new Array();
  23884. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23885. var particleSystem = this.getScene().particleSystems[index];
  23886. if (particleSystem.emitter === this) {
  23887. results.push(particleSystem);
  23888. }
  23889. }
  23890. return results;
  23891. };
  23892. /**
  23893. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23894. */
  23895. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23896. var results = new Array();
  23897. var descendants = this.getDescendants();
  23898. descendants.push(this);
  23899. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23900. var particleSystem = this.getScene().particleSystems[index];
  23901. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23902. results.push(particleSystem);
  23903. }
  23904. }
  23905. return results;
  23906. };
  23907. Mesh.prototype._checkDelayState = function () {
  23908. var scene = this.getScene();
  23909. if (this._geometry) {
  23910. this._geometry.load(scene);
  23911. }
  23912. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23914. this._queueLoad(this, scene);
  23915. }
  23916. return this;
  23917. };
  23918. Mesh.prototype._queueLoad = function (mesh, scene) {
  23919. var _this = this;
  23920. scene._addPendingData(mesh);
  23921. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23922. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23923. if (data instanceof ArrayBuffer) {
  23924. _this._delayLoadingFunction(data, _this);
  23925. }
  23926. else {
  23927. _this._delayLoadingFunction(JSON.parse(data), _this);
  23928. }
  23929. _this.instances.forEach(function (instance) {
  23930. instance._syncSubMeshes();
  23931. });
  23932. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23933. scene._removePendingData(_this);
  23934. }, function () { }, scene.database, getBinaryData);
  23935. return this;
  23936. };
  23937. /**
  23938. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23939. */
  23940. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23941. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23942. return false;
  23943. }
  23944. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23945. return false;
  23946. }
  23947. this._checkDelayState();
  23948. return true;
  23949. };
  23950. /**
  23951. * Sets the mesh material by the material or multiMaterial `id` property.
  23952. * The material `id` is a string identifying the material or the multiMaterial.
  23953. * This method returns the Mesh.
  23954. */
  23955. Mesh.prototype.setMaterialByID = function (id) {
  23956. var materials = this.getScene().materials;
  23957. var index;
  23958. for (index = 0; index < materials.length; index++) {
  23959. if (materials[index].id === id) {
  23960. this.material = materials[index];
  23961. return this;
  23962. }
  23963. }
  23964. // Multi
  23965. var multiMaterials = this.getScene().multiMaterials;
  23966. for (index = 0; index < multiMaterials.length; index++) {
  23967. if (multiMaterials[index].id === id) {
  23968. this.material = multiMaterials[index];
  23969. return this;
  23970. }
  23971. }
  23972. return this;
  23973. };
  23974. /**
  23975. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23976. */
  23977. Mesh.prototype.getAnimatables = function () {
  23978. var results = [];
  23979. if (this.material) {
  23980. results.push(this.material);
  23981. }
  23982. if (this.skeleton) {
  23983. results.push(this.skeleton);
  23984. }
  23985. return results;
  23986. };
  23987. /**
  23988. * Modifies the mesh geometry according to the passed transformation matrix.
  23989. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23990. * The mesh normals are modified accordingly the same transformation.
  23991. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23992. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23993. * Returns the Mesh.
  23994. */
  23995. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23996. // Position
  23997. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23998. return this;
  23999. }
  24000. var submeshes = this.subMeshes.splice(0);
  24001. this._resetPointsArrayCache();
  24002. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24003. var temp = [];
  24004. var index;
  24005. for (index = 0; index < data.length; index += 3) {
  24006. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24007. }
  24008. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24009. // Normals
  24010. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24011. return this;
  24012. }
  24013. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24014. temp = [];
  24015. for (index = 0; index < data.length; index += 3) {
  24016. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24017. }
  24018. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24019. // flip faces?
  24020. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24021. this.flipFaces();
  24022. }
  24023. // Restore submeshes
  24024. this.releaseSubMeshes();
  24025. this.subMeshes = submeshes;
  24026. return this;
  24027. };
  24028. /**
  24029. * Modifies the mesh geometry according to its own current World Matrix.
  24030. * The mesh World Matrix is then reset.
  24031. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24032. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24033. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24034. * Returns the Mesh.
  24035. */
  24036. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24037. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24038. this.scaling.copyFromFloats(1, 1, 1);
  24039. this.position.copyFromFloats(0, 0, 0);
  24040. this.rotation.copyFromFloats(0, 0, 0);
  24041. //only if quaternion is already set
  24042. if (this.rotationQuaternion) {
  24043. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24044. }
  24045. this._worldMatrix = BABYLON.Matrix.Identity();
  24046. return this;
  24047. };
  24048. // Cache
  24049. Mesh.prototype._resetPointsArrayCache = function () {
  24050. this._positions = null;
  24051. return this;
  24052. };
  24053. Mesh.prototype._generatePointsArray = function () {
  24054. if (this._positions)
  24055. return true;
  24056. this._positions = [];
  24057. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24058. if (!data) {
  24059. return false;
  24060. }
  24061. for (var index = 0; index < data.length; index += 3) {
  24062. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  24063. }
  24064. return true;
  24065. };
  24066. /**
  24067. * Returns a new Mesh object generated from the current mesh properties.
  24068. * This method must not get confused with createInstance().
  24069. * The parameter `name` is a string, the name given to the new mesh.
  24070. * The optional parameter `newParent` can be any Node object (default `null`).
  24071. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24072. * 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.
  24073. */
  24074. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24075. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24076. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24077. };
  24078. /**
  24079. * Disposes the mesh.
  24080. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24081. */
  24082. Mesh.prototype.dispose = function (doNotRecurse) {
  24083. var _this = this;
  24084. if (this._geometry) {
  24085. this._geometry.releaseForMesh(this, true);
  24086. }
  24087. // Sources
  24088. var meshes = this.getScene().meshes;
  24089. meshes.forEach(function (mesh) {
  24090. if (mesh._source && mesh._source === _this) {
  24091. mesh._source = null;
  24092. }
  24093. });
  24094. this._source = null;
  24095. // Instances
  24096. if (this._instancesBuffer) {
  24097. this._instancesBuffer.dispose();
  24098. this._instancesBuffer = null;
  24099. }
  24100. while (this.instances.length) {
  24101. this.instances[0].dispose();
  24102. }
  24103. // Highlight layers.
  24104. var highlightLayers = this.getScene().highlightLayers;
  24105. for (var i = 0; i < highlightLayers.length; i++) {
  24106. var highlightLayer = highlightLayers[i];
  24107. if (highlightLayer) {
  24108. highlightLayer.removeMesh(this);
  24109. highlightLayer.removeExcludedMesh(this);
  24110. }
  24111. }
  24112. _super.prototype.dispose.call(this, doNotRecurse);
  24113. };
  24114. /**
  24115. * Modifies the mesh geometry according to a displacement map.
  24116. * 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.
  24117. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24118. * This method returns nothing.
  24119. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24120. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24121. * 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.
  24122. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24123. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24124. *
  24125. * Returns the Mesh.
  24126. */
  24127. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24128. var _this = this;
  24129. var scene = this.getScene();
  24130. var onload = function (img) {
  24131. // Getting height map data
  24132. var canvas = document.createElement("canvas");
  24133. var context = canvas.getContext("2d");
  24134. var heightMapWidth = img.width;
  24135. var heightMapHeight = img.height;
  24136. canvas.width = heightMapWidth;
  24137. canvas.height = heightMapHeight;
  24138. context.drawImage(img, 0, 0);
  24139. // Create VertexData from map data
  24140. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24141. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24142. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24143. //execute success callback, if set
  24144. if (onSuccess) {
  24145. onSuccess(_this);
  24146. }
  24147. };
  24148. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24149. return this;
  24150. };
  24151. /**
  24152. * Modifies the mesh geometry according to a displacementMap buffer.
  24153. * 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.
  24154. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24155. * This method returns nothing.
  24156. * 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.
  24157. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24158. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24159. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24160. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24161. *
  24162. * Returns the Mesh.
  24163. */
  24164. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24165. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24166. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24167. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24168. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24169. return this;
  24170. }
  24171. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24172. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24173. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24174. var position = BABYLON.Vector3.Zero();
  24175. var normal = BABYLON.Vector3.Zero();
  24176. var uv = BABYLON.Vector2.Zero();
  24177. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24178. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24179. for (var index = 0; index < positions.length; index += 3) {
  24180. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24181. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24182. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24183. // Compute height
  24184. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24185. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24186. var pos = (u + v * heightMapWidth) * 4;
  24187. var r = buffer[pos] / 255.0;
  24188. var g = buffer[pos + 1] / 255.0;
  24189. var b = buffer[pos + 2] / 255.0;
  24190. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24191. normal.normalize();
  24192. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24193. position = position.add(normal);
  24194. position.toArray(positions, index);
  24195. }
  24196. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24197. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24198. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24199. return this;
  24200. };
  24201. /**
  24202. * Modify the mesh to get a flat shading rendering.
  24203. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24204. * This method returns the Mesh.
  24205. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24206. */
  24207. Mesh.prototype.convertToFlatShadedMesh = function () {
  24208. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24209. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24210. var kinds = this.getVerticesDataKinds();
  24211. var vbs = [];
  24212. var data = [];
  24213. var newdata = [];
  24214. var updatableNormals = false;
  24215. var kindIndex;
  24216. var kind;
  24217. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24218. kind = kinds[kindIndex];
  24219. var vertexBuffer = this.getVertexBuffer(kind);
  24220. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24221. updatableNormals = vertexBuffer.isUpdatable();
  24222. kinds.splice(kindIndex, 1);
  24223. kindIndex--;
  24224. continue;
  24225. }
  24226. vbs[kind] = vertexBuffer;
  24227. data[kind] = vbs[kind].getData();
  24228. newdata[kind] = [];
  24229. }
  24230. // Save previous submeshes
  24231. var previousSubmeshes = this.subMeshes.slice(0);
  24232. var indices = this.getIndices();
  24233. var totalIndices = this.getTotalIndices();
  24234. // Generating unique vertices per face
  24235. var index;
  24236. for (index = 0; index < totalIndices; index++) {
  24237. var vertexIndex = indices[index];
  24238. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24239. kind = kinds[kindIndex];
  24240. var stride = vbs[kind].getStrideSize();
  24241. for (var offset = 0; offset < stride; offset++) {
  24242. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24243. }
  24244. }
  24245. }
  24246. // Updating faces & normal
  24247. var normals = [];
  24248. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24249. for (index = 0; index < totalIndices; index += 3) {
  24250. indices[index] = index;
  24251. indices[index + 1] = index + 1;
  24252. indices[index + 2] = index + 2;
  24253. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24254. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24255. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24256. var p1p2 = p1.subtract(p2);
  24257. var p3p2 = p3.subtract(p2);
  24258. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24259. // Store same normals for every vertex
  24260. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24261. normals.push(normal.x);
  24262. normals.push(normal.y);
  24263. normals.push(normal.z);
  24264. }
  24265. }
  24266. this.setIndices(indices);
  24267. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24268. // Updating vertex buffers
  24269. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24270. kind = kinds[kindIndex];
  24271. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24272. }
  24273. // Updating submeshes
  24274. this.releaseSubMeshes();
  24275. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24276. var previousOne = previousSubmeshes[submeshIndex];
  24277. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24278. }
  24279. this.synchronizeInstances();
  24280. return this;
  24281. };
  24282. /**
  24283. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24284. * In other words, more vertices, no more indices and a single bigger VBO.
  24285. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24286. * Returns the Mesh.
  24287. */
  24288. Mesh.prototype.convertToUnIndexedMesh = function () {
  24289. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24290. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24291. var kinds = this.getVerticesDataKinds();
  24292. var vbs = [];
  24293. var data = [];
  24294. var newdata = [];
  24295. var updatableNormals = false;
  24296. var kindIndex;
  24297. var kind;
  24298. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24299. kind = kinds[kindIndex];
  24300. var vertexBuffer = this.getVertexBuffer(kind);
  24301. vbs[kind] = vertexBuffer;
  24302. data[kind] = vbs[kind].getData();
  24303. newdata[kind] = [];
  24304. }
  24305. // Save previous submeshes
  24306. var previousSubmeshes = this.subMeshes.slice(0);
  24307. var indices = this.getIndices();
  24308. var totalIndices = this.getTotalIndices();
  24309. // Generating unique vertices per face
  24310. var index;
  24311. for (index = 0; index < totalIndices; index++) {
  24312. var vertexIndex = indices[index];
  24313. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24314. kind = kinds[kindIndex];
  24315. var stride = vbs[kind].getStrideSize();
  24316. for (var offset = 0; offset < stride; offset++) {
  24317. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24318. }
  24319. }
  24320. }
  24321. // Updating indices
  24322. for (index = 0; index < totalIndices; index += 3) {
  24323. indices[index] = index;
  24324. indices[index + 1] = index + 1;
  24325. indices[index + 2] = index + 2;
  24326. }
  24327. this.setIndices(indices);
  24328. // Updating vertex buffers
  24329. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24330. kind = kinds[kindIndex];
  24331. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24332. }
  24333. // Updating submeshes
  24334. this.releaseSubMeshes();
  24335. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24336. var previousOne = previousSubmeshes[submeshIndex];
  24337. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24338. }
  24339. this._unIndexed = true;
  24340. this.synchronizeInstances();
  24341. return this;
  24342. };
  24343. /**
  24344. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24345. * This method returns the Mesh.
  24346. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24347. */
  24348. Mesh.prototype.flipFaces = function (flipNormals) {
  24349. if (flipNormals === void 0) { flipNormals = false; }
  24350. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24351. var i;
  24352. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24353. for (i = 0; i < vertex_data.normals.length; i++) {
  24354. vertex_data.normals[i] *= -1;
  24355. }
  24356. }
  24357. var temp;
  24358. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24359. // reassign indices
  24360. temp = vertex_data.indices[i + 1];
  24361. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24362. vertex_data.indices[i + 2] = temp;
  24363. }
  24364. vertex_data.applyToMesh(this);
  24365. return this;
  24366. };
  24367. // Instances
  24368. /**
  24369. * Creates a new InstancedMesh object from the mesh model.
  24370. * An instance shares the same properties and the same material than its model.
  24371. * Only these properties of each instance can then be set individually :
  24372. * - position
  24373. * - rotation
  24374. * - rotationQuaternion
  24375. * - setPivotMatrix
  24376. * - scaling
  24377. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24378. * Warning : this method is not supported for Line mesh and LineSystem
  24379. */
  24380. Mesh.prototype.createInstance = function (name) {
  24381. return new BABYLON.InstancedMesh(name, this);
  24382. };
  24383. /**
  24384. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24385. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24386. * This method returns the Mesh.
  24387. */
  24388. Mesh.prototype.synchronizeInstances = function () {
  24389. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24390. var instance = this.instances[instanceIndex];
  24391. instance._syncSubMeshes();
  24392. }
  24393. return this;
  24394. };
  24395. /**
  24396. * Simplify the mesh according to the given array of settings.
  24397. * Function will return immediately and will simplify async. It returns the Mesh.
  24398. * @param settings a collection of simplification settings.
  24399. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24400. * @param type the type of simplification to run.
  24401. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24402. */
  24403. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24404. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24405. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24406. this.getScene().simplificationQueue.addTask({
  24407. settings: settings,
  24408. parallelProcessing: parallelProcessing,
  24409. mesh: this,
  24410. simplificationType: simplificationType,
  24411. successCallback: successCallback
  24412. });
  24413. return this;
  24414. };
  24415. /**
  24416. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24417. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24418. * This should be used together with the simplification to avoid disappearing triangles.
  24419. * Returns the Mesh.
  24420. * @param successCallback an optional success callback to be called after the optimization finished.
  24421. */
  24422. Mesh.prototype.optimizeIndices = function (successCallback) {
  24423. var _this = this;
  24424. var indices = this.getIndices();
  24425. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24426. var vectorPositions = [];
  24427. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24428. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24429. }
  24430. var dupes = [];
  24431. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24432. var realPos = vectorPositions.length - 1 - iteration;
  24433. var testedPosition = vectorPositions[realPos];
  24434. for (var j = 0; j < realPos; ++j) {
  24435. var againstPosition = vectorPositions[j];
  24436. if (testedPosition.equals(againstPosition)) {
  24437. dupes[realPos] = j;
  24438. break;
  24439. }
  24440. }
  24441. }, function () {
  24442. for (var i = 0; i < indices.length; ++i) {
  24443. indices[i] = dupes[indices[i]] || indices[i];
  24444. }
  24445. //indices are now reordered
  24446. var originalSubMeshes = _this.subMeshes.slice(0);
  24447. _this.setIndices(indices);
  24448. _this.subMeshes = originalSubMeshes;
  24449. if (successCallback) {
  24450. successCallback(_this);
  24451. }
  24452. });
  24453. return this;
  24454. };
  24455. Mesh.prototype.serialize = function (serializationObject) {
  24456. serializationObject.name = this.name;
  24457. serializationObject.id = this.id;
  24458. serializationObject.type = this.getClassName();
  24459. if (BABYLON.Tags.HasTags(this)) {
  24460. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24461. }
  24462. serializationObject.position = this.position.asArray();
  24463. if (this.rotationQuaternion) {
  24464. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24465. }
  24466. else if (this.rotation) {
  24467. serializationObject.rotation = this.rotation.asArray();
  24468. }
  24469. serializationObject.scaling = this.scaling.asArray();
  24470. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24471. serializationObject.isEnabled = this.isEnabled();
  24472. serializationObject.isVisible = this.isVisible;
  24473. serializationObject.infiniteDistance = this.infiniteDistance;
  24474. serializationObject.pickable = this.isPickable;
  24475. serializationObject.receiveShadows = this.receiveShadows;
  24476. serializationObject.billboardMode = this.billboardMode;
  24477. serializationObject.visibility = this.visibility;
  24478. serializationObject.checkCollisions = this.checkCollisions;
  24479. serializationObject.isBlocker = this.isBlocker;
  24480. // Parent
  24481. if (this.parent) {
  24482. serializationObject.parentId = this.parent.id;
  24483. }
  24484. // Geometry
  24485. var geometry = this._geometry;
  24486. if (geometry) {
  24487. var geometryId = geometry.id;
  24488. serializationObject.geometryId = geometryId;
  24489. // SubMeshes
  24490. serializationObject.subMeshes = [];
  24491. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24492. var subMesh = this.subMeshes[subIndex];
  24493. serializationObject.subMeshes.push({
  24494. materialIndex: subMesh.materialIndex,
  24495. verticesStart: subMesh.verticesStart,
  24496. verticesCount: subMesh.verticesCount,
  24497. indexStart: subMesh.indexStart,
  24498. indexCount: subMesh.indexCount
  24499. });
  24500. }
  24501. }
  24502. // Material
  24503. if (this.material) {
  24504. serializationObject.materialId = this.material.id;
  24505. }
  24506. else {
  24507. this.material = null;
  24508. }
  24509. // Skeleton
  24510. if (this.skeleton) {
  24511. serializationObject.skeletonId = this.skeleton.id;
  24512. }
  24513. // Physics
  24514. //TODO implement correct serialization for physics impostors.
  24515. if (this.getPhysicsImpostor()) {
  24516. var impostor = this.getPhysicsImpostor();
  24517. serializationObject.physicsMass = impostor.getParam("mass");
  24518. serializationObject.physicsFriction = impostor.getParam("friction");
  24519. serializationObject.physicsRestitution = impostor.getParam("mass");
  24520. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24521. }
  24522. // Metadata
  24523. if (this.metadata) {
  24524. serializationObject.metadata = this.metadata;
  24525. }
  24526. // Instances
  24527. serializationObject.instances = [];
  24528. for (var index = 0; index < this.instances.length; index++) {
  24529. var instance = this.instances[index];
  24530. var serializationInstance = {
  24531. name: instance.name,
  24532. position: instance.position.asArray(),
  24533. scaling: instance.scaling.asArray()
  24534. };
  24535. if (instance.rotationQuaternion) {
  24536. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24537. }
  24538. else if (instance.rotation) {
  24539. serializationInstance.rotation = instance.rotation.asArray();
  24540. }
  24541. serializationObject.instances.push(serializationInstance);
  24542. // Animations
  24543. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24544. serializationInstance.ranges = instance.serializeAnimationRanges();
  24545. }
  24546. // Animations
  24547. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24548. serializationObject.ranges = this.serializeAnimationRanges();
  24549. // Layer mask
  24550. serializationObject.layerMask = this.layerMask;
  24551. // Alpha
  24552. serializationObject.alphaIndex = this.alphaIndex;
  24553. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24554. // Overlay
  24555. serializationObject.overlayAlpha = this.overlayAlpha;
  24556. serializationObject.overlayColor = this.overlayColor.asArray();
  24557. serializationObject.renderOverlay = this.renderOverlay;
  24558. // Fog
  24559. serializationObject.applyFog = this.applyFog;
  24560. // Action Manager
  24561. if (this.actionManager) {
  24562. serializationObject.actions = this.actionManager.serialize(this.name);
  24563. }
  24564. };
  24565. // Statics
  24566. /**
  24567. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24568. * The parameter `parsedMesh` is the mesh to be copied.
  24569. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24570. */
  24571. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24572. var mesh;
  24573. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24574. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24575. }
  24576. else {
  24577. mesh = new Mesh(parsedMesh.name, scene);
  24578. }
  24579. mesh.id = parsedMesh.id;
  24580. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24581. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24582. if (parsedMesh.metadata !== undefined) {
  24583. mesh.metadata = parsedMesh.metadata;
  24584. }
  24585. if (parsedMesh.rotationQuaternion) {
  24586. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24587. }
  24588. else if (parsedMesh.rotation) {
  24589. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24590. }
  24591. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24592. if (parsedMesh.localMatrix) {
  24593. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24594. }
  24595. else if (parsedMesh.pivotMatrix) {
  24596. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24597. }
  24598. mesh.setEnabled(parsedMesh.isEnabled);
  24599. mesh.isVisible = parsedMesh.isVisible;
  24600. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24601. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24602. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24603. if (parsedMesh.applyFog !== undefined) {
  24604. mesh.applyFog = parsedMesh.applyFog;
  24605. }
  24606. if (parsedMesh.pickable !== undefined) {
  24607. mesh.isPickable = parsedMesh.pickable;
  24608. }
  24609. if (parsedMesh.alphaIndex !== undefined) {
  24610. mesh.alphaIndex = parsedMesh.alphaIndex;
  24611. }
  24612. mesh.receiveShadows = parsedMesh.receiveShadows;
  24613. mesh.billboardMode = parsedMesh.billboardMode;
  24614. if (parsedMesh.visibility !== undefined) {
  24615. mesh.visibility = parsedMesh.visibility;
  24616. }
  24617. mesh.checkCollisions = parsedMesh.checkCollisions;
  24618. if (parsedMesh.isBlocker !== undefined) {
  24619. mesh.isBlocker = parsedMesh.isBlocker;
  24620. }
  24621. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24622. // freezeWorldMatrix
  24623. if (parsedMesh.freezeWorldMatrix) {
  24624. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24625. }
  24626. // Parent
  24627. if (parsedMesh.parentId) {
  24628. mesh._waitingParentId = parsedMesh.parentId;
  24629. }
  24630. // Actions
  24631. if (parsedMesh.actions !== undefined) {
  24632. mesh._waitingActions = parsedMesh.actions;
  24633. }
  24634. // Overlay
  24635. if (parsedMesh.overlayAlpha !== undefined) {
  24636. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24637. }
  24638. if (parsedMesh.overlayColor !== undefined) {
  24639. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24640. }
  24641. if (parsedMesh.renderOverlay !== undefined) {
  24642. mesh.renderOverlay = parsedMesh.renderOverlay;
  24643. }
  24644. // Geometry
  24645. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24646. if (parsedMesh.delayLoadingFile) {
  24647. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24648. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24649. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24650. if (parsedMesh._binaryInfo) {
  24651. mesh._binaryInfo = parsedMesh._binaryInfo;
  24652. }
  24653. mesh._delayInfo = [];
  24654. if (parsedMesh.hasUVs) {
  24655. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24656. }
  24657. if (parsedMesh.hasUVs2) {
  24658. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24659. }
  24660. if (parsedMesh.hasUVs3) {
  24661. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24662. }
  24663. if (parsedMesh.hasUVs4) {
  24664. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24665. }
  24666. if (parsedMesh.hasUVs5) {
  24667. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24668. }
  24669. if (parsedMesh.hasUVs6) {
  24670. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24671. }
  24672. if (parsedMesh.hasColors) {
  24673. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24674. }
  24675. if (parsedMesh.hasMatricesIndices) {
  24676. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24677. }
  24678. if (parsedMesh.hasMatricesWeights) {
  24679. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24680. }
  24681. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24682. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24683. mesh._checkDelayState();
  24684. }
  24685. }
  24686. else {
  24687. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24688. }
  24689. // Material
  24690. if (parsedMesh.materialId) {
  24691. mesh.setMaterialByID(parsedMesh.materialId);
  24692. }
  24693. else {
  24694. mesh.material = null;
  24695. }
  24696. // Skeleton
  24697. if (parsedMesh.skeletonId > -1) {
  24698. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24699. if (parsedMesh.numBoneInfluencers) {
  24700. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24701. }
  24702. }
  24703. // Animations
  24704. if (parsedMesh.animations) {
  24705. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24706. var parsedAnimation = parsedMesh.animations[animationIndex];
  24707. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24708. }
  24709. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24710. }
  24711. if (parsedMesh.autoAnimate) {
  24712. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24713. }
  24714. // Layer Mask
  24715. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24716. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24717. }
  24718. else {
  24719. mesh.layerMask = 0x0FFFFFFF;
  24720. }
  24721. // Physics
  24722. if (parsedMesh.physicsImpostor) {
  24723. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24724. mass: parsedMesh.physicsMass,
  24725. friction: parsedMesh.physicsFriction,
  24726. restitution: parsedMesh.physicsRestitution
  24727. }, scene);
  24728. }
  24729. // Instances
  24730. if (parsedMesh.instances) {
  24731. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24732. var parsedInstance = parsedMesh.instances[index];
  24733. var instance = mesh.createInstance(parsedInstance.name);
  24734. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24735. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24736. if (parsedInstance.parentId) {
  24737. instance._waitingParentId = parsedInstance.parentId;
  24738. }
  24739. if (parsedInstance.rotationQuaternion) {
  24740. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24741. }
  24742. else if (parsedInstance.rotation) {
  24743. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24744. }
  24745. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24746. instance.checkCollisions = mesh.checkCollisions;
  24747. if (parsedMesh.animations) {
  24748. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24749. parsedAnimation = parsedMesh.animations[animationIndex];
  24750. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24751. }
  24752. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24753. }
  24754. }
  24755. }
  24756. return mesh;
  24757. };
  24758. /**
  24759. * Creates a ribbon mesh.
  24760. * Please consider using the same method from the MeshBuilder class instead.
  24761. * 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.
  24762. *
  24763. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24764. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24765. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24766. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24767. * 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.
  24768. * 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.
  24769. * 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
  24770. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24771. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24772. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24773. */
  24774. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24775. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24776. pathArray: pathArray,
  24777. closeArray: closeArray,
  24778. closePath: closePath,
  24779. offset: offset,
  24780. updatable: updatable,
  24781. sideOrientation: sideOrientation,
  24782. instance: instance
  24783. }, scene);
  24784. };
  24785. /**
  24786. * Creates a plane polygonal mesh. By default, this is a disc.
  24787. * Please consider using the same method from the MeshBuilder class instead.
  24788. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24789. * 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.
  24790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24791. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24793. */
  24794. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24795. var options = {
  24796. radius: radius,
  24797. tessellation: tessellation,
  24798. sideOrientation: sideOrientation,
  24799. updatable: updatable
  24800. };
  24801. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24802. };
  24803. /**
  24804. * Creates a box mesh.
  24805. * Please consider using the same method from the MeshBuilder class instead.
  24806. * The parameter `size` sets the size (float) of each box side (default 1).
  24807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24810. */
  24811. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24812. var options = {
  24813. size: size,
  24814. sideOrientation: sideOrientation,
  24815. updatable: updatable
  24816. };
  24817. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24818. };
  24819. /**
  24820. * Creates a sphere mesh.
  24821. * Please consider using the same method from the MeshBuilder class instead.
  24822. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24823. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24825. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24827. */
  24828. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24829. var options = {
  24830. segments: segments,
  24831. diameterX: diameter,
  24832. diameterY: diameter,
  24833. diameterZ: diameter,
  24834. sideOrientation: sideOrientation,
  24835. updatable: updatable
  24836. };
  24837. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24838. };
  24839. /**
  24840. * Creates a cylinder or a cone mesh.
  24841. * Please consider using the same method from the MeshBuilder class instead.
  24842. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24843. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24844. * 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.
  24845. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24846. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24850. */
  24851. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24852. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24853. if (scene !== undefined) {
  24854. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24855. updatable = scene;
  24856. }
  24857. scene = subdivisions;
  24858. subdivisions = 1;
  24859. }
  24860. var options = {
  24861. height: height,
  24862. diameterTop: diameterTop,
  24863. diameterBottom: diameterBottom,
  24864. tessellation: tessellation,
  24865. subdivisions: subdivisions,
  24866. sideOrientation: sideOrientation,
  24867. updatable: updatable
  24868. };
  24869. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24870. };
  24871. // Torus (Code from SharpDX.org)
  24872. /**
  24873. * Creates a torus mesh.
  24874. * Please consider using the same method from the MeshBuilder class instead.
  24875. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24876. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24877. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24881. */
  24882. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24883. var options = {
  24884. diameter: diameter,
  24885. thickness: thickness,
  24886. tessellation: tessellation,
  24887. sideOrientation: sideOrientation,
  24888. updatable: updatable
  24889. };
  24890. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24891. };
  24892. /**
  24893. * Creates a torus knot mesh.
  24894. * Please consider using the same method from the MeshBuilder class instead.
  24895. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24896. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24897. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24898. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24902. */
  24903. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24904. var options = {
  24905. radius: radius,
  24906. tube: tube,
  24907. radialSegments: radialSegments,
  24908. tubularSegments: tubularSegments,
  24909. p: p,
  24910. q: q,
  24911. sideOrientation: sideOrientation,
  24912. updatable: updatable
  24913. };
  24914. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24915. };
  24916. /**
  24917. * Creates a line mesh.
  24918. * Please consider using the same method from the MeshBuilder class instead.
  24919. * 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.
  24920. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24921. * The parameter `points` is an array successive Vector3.
  24922. * 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
  24923. * When updating an instance, remember that only point positions can change, not the number of points.
  24924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24925. */
  24926. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24927. var options = {
  24928. points: points,
  24929. updatable: updatable,
  24930. instance: instance
  24931. };
  24932. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24933. };
  24934. /**
  24935. * Creates a dashed line mesh.
  24936. * Please consider using the same method from the MeshBuilder class instead.
  24937. * 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.
  24938. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24939. * The parameter `points` is an array successive Vector3.
  24940. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24941. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24942. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24943. * 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
  24944. * When updating an instance, remember that only point positions can change, not the number of points.
  24945. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24946. */
  24947. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24948. var options = {
  24949. points: points,
  24950. dashSize: dashSize,
  24951. gapSize: gapSize,
  24952. dashNb: dashNb,
  24953. updatable: updatable,
  24954. instance: instance
  24955. };
  24956. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24957. };
  24958. /**
  24959. * Creates an extruded shape mesh.
  24960. * 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.
  24961. * Please consider using the same method from the MeshBuilder class instead.
  24962. *
  24963. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24964. * 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
  24965. * extruded along the Z axis.
  24966. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24967. * 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.
  24968. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24969. * 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
  24970. * 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
  24971. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24975. */
  24976. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24977. var options = {
  24978. shape: shape,
  24979. path: path,
  24980. scale: scale,
  24981. rotation: rotation,
  24982. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24983. sideOrientation: sideOrientation,
  24984. instance: instance,
  24985. updatable: updatable
  24986. };
  24987. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24988. };
  24989. /**
  24990. * Creates an custom extruded shape mesh.
  24991. * 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.
  24992. * Please consider using the same method from the MeshBuilder class instead.
  24993. *
  24994. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24995. * 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
  24996. * extruded along the Z axis.
  24997. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24998. * 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
  24999. * and the distance of this point from the begining of the path :
  25000. * ```javascript
  25001. * var rotationFunction = function(i, distance) {
  25002. * // do things
  25003. * return rotationValue; }
  25004. * ```
  25005. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25006. * 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
  25007. * and the distance of this point from the begining of the path :
  25008. * ```javascript
  25009. * var scaleFunction = function(i, distance) {
  25010. * // do things
  25011. * return scaleValue;}
  25012. * ```
  25013. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25014. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25015. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25016. * 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
  25017. * 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
  25018. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25022. */
  25023. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25024. var options = {
  25025. shape: shape,
  25026. path: path,
  25027. scaleFunction: scaleFunction,
  25028. rotationFunction: rotationFunction,
  25029. ribbonCloseArray: ribbonCloseArray,
  25030. ribbonClosePath: ribbonClosePath,
  25031. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25032. sideOrientation: sideOrientation,
  25033. instance: instance,
  25034. updatable: updatable
  25035. };
  25036. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25037. };
  25038. /**
  25039. * Creates lathe mesh.
  25040. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25041. * Please consider using the same method from the MeshBuilder class instead.
  25042. * 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
  25043. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25044. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25045. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25051. var options = {
  25052. shape: shape,
  25053. radius: radius,
  25054. tessellation: tessellation,
  25055. sideOrientation: sideOrientation,
  25056. updatable: updatable
  25057. };
  25058. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25059. };
  25060. /**
  25061. * Creates a plane mesh.
  25062. * Please consider using the same method from the MeshBuilder class instead.
  25063. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25067. */
  25068. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25069. var options = {
  25070. size: size,
  25071. width: size,
  25072. height: size,
  25073. sideOrientation: sideOrientation,
  25074. updatable: updatable
  25075. };
  25076. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25077. };
  25078. /**
  25079. * Creates a ground mesh.
  25080. * Please consider using the same method from the MeshBuilder class instead.
  25081. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25082. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25084. */
  25085. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25086. var options = {
  25087. width: width,
  25088. height: height,
  25089. subdivisions: subdivisions,
  25090. updatable: updatable
  25091. };
  25092. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25093. };
  25094. /**
  25095. * Creates a tiled ground mesh.
  25096. * Please consider using the same method from the MeshBuilder class instead.
  25097. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25098. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25099. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25100. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25101. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25102. * numbers of subdivisions on the ground width and height of each tile.
  25103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25104. */
  25105. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25106. var options = {
  25107. xmin: xmin,
  25108. zmin: zmin,
  25109. xmax: xmax,
  25110. zmax: zmax,
  25111. subdivisions: subdivisions,
  25112. precision: precision,
  25113. updatable: updatable
  25114. };
  25115. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25116. };
  25117. /**
  25118. * Creates a ground mesh from a height map.
  25119. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25120. * Please consider using the same method from the MeshBuilder class instead.
  25121. * The parameter `url` sets the URL of the height map image resource.
  25122. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25123. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25124. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25125. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25126. * 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).
  25127. * This function is passed the newly built mesh :
  25128. * ```javascript
  25129. * function(mesh) { // do things
  25130. * return; }
  25131. * ```
  25132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25133. */
  25134. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25135. var options = {
  25136. width: width,
  25137. height: height,
  25138. subdivisions: subdivisions,
  25139. minHeight: minHeight,
  25140. maxHeight: maxHeight,
  25141. updatable: updatable,
  25142. onReady: onReady
  25143. };
  25144. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25145. };
  25146. /**
  25147. * Creates a tube mesh.
  25148. * 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.
  25149. * Please consider using the same method from the MeshBuilder class instead.
  25150. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25151. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25152. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25153. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25154. * 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.
  25155. * It must return a radius value (positive float) :
  25156. * ```javascript
  25157. * var radiusFunction = function(i, distance) {
  25158. * // do things
  25159. * return radius; }
  25160. * ```
  25161. * 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
  25162. * 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
  25163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25166. */
  25167. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25168. var options = {
  25169. path: path,
  25170. radius: radius,
  25171. tessellation: tessellation,
  25172. radiusFunction: radiusFunction,
  25173. arc: 1,
  25174. cap: cap,
  25175. updatable: updatable,
  25176. sideOrientation: sideOrientation,
  25177. instance: instance
  25178. };
  25179. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25180. };
  25181. /**
  25182. * Creates a polyhedron mesh.
  25183. * Please consider using the same method from the MeshBuilder class instead.
  25184. * 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
  25185. * to choose the wanted type.
  25186. * The parameter `size` (positive float, default 1) sets the polygon size.
  25187. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25188. * 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`.
  25189. * 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
  25190. * 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)`).
  25191. * 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
  25192. * 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.
  25193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25196. */
  25197. Mesh.CreatePolyhedron = function (name, options, scene) {
  25198. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25199. };
  25200. /**
  25201. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25202. * Please consider using the same method from the MeshBuilder class instead.
  25203. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25204. * 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`).
  25205. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25206. * 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.
  25207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25210. */
  25211. Mesh.CreateIcoSphere = function (name, options, scene) {
  25212. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25213. };
  25214. /**
  25215. * Creates a decal mesh.
  25216. * Please consider using the same method from the MeshBuilder class instead.
  25217. * 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.
  25218. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25219. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25220. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25221. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25222. */
  25223. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25224. var options = {
  25225. position: position,
  25226. normal: normal,
  25227. size: size,
  25228. angle: angle
  25229. };
  25230. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25231. };
  25232. // Skeletons
  25233. /**
  25234. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25235. */
  25236. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25237. var source;
  25238. if (!this._sourcePositions) {
  25239. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25240. this._sourcePositions = new Float32Array(source);
  25241. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25242. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25243. }
  25244. }
  25245. return this._sourcePositions;
  25246. };
  25247. /**
  25248. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25249. */
  25250. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25251. var source;
  25252. if (!this._sourceNormals) {
  25253. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25254. this._sourceNormals = new Float32Array(source);
  25255. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25256. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25257. }
  25258. }
  25259. return this._sourceNormals;
  25260. };
  25261. /**
  25262. * Updates the vertex buffer by applying transformation from the bones.
  25263. * Returns the Mesh.
  25264. *
  25265. * @param {skeleton} skeleton to apply
  25266. */
  25267. Mesh.prototype.applySkeleton = function (skeleton) {
  25268. if (!this.geometry) {
  25269. return this;
  25270. }
  25271. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25272. return this;
  25273. }
  25274. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25276. return this;
  25277. }
  25278. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25279. return this;
  25280. }
  25281. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25282. return this;
  25283. }
  25284. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25285. return this;
  25286. }
  25287. if (!this._sourcePositions) {
  25288. var submeshes = this.subMeshes.slice();
  25289. this.setPositionsForCPUSkinning();
  25290. this.subMeshes = submeshes;
  25291. }
  25292. if (!this._sourceNormals) {
  25293. this.setNormalsForCPUSkinning();
  25294. }
  25295. // positionsData checks for not being Float32Array will only pass at most once
  25296. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25297. if (!(positionsData instanceof Float32Array)) {
  25298. positionsData = new Float32Array(positionsData);
  25299. }
  25300. // normalsData checks for not being Float32Array will only pass at most once
  25301. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25302. if (!(normalsData instanceof Float32Array)) {
  25303. normalsData = new Float32Array(normalsData);
  25304. }
  25305. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25306. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25307. var needExtras = this.numBoneInfluencers > 4;
  25308. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25309. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25310. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25311. var tempVector3 = BABYLON.Vector3.Zero();
  25312. var finalMatrix = new BABYLON.Matrix();
  25313. var tempMatrix = new BABYLON.Matrix();
  25314. var matWeightIdx = 0;
  25315. var inf;
  25316. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25317. var weight;
  25318. for (inf = 0; inf < 4; inf++) {
  25319. weight = matricesWeightsData[matWeightIdx + inf];
  25320. if (weight > 0) {
  25321. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25322. finalMatrix.addToSelf(tempMatrix);
  25323. }
  25324. else
  25325. break;
  25326. }
  25327. if (needExtras) {
  25328. for (inf = 0; inf < 4; inf++) {
  25329. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25330. if (weight > 0) {
  25331. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25332. finalMatrix.addToSelf(tempMatrix);
  25333. }
  25334. else
  25335. break;
  25336. }
  25337. }
  25338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25339. tempVector3.toArray(positionsData, index);
  25340. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25341. tempVector3.toArray(normalsData, index);
  25342. finalMatrix.reset();
  25343. }
  25344. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25345. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25346. return this;
  25347. };
  25348. // Tools
  25349. /**
  25350. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25351. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25352. */
  25353. Mesh.MinMax = function (meshes) {
  25354. var minVector = null;
  25355. var maxVector = null;
  25356. meshes.forEach(function (mesh, index, array) {
  25357. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25358. if (!minVector) {
  25359. minVector = boundingBox.minimumWorld;
  25360. maxVector = boundingBox.maximumWorld;
  25361. }
  25362. else {
  25363. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25364. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25365. }
  25366. });
  25367. return {
  25368. min: minVector,
  25369. max: maxVector
  25370. };
  25371. };
  25372. /**
  25373. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25374. */
  25375. Mesh.Center = function (meshesOrMinMaxVector) {
  25376. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25377. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25378. };
  25379. /**
  25380. * Merge the array of meshes into a single mesh for performance reasons.
  25381. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25382. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25383. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25384. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25385. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25386. */
  25387. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25388. if (disposeSource === void 0) { disposeSource = true; }
  25389. var index;
  25390. if (!allow32BitsIndices) {
  25391. var totalVertices = 0;
  25392. // Counting vertices
  25393. for (index = 0; index < meshes.length; index++) {
  25394. if (meshes[index]) {
  25395. totalVertices += meshes[index].getTotalVertices();
  25396. if (totalVertices > 65536) {
  25397. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25398. return null;
  25399. }
  25400. }
  25401. }
  25402. }
  25403. // Merge
  25404. var vertexData;
  25405. var otherVertexData;
  25406. var indiceArray = new Array();
  25407. var source;
  25408. for (index = 0; index < meshes.length; index++) {
  25409. if (meshes[index]) {
  25410. meshes[index].computeWorldMatrix(true);
  25411. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25412. otherVertexData.transform(meshes[index].getWorldMatrix());
  25413. if (vertexData) {
  25414. vertexData.merge(otherVertexData);
  25415. }
  25416. else {
  25417. vertexData = otherVertexData;
  25418. source = meshes[index];
  25419. }
  25420. if (subdivideWithSubMeshes) {
  25421. indiceArray.push(meshes[index].getTotalIndices());
  25422. }
  25423. }
  25424. }
  25425. if (!meshSubclass) {
  25426. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25427. }
  25428. vertexData.applyToMesh(meshSubclass);
  25429. // Setting properties
  25430. meshSubclass.material = source.material;
  25431. meshSubclass.checkCollisions = source.checkCollisions;
  25432. // Cleaning
  25433. if (disposeSource) {
  25434. for (index = 0; index < meshes.length; index++) {
  25435. if (meshes[index]) {
  25436. meshes[index].dispose();
  25437. }
  25438. }
  25439. }
  25440. // Subdivide
  25441. if (subdivideWithSubMeshes) {
  25442. //-- Suppresions du submesh global
  25443. meshSubclass.releaseSubMeshes();
  25444. index = 0;
  25445. var offset = 0;
  25446. //-- aplique la subdivision en fonction du tableau d'indices
  25447. while (index < indiceArray.length) {
  25448. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25449. offset += indiceArray[index];
  25450. index++;
  25451. }
  25452. }
  25453. return meshSubclass;
  25454. };
  25455. return Mesh;
  25456. }(BABYLON.AbstractMesh));
  25457. // Consts
  25458. Mesh._FRONTSIDE = 0;
  25459. Mesh._BACKSIDE = 1;
  25460. Mesh._DOUBLESIDE = 2;
  25461. Mesh._DEFAULTSIDE = 0;
  25462. Mesh._NO_CAP = 0;
  25463. Mesh._CAP_START = 1;
  25464. Mesh._CAP_END = 2;
  25465. Mesh._CAP_ALL = 3;
  25466. BABYLON.Mesh = Mesh;
  25467. })(BABYLON || (BABYLON = {}));
  25468. //# sourceMappingURL=babylon.mesh.js.map
  25469. var BABYLON;
  25470. (function (BABYLON) {
  25471. var SubMesh = (function () {
  25472. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25473. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25474. this.materialIndex = materialIndex;
  25475. this.verticesStart = verticesStart;
  25476. this.verticesCount = verticesCount;
  25477. this.indexStart = indexStart;
  25478. this.indexCount = indexCount;
  25479. this._renderId = 0;
  25480. this._mesh = mesh;
  25481. this._renderingMesh = renderingMesh || mesh;
  25482. mesh.subMeshes.push(this);
  25483. this._trianglePlanes = [];
  25484. this._id = mesh.subMeshes.length - 1;
  25485. if (createBoundingBox) {
  25486. this.refreshBoundingInfo();
  25487. mesh.computeWorldMatrix(true);
  25488. }
  25489. }
  25490. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25491. get: function () {
  25492. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25493. },
  25494. enumerable: true,
  25495. configurable: true
  25496. });
  25497. /**
  25498. * Returns the submesh BoudingInfo object.
  25499. */
  25500. SubMesh.prototype.getBoundingInfo = function () {
  25501. if (this.IsGlobal) {
  25502. return this._mesh.getBoundingInfo();
  25503. }
  25504. return this._boundingInfo;
  25505. };
  25506. /**
  25507. * Sets the submesh BoundingInfo.
  25508. * Return the SubMesh.
  25509. */
  25510. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25511. this._boundingInfo = boundingInfo;
  25512. return this;
  25513. };
  25514. /**
  25515. * Returns the mesh of the current submesh.
  25516. */
  25517. SubMesh.prototype.getMesh = function () {
  25518. return this._mesh;
  25519. };
  25520. /**
  25521. * Returns the rendering mesh of the submesh.
  25522. */
  25523. SubMesh.prototype.getRenderingMesh = function () {
  25524. return this._renderingMesh;
  25525. };
  25526. /**
  25527. * Returns the submesh material.
  25528. */
  25529. SubMesh.prototype.getMaterial = function () {
  25530. var rootMaterial = this._renderingMesh.material;
  25531. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25532. var multiMaterial = rootMaterial;
  25533. return multiMaterial.getSubMaterial(this.materialIndex);
  25534. }
  25535. if (!rootMaterial) {
  25536. return this._mesh.getScene().defaultMaterial;
  25537. }
  25538. return rootMaterial;
  25539. };
  25540. // Methods
  25541. /**
  25542. * Sets a new updated BoundingInfo object to the submesh.
  25543. * Returns the SubMesh.
  25544. */
  25545. SubMesh.prototype.refreshBoundingInfo = function () {
  25546. this._lastColliderWorldVertices = null;
  25547. if (this.IsGlobal) {
  25548. return;
  25549. }
  25550. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25551. if (!data) {
  25552. this._boundingInfo = this._mesh._boundingInfo;
  25553. return;
  25554. }
  25555. var indices = this._renderingMesh.getIndices();
  25556. var extend;
  25557. //is this the only submesh?
  25558. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25559. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25560. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25561. }
  25562. else {
  25563. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25564. }
  25565. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25566. return this;
  25567. };
  25568. SubMesh.prototype._checkCollision = function (collider) {
  25569. return this.getBoundingInfo()._checkCollision(collider);
  25570. };
  25571. /**
  25572. * Updates the submesh BoundingInfo.
  25573. * Returns the Submesh.
  25574. */
  25575. SubMesh.prototype.updateBoundingInfo = function (world) {
  25576. if (!this.getBoundingInfo()) {
  25577. this.refreshBoundingInfo();
  25578. }
  25579. this.getBoundingInfo().update(world);
  25580. return this;
  25581. };
  25582. /**
  25583. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25584. * Boolean returned.
  25585. */
  25586. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25587. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25588. };
  25589. /**
  25590. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25591. * Boolean returned.
  25592. */
  25593. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25594. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25595. };
  25596. /**
  25597. * Renders the submesh.
  25598. * Returns it.
  25599. */
  25600. SubMesh.prototype.render = function (enableAlphaMode) {
  25601. this._renderingMesh.render(this, enableAlphaMode);
  25602. return this;
  25603. };
  25604. /**
  25605. * Returns a new Index Buffer.
  25606. * Type returned : WebGLBuffer.
  25607. */
  25608. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25609. if (!this._linesIndexBuffer) {
  25610. var linesIndices = [];
  25611. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25612. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25613. }
  25614. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25615. this.linesIndexCount = linesIndices.length;
  25616. }
  25617. return this._linesIndexBuffer;
  25618. };
  25619. /**
  25620. * True is the passed Ray intersects the submesh bounding box.
  25621. * Boolean returned.
  25622. */
  25623. SubMesh.prototype.canIntersects = function (ray) {
  25624. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25625. };
  25626. /**
  25627. * Returns an object IntersectionInfo.
  25628. */
  25629. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25630. var intersectInfo = null;
  25631. // LineMesh first as it's also a Mesh...
  25632. if (this._mesh instanceof BABYLON.LinesMesh) {
  25633. var lineMesh = this._mesh;
  25634. // Line test
  25635. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25636. var p0 = positions[indices[index]];
  25637. var p1 = positions[indices[index + 1]];
  25638. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25639. if (length < 0) {
  25640. continue;
  25641. }
  25642. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25643. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25644. if (fastCheck) {
  25645. break;
  25646. }
  25647. }
  25648. }
  25649. }
  25650. else {
  25651. // Triangles test
  25652. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25653. var p0 = positions[indices[index]];
  25654. var p1 = positions[indices[index + 1]];
  25655. var p2 = positions[indices[index + 2]];
  25656. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25657. if (currentIntersectInfo) {
  25658. if (currentIntersectInfo.distance < 0) {
  25659. continue;
  25660. }
  25661. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25662. intersectInfo = currentIntersectInfo;
  25663. intersectInfo.faceId = index / 3;
  25664. if (fastCheck) {
  25665. break;
  25666. }
  25667. }
  25668. }
  25669. }
  25670. }
  25671. return intersectInfo;
  25672. };
  25673. // Clone
  25674. /**
  25675. * Creates a new Submesh from the passed Mesh.
  25676. */
  25677. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25678. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25679. if (!this.IsGlobal) {
  25680. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25681. }
  25682. return result;
  25683. };
  25684. // Dispose
  25685. /**
  25686. * Disposes the Submesh.
  25687. * Returns nothing.
  25688. */
  25689. SubMesh.prototype.dispose = function () {
  25690. if (this._linesIndexBuffer) {
  25691. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25692. this._linesIndexBuffer = null;
  25693. }
  25694. // Remove from mesh
  25695. var index = this._mesh.subMeshes.indexOf(this);
  25696. this._mesh.subMeshes.splice(index, 1);
  25697. };
  25698. // Statics
  25699. /**
  25700. * Creates a new Submesh from the passed parameters :
  25701. * - materialIndex (integer) : the index of the main mesh material.
  25702. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25703. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25704. * - mesh (Mesh) : the main mesh to create the submesh from.
  25705. * - renderingMesh (optional Mesh) : rendering mesh.
  25706. */
  25707. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25708. var minVertexIndex = Number.MAX_VALUE;
  25709. var maxVertexIndex = -Number.MAX_VALUE;
  25710. renderingMesh = renderingMesh || mesh;
  25711. var indices = renderingMesh.getIndices();
  25712. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25713. var vertexIndex = indices[index];
  25714. if (vertexIndex < minVertexIndex)
  25715. minVertexIndex = vertexIndex;
  25716. if (vertexIndex > maxVertexIndex)
  25717. maxVertexIndex = vertexIndex;
  25718. }
  25719. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25720. };
  25721. return SubMesh;
  25722. }());
  25723. BABYLON.SubMesh = SubMesh;
  25724. })(BABYLON || (BABYLON = {}));
  25725. //# sourceMappingURL=babylon.subMesh.js.map
  25726. var BABYLON;
  25727. (function (BABYLON) {
  25728. var MeshBuilder = (function () {
  25729. function MeshBuilder() {
  25730. }
  25731. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25732. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25733. return BABYLON.Mesh.DOUBLESIDE;
  25734. }
  25735. if (orientation === undefined || orientation === null) {
  25736. return BABYLON.Mesh.FRONTSIDE;
  25737. }
  25738. return orientation;
  25739. };
  25740. /**
  25741. * Creates a box mesh.
  25742. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25743. * The parameter `size` sets the size (float) of each box side (default 1).
  25744. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25745. * 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).
  25746. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25748. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25750. */
  25751. MeshBuilder.CreateBox = function (name, options, scene) {
  25752. var box = new BABYLON.Mesh(name, scene);
  25753. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25754. box.sideOrientation = options.sideOrientation;
  25755. var vertexData = BABYLON.VertexData.CreateBox(options);
  25756. vertexData.applyToMesh(box, options.updatable);
  25757. return box;
  25758. };
  25759. /**
  25760. * Creates a sphere mesh.
  25761. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25762. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25763. * 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`).
  25764. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25765. * 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
  25766. * 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).
  25767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25770. */
  25771. MeshBuilder.CreateSphere = function (name, options, scene) {
  25772. var sphere = new BABYLON.Mesh(name, scene);
  25773. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25774. sphere.sideOrientation = options.sideOrientation;
  25775. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25776. vertexData.applyToMesh(sphere, options.updatable);
  25777. return sphere;
  25778. };
  25779. /**
  25780. * Creates a plane polygonal mesh. By default, this is a disc.
  25781. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25782. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25783. * 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.
  25784. * 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
  25785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25788. */
  25789. MeshBuilder.CreateDisc = function (name, options, scene) {
  25790. var disc = new BABYLON.Mesh(name, scene);
  25791. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25792. disc.sideOrientation = options.sideOrientation;
  25793. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25794. vertexData.applyToMesh(disc, options.updatable);
  25795. return disc;
  25796. };
  25797. /**
  25798. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25800. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25801. * 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`).
  25802. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25803. * 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.
  25804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25807. */
  25808. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25809. var sphere = new BABYLON.Mesh(name, scene);
  25810. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25811. sphere.sideOrientation = options.sideOrientation;
  25812. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25813. vertexData.applyToMesh(sphere, options.updatable);
  25814. return sphere;
  25815. };
  25816. ;
  25817. /**
  25818. * Creates a ribbon mesh.
  25819. * 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.
  25820. *
  25821. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25822. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25823. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25824. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25825. * 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.
  25826. * 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.
  25827. * 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
  25828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25830. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25831. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  25832. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  25833. * 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
  25834. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  25835. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  25836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25837. */
  25838. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25839. var pathArray = options.pathArray;
  25840. var closeArray = options.closeArray;
  25841. var closePath = options.closePath;
  25842. var offset = options.offset;
  25843. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25844. var instance = options.instance;
  25845. var updatable = options.updatable;
  25846. if (instance) {
  25847. // positionFunction : ribbon case
  25848. // only pathArray and sideOrientation parameters are taken into account for positions update
  25849. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25850. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25851. var positionFunction = function (positions) {
  25852. var minlg = pathArray[0].length;
  25853. var i = 0;
  25854. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25855. for (var si = 1; si <= ns; si++) {
  25856. for (var p = 0; p < pathArray.length; p++) {
  25857. var path = pathArray[p];
  25858. var l = path.length;
  25859. minlg = (minlg < l) ? minlg : l;
  25860. var j = 0;
  25861. while (j < minlg) {
  25862. positions[i] = path[j].x;
  25863. positions[i + 1] = path[j].y;
  25864. positions[i + 2] = path[j].z;
  25865. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25866. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25867. }
  25868. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25869. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25870. }
  25871. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25872. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25873. }
  25874. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25875. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25876. }
  25877. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25878. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25879. }
  25880. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25881. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25882. }
  25883. j++;
  25884. i += 3;
  25885. }
  25886. if (instance._closePath) {
  25887. positions[i] = path[0].x;
  25888. positions[i + 1] = path[0].y;
  25889. positions[i + 2] = path[0].z;
  25890. i += 3;
  25891. }
  25892. }
  25893. }
  25894. };
  25895. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25896. positionFunction(positions);
  25897. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25898. instance._boundingInfo.update(instance._worldMatrix);
  25899. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25900. if (options.colors) {
  25901. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25902. for (var c = 0; c < options.colors.length; c++) {
  25903. colors[c * 4] = options.colors[c].r;
  25904. colors[c * 4 + 1] = options.colors[c].g;
  25905. colors[c * 4 + 2] = options.colors[c].b;
  25906. colors[c * 4 + 3] = options.colors[c].a;
  25907. }
  25908. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  25909. }
  25910. if (options.uvs) {
  25911. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25912. for (var i = 0; i < options.uvs.length; i++) {
  25913. uvs[i * 2] = options.uvs[i].x;
  25914. uvs[i * 2 + 1] = options.uvs[i].y;
  25915. }
  25916. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  25917. }
  25918. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25919. var indices = instance.getIndices();
  25920. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25921. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25922. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25923. if (instance._closePath) {
  25924. var indexFirst = 0;
  25925. var indexLast = 0;
  25926. for (var p = 0; p < pathArray.length; p++) {
  25927. indexFirst = instance._idx[p] * 3;
  25928. if (p + 1 < pathArray.length) {
  25929. indexLast = (instance._idx[p + 1] - 1) * 3;
  25930. }
  25931. else {
  25932. indexLast = normals.length - 3;
  25933. }
  25934. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25935. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25936. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25937. normals[indexLast] = normals[indexFirst];
  25938. normals[indexLast + 1] = normals[indexFirst + 1];
  25939. normals[indexLast + 2] = normals[indexFirst + 2];
  25940. }
  25941. }
  25942. if (!(instance.areNormalsFrozen)) {
  25943. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25944. }
  25945. }
  25946. return instance;
  25947. }
  25948. else {
  25949. var ribbon = new BABYLON.Mesh(name, scene);
  25950. ribbon.sideOrientation = sideOrientation;
  25951. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25952. if (closePath) {
  25953. ribbon._idx = vertexData._idx;
  25954. }
  25955. ribbon._closePath = closePath;
  25956. ribbon._closeArray = closeArray;
  25957. vertexData.applyToMesh(ribbon, updatable);
  25958. return ribbon;
  25959. }
  25960. };
  25961. /**
  25962. * Creates a cylinder or a cone mesh.
  25963. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25964. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25965. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25966. * 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.
  25967. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25968. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25969. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25970. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25971. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25972. * 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).
  25973. * 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
  25974. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25975. * 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
  25976. * 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.
  25977. * If `enclose` is false, a ring surface is one element.
  25978. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25979. * 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
  25980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25983. */
  25984. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25985. var cylinder = new BABYLON.Mesh(name, scene);
  25986. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25987. cylinder.sideOrientation = options.sideOrientation;
  25988. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25989. vertexData.applyToMesh(cylinder, options.updatable);
  25990. return cylinder;
  25991. };
  25992. /**
  25993. * Creates a torus mesh.
  25994. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25995. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25996. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25997. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26001. */
  26002. MeshBuilder.CreateTorus = function (name, options, scene) {
  26003. var torus = new BABYLON.Mesh(name, scene);
  26004. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26005. torus.sideOrientation = options.sideOrientation;
  26006. var vertexData = BABYLON.VertexData.CreateTorus(options);
  26007. vertexData.applyToMesh(torus, options.updatable);
  26008. return torus;
  26009. };
  26010. /**
  26011. * Creates a torus knot mesh.
  26012. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  26013. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26014. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26015. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26016. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26020. */
  26021. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  26022. var torusKnot = new BABYLON.Mesh(name, scene);
  26023. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26024. torusKnot.sideOrientation = options.sideOrientation;
  26025. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  26026. vertexData.applyToMesh(torusKnot, options.updatable);
  26027. return torusKnot;
  26028. };
  26029. /**
  26030. * Creates a line system mesh.
  26031. * A line system is a pool of many lines gathered in a single mesh.
  26032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  26033. * 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.
  26034. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  26035. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  26036. * 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
  26037. * 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
  26038. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  26039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26040. */
  26041. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  26042. var instance = options.instance;
  26043. var lines = options.lines;
  26044. if (instance) {
  26045. var positionFunction = function (positions) {
  26046. var i = 0;
  26047. for (var l = 0; l < lines.length; l++) {
  26048. var points = lines[l];
  26049. for (var p = 0; p < points.length; p++) {
  26050. positions[i] = points[p].x;
  26051. positions[i + 1] = points[p].y;
  26052. positions[i + 2] = points[p].z;
  26053. i += 3;
  26054. }
  26055. }
  26056. };
  26057. instance.updateMeshPositions(positionFunction, false);
  26058. return instance;
  26059. }
  26060. // line system creation
  26061. var lineSystem = new BABYLON.LinesMesh(name, scene);
  26062. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  26063. vertexData.applyToMesh(lineSystem, options.updatable);
  26064. return lineSystem;
  26065. };
  26066. /**
  26067. * Creates a line mesh.
  26068. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  26069. * 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.
  26070. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26071. * The parameter `points` is an array successive Vector3.
  26072. * 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
  26073. * When updating an instance, remember that only point positions can change, not the number of points.
  26074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26075. */
  26076. MeshBuilder.CreateLines = function (name, options, scene) {
  26077. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  26078. return lines;
  26079. };
  26080. /**
  26081. * Creates a dashed line mesh.
  26082. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26083. * 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.
  26084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26085. * The parameter `points` is an array successive Vector3.
  26086. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26087. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26088. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26089. * 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
  26090. * When updating an instance, remember that only point positions can change, not the number of points.
  26091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26092. */
  26093. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26094. var points = options.points;
  26095. var instance = options.instance;
  26096. var gapSize = options.gapSize;
  26097. var dashNb = options.dashNb;
  26098. var dashSize = options.dashSize;
  26099. if (instance) {
  26100. var positionFunction = function (positions) {
  26101. var curvect = BABYLON.Vector3.Zero();
  26102. var nbSeg = positions.length / 6;
  26103. var lg = 0;
  26104. var nb = 0;
  26105. var shft = 0;
  26106. var dashshft = 0;
  26107. var curshft = 0;
  26108. var p = 0;
  26109. var i = 0;
  26110. var j = 0;
  26111. for (i = 0; i < points.length - 1; i++) {
  26112. points[i + 1].subtractToRef(points[i], curvect);
  26113. lg += curvect.length();
  26114. }
  26115. shft = lg / nbSeg;
  26116. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26117. for (i = 0; i < points.length - 1; i++) {
  26118. points[i + 1].subtractToRef(points[i], curvect);
  26119. nb = Math.floor(curvect.length() / shft);
  26120. curvect.normalize();
  26121. j = 0;
  26122. while (j < nb && p < positions.length) {
  26123. curshft = shft * j;
  26124. positions[p] = points[i].x + curshft * curvect.x;
  26125. positions[p + 1] = points[i].y + curshft * curvect.y;
  26126. positions[p + 2] = points[i].z + curshft * curvect.z;
  26127. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26128. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26129. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26130. p += 6;
  26131. j++;
  26132. }
  26133. }
  26134. while (p < positions.length) {
  26135. positions[p] = points[i].x;
  26136. positions[p + 1] = points[i].y;
  26137. positions[p + 2] = points[i].z;
  26138. p += 3;
  26139. }
  26140. };
  26141. instance.updateMeshPositions(positionFunction, false);
  26142. return instance;
  26143. }
  26144. // dashed lines creation
  26145. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26146. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26147. vertexData.applyToMesh(dashedLines, options.updatable);
  26148. dashedLines.dashSize = dashSize;
  26149. dashedLines.gapSize = gapSize;
  26150. return dashedLines;
  26151. };
  26152. /**
  26153. * Creates an extruded shape mesh.
  26154. * 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.
  26155. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26156. *
  26157. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26158. * 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
  26159. * extruded along the Z axis.
  26160. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26161. * 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.
  26162. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26163. * 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
  26164. * 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
  26165. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26168. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26170. */
  26171. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26172. var path = options.path;
  26173. var shape = options.shape;
  26174. var scale = options.scale || 1;
  26175. var rotation = options.rotation || 0;
  26176. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26177. var updatable = options.updatable;
  26178. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26179. var instance = options.instance;
  26180. var invertUV = options.invertUV || false;
  26181. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26182. };
  26183. /**
  26184. * Creates an custom extruded shape mesh.
  26185. * 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.
  26186. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26187. *
  26188. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26189. * 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
  26190. * extruded along the Z axis.
  26191. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26192. * 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
  26193. * and the distance of this point from the begining of the path :
  26194. * ```javascript
  26195. * var rotationFunction = function(i, distance) {
  26196. * // do things
  26197. * return rotationValue; }
  26198. * ```
  26199. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26200. * 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
  26201. * and the distance of this point from the begining of the path :
  26202. * ```javascript
  26203. * var scaleFunction = function(i, distance) {
  26204. * // do things
  26205. * return scaleValue;}
  26206. * ```
  26207. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26208. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26209. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26210. * 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
  26211. * 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
  26212. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26215. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26217. */
  26218. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26219. var path = options.path;
  26220. var shape = options.shape;
  26221. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26222. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26223. var ribbonCloseArray = options.ribbonCloseArray || false;
  26224. var ribbonClosePath = options.ribbonClosePath || false;
  26225. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26226. var updatable = options.updatable;
  26227. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26228. var instance = options.instance;
  26229. var invertUV = options.invertUV || false;
  26230. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26231. };
  26232. /**
  26233. * Creates lathe mesh.
  26234. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26235. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26236. *
  26237. * 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
  26238. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26239. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26240. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26241. * 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.
  26242. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26243. * 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
  26244. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26245. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26246. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26248. */
  26249. MeshBuilder.CreateLathe = function (name, options, scene) {
  26250. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26251. var closed = (options.closed === undefined) ? true : options.closed;
  26252. var shape = options.shape;
  26253. var radius = options.radius || 1;
  26254. var tessellation = options.tessellation || 64;
  26255. var updatable = options.updatable;
  26256. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26257. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26258. var pi2 = Math.PI * 2;
  26259. var paths = new Array();
  26260. var invertUV = options.invertUV || false;
  26261. var i = 0;
  26262. var p = 0;
  26263. var step = pi2 / tessellation * arc;
  26264. var rotated;
  26265. var path = new Array();
  26266. ;
  26267. for (i = 0; i <= tessellation; i++) {
  26268. var path = [];
  26269. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26270. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26271. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26272. }
  26273. for (p = 0; p < shape.length; p++) {
  26274. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26275. path.push(rotated);
  26276. }
  26277. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26278. 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));
  26279. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26280. }
  26281. paths.push(path);
  26282. }
  26283. // lathe ribbon
  26284. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26285. return lathe;
  26286. };
  26287. /**
  26288. * Creates a plane mesh.
  26289. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26290. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26291. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26292. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26296. */
  26297. MeshBuilder.CreatePlane = function (name, options, scene) {
  26298. var plane = new BABYLON.Mesh(name, scene);
  26299. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26300. plane.sideOrientation = options.sideOrientation;
  26301. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26302. vertexData.applyToMesh(plane, options.updatable);
  26303. if (options.sourcePlane) {
  26304. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26305. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26306. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26307. plane.rotate(vectorProduct, product);
  26308. }
  26309. return plane;
  26310. };
  26311. /**
  26312. * Creates a ground mesh.
  26313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26314. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26315. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26317. */
  26318. MeshBuilder.CreateGround = function (name, options, scene) {
  26319. var ground = new BABYLON.GroundMesh(name, scene);
  26320. ground._setReady(false);
  26321. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26322. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26323. ground._width = options.width || 1;
  26324. ground._height = options.height || 1;
  26325. ground._maxX = ground._width / 2;
  26326. ground._maxZ = ground._height / 2;
  26327. ground._minX = -ground._maxX;
  26328. ground._minZ = -ground._maxZ;
  26329. var vertexData = BABYLON.VertexData.CreateGround(options);
  26330. vertexData.applyToMesh(ground, options.updatable);
  26331. ground._setReady(true);
  26332. return ground;
  26333. };
  26334. /**
  26335. * Creates a tiled ground mesh.
  26336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26337. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26338. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26339. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26340. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26341. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26342. * numbers of subdivisions on the ground width and height of each tile.
  26343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26344. */
  26345. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26346. var tiledGround = new BABYLON.Mesh(name, scene);
  26347. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26348. vertexData.applyToMesh(tiledGround, options.updatable);
  26349. return tiledGround;
  26350. };
  26351. /**
  26352. * Creates a ground mesh from a height map.
  26353. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26355. * The parameter `url` sets the URL of the height map image resource.
  26356. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26357. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26358. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26359. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26360. * 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.
  26361. * 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).
  26362. * This function is passed the newly built mesh :
  26363. * ```javascript
  26364. * function(mesh) { // do things
  26365. * return; }
  26366. * ```
  26367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26368. */
  26369. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26370. var width = options.width || 10.0;
  26371. var height = options.height || 10.0;
  26372. var subdivisions = options.subdivisions || 1 | 0;
  26373. var minHeight = options.minHeight || 0.0;
  26374. var maxHeight = options.maxHeight || 10.0;
  26375. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26376. var updatable = options.updatable;
  26377. var onReady = options.onReady;
  26378. var ground = new BABYLON.GroundMesh(name, scene);
  26379. ground._subdivisionsX = subdivisions;
  26380. ground._subdivisionsY = subdivisions;
  26381. ground._width = width;
  26382. ground._height = height;
  26383. ground._maxX = ground._width / 2.0;
  26384. ground._maxZ = ground._height / 2.0;
  26385. ground._minX = -ground._maxX;
  26386. ground._minZ = -ground._maxZ;
  26387. ground._setReady(false);
  26388. var onload = function (img) {
  26389. // Getting height map data
  26390. var canvas = document.createElement("canvas");
  26391. var context = canvas.getContext("2d");
  26392. var bufferWidth = img.width;
  26393. var bufferHeight = img.height;
  26394. canvas.width = bufferWidth;
  26395. canvas.height = bufferHeight;
  26396. context.drawImage(img, 0, 0);
  26397. // Create VertexData from map data
  26398. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26399. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26400. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26401. width: width, height: height,
  26402. subdivisions: subdivisions,
  26403. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26404. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26405. });
  26406. vertexData.applyToMesh(ground, updatable);
  26407. ground._setReady(true);
  26408. //execute ready callback, if set
  26409. if (onReady) {
  26410. onReady(ground);
  26411. }
  26412. };
  26413. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26414. return ground;
  26415. };
  26416. /**
  26417. * Creates a tube mesh.
  26418. * 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.
  26419. *
  26420. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26421. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26422. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26423. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26424. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26425. * 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.
  26426. * It must return a radius value (positive float) :
  26427. * ```javascript
  26428. * var radiusFunction = function(i, distance) {
  26429. * // do things
  26430. * return radius; }
  26431. * ```
  26432. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26433. * 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
  26434. * 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
  26435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26437. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26439. */
  26440. MeshBuilder.CreateTube = function (name, options, scene) {
  26441. var path = options.path;
  26442. var radius = options.radius || 1.0;
  26443. var tessellation = options.tessellation || 64 | 0;
  26444. var radiusFunction = options.radiusFunction;
  26445. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26446. var invertUV = options.invertUV || false;
  26447. var updatable = options.updatable;
  26448. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26449. var instance = options.instance;
  26450. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26451. // tube geometry
  26452. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26453. var tangents = path3D.getTangents();
  26454. var normals = path3D.getNormals();
  26455. var distances = path3D.getDistances();
  26456. var pi2 = Math.PI * 2;
  26457. var step = pi2 / tessellation * arc;
  26458. var returnRadius = function () { return radius; };
  26459. var radiusFunctionFinal = radiusFunction || returnRadius;
  26460. var circlePath;
  26461. var rad;
  26462. var normal;
  26463. var rotated;
  26464. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26465. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26466. for (var i = 0; i < path.length; i++) {
  26467. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26468. circlePath = Array(); // current circle array
  26469. normal = normals[i]; // current normal
  26470. for (var t = 0; t < tessellation; t++) {
  26471. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26472. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26473. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26474. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26475. circlePath[t] = rotated;
  26476. }
  26477. circlePaths[index] = circlePath;
  26478. index++;
  26479. }
  26480. // cap
  26481. var capPath = function (nbPoints, pathIndex) {
  26482. var pointCap = Array();
  26483. for (var i = 0; i < nbPoints; i++) {
  26484. pointCap.push(path[pathIndex]);
  26485. }
  26486. return pointCap;
  26487. };
  26488. switch (cap) {
  26489. case BABYLON.Mesh.NO_CAP:
  26490. break;
  26491. case BABYLON.Mesh.CAP_START:
  26492. circlePaths[0] = capPath(tessellation, 0);
  26493. circlePaths[1] = circlePaths[2].slice(0);
  26494. break;
  26495. case BABYLON.Mesh.CAP_END:
  26496. circlePaths[index] = circlePaths[index - 1].slice(0);
  26497. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26498. break;
  26499. case BABYLON.Mesh.CAP_ALL:
  26500. circlePaths[0] = capPath(tessellation, 0);
  26501. circlePaths[1] = circlePaths[2].slice(0);
  26502. circlePaths[index] = circlePaths[index - 1].slice(0);
  26503. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26504. break;
  26505. default:
  26506. break;
  26507. }
  26508. return circlePaths;
  26509. };
  26510. var path3D;
  26511. var pathArray;
  26512. if (instance) {
  26513. var arc = options.arc || instance.arc;
  26514. path3D = (instance.path3D).update(path);
  26515. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26516. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26517. instance.path3D = path3D;
  26518. instance.pathArray = pathArray;
  26519. instance.arc = arc;
  26520. return instance;
  26521. }
  26522. // tube creation
  26523. path3D = new BABYLON.Path3D(path);
  26524. var newPathArray = new Array();
  26525. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26526. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26527. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26528. tube.pathArray = pathArray;
  26529. tube.path3D = path3D;
  26530. tube.tessellation = tessellation;
  26531. tube.cap = cap;
  26532. tube.arc = options.arc;
  26533. return tube;
  26534. };
  26535. /**
  26536. * Creates a polyhedron mesh.
  26537. *
  26538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26539. * 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
  26540. * to choose the wanted type.
  26541. * The parameter `size` (positive float, default 1) sets the polygon size.
  26542. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26543. * 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`.
  26544. * 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
  26545. * 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)`).
  26546. * 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
  26547. * 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.
  26548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26551. */
  26552. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26553. var polyhedron = new BABYLON.Mesh(name, scene);
  26554. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26555. polyhedron.sideOrientation = options.sideOrientation;
  26556. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26557. vertexData.applyToMesh(polyhedron, options.updatable);
  26558. return polyhedron;
  26559. };
  26560. /**
  26561. * Creates a decal mesh.
  26562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26563. * 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.
  26564. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26565. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26566. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26567. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26568. */
  26569. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26570. var indices = sourceMesh.getIndices();
  26571. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26572. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26573. var position = options.position || BABYLON.Vector3.Zero();
  26574. var normal = options.normal || BABYLON.Vector3.Up();
  26575. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26576. var angle = options.angle || 0;
  26577. // Getting correct rotation
  26578. if (!normal) {
  26579. var target = new BABYLON.Vector3(0, 0, 1);
  26580. var camera = sourceMesh.getScene().activeCamera;
  26581. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26582. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26583. }
  26584. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26585. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26586. var pitch = Math.atan2(normal.y, len);
  26587. // Matrix
  26588. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26589. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26590. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26591. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26592. var vertexData = new BABYLON.VertexData();
  26593. vertexData.indices = [];
  26594. vertexData.positions = [];
  26595. vertexData.normals = [];
  26596. vertexData.uvs = [];
  26597. var currentVertexDataIndex = 0;
  26598. var extractDecalVector3 = function (indexId) {
  26599. var vertexId = indices[indexId];
  26600. var result = new BABYLON.PositionNormalVertex();
  26601. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26602. // Send vector to decal local world
  26603. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26604. // Get normal
  26605. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26606. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26607. return result;
  26608. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26609. var clip = function (vertices, axis) {
  26610. if (vertices.length === 0) {
  26611. return vertices;
  26612. }
  26613. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26614. var clipVertices = function (v0, v1) {
  26615. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26616. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26617. };
  26618. var result = new Array();
  26619. for (var index = 0; index < vertices.length; index += 3) {
  26620. var v1Out;
  26621. var v2Out;
  26622. var v3Out;
  26623. var total = 0;
  26624. var nV1, nV2, nV3, nV4;
  26625. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26626. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26627. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26628. v1Out = d1 > 0;
  26629. v2Out = d2 > 0;
  26630. v3Out = d3 > 0;
  26631. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26632. switch (total) {
  26633. case 0:
  26634. result.push(vertices[index]);
  26635. result.push(vertices[index + 1]);
  26636. result.push(vertices[index + 2]);
  26637. break;
  26638. case 1:
  26639. if (v1Out) {
  26640. nV1 = vertices[index + 1];
  26641. nV2 = vertices[index + 2];
  26642. nV3 = clipVertices(vertices[index], nV1);
  26643. nV4 = clipVertices(vertices[index], nV2);
  26644. }
  26645. if (v2Out) {
  26646. nV1 = vertices[index];
  26647. nV2 = vertices[index + 2];
  26648. nV3 = clipVertices(vertices[index + 1], nV1);
  26649. nV4 = clipVertices(vertices[index + 1], nV2);
  26650. result.push(nV3);
  26651. result.push(nV2.clone());
  26652. result.push(nV1.clone());
  26653. result.push(nV2.clone());
  26654. result.push(nV3.clone());
  26655. result.push(nV4);
  26656. break;
  26657. }
  26658. if (v3Out) {
  26659. nV1 = vertices[index];
  26660. nV2 = vertices[index + 1];
  26661. nV3 = clipVertices(vertices[index + 2], nV1);
  26662. nV4 = clipVertices(vertices[index + 2], nV2);
  26663. }
  26664. result.push(nV1.clone());
  26665. result.push(nV2.clone());
  26666. result.push(nV3);
  26667. result.push(nV4);
  26668. result.push(nV3.clone());
  26669. result.push(nV2.clone());
  26670. break;
  26671. case 2:
  26672. if (!v1Out) {
  26673. nV1 = vertices[index].clone();
  26674. nV2 = clipVertices(nV1, vertices[index + 1]);
  26675. nV3 = clipVertices(nV1, vertices[index + 2]);
  26676. result.push(nV1);
  26677. result.push(nV2);
  26678. result.push(nV3);
  26679. }
  26680. if (!v2Out) {
  26681. nV1 = vertices[index + 1].clone();
  26682. nV2 = clipVertices(nV1, vertices[index + 2]);
  26683. nV3 = clipVertices(nV1, vertices[index]);
  26684. result.push(nV1);
  26685. result.push(nV2);
  26686. result.push(nV3);
  26687. }
  26688. if (!v3Out) {
  26689. nV1 = vertices[index + 2].clone();
  26690. nV2 = clipVertices(nV1, vertices[index]);
  26691. nV3 = clipVertices(nV1, vertices[index + 1]);
  26692. result.push(nV1);
  26693. result.push(nV2);
  26694. result.push(nV3);
  26695. }
  26696. break;
  26697. case 3:
  26698. break;
  26699. }
  26700. }
  26701. return result;
  26702. };
  26703. for (var index = 0; index < indices.length; index += 3) {
  26704. var faceVertices = new Array();
  26705. faceVertices.push(extractDecalVector3(index));
  26706. faceVertices.push(extractDecalVector3(index + 1));
  26707. faceVertices.push(extractDecalVector3(index + 2));
  26708. // Clip
  26709. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26710. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26711. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26712. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26713. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26714. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26715. if (faceVertices.length === 0) {
  26716. continue;
  26717. }
  26718. // Add UVs and get back to world
  26719. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26720. var vertex = faceVertices[vIndex];
  26721. //TODO check for Int32Array | Uint32Array | Uint16Array
  26722. vertexData.indices.push(currentVertexDataIndex);
  26723. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26724. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26725. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26726. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26727. currentVertexDataIndex++;
  26728. }
  26729. }
  26730. // Return mesh
  26731. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26732. vertexData.applyToMesh(decal);
  26733. decal.position = position.clone();
  26734. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26735. return decal;
  26736. };
  26737. // Privates
  26738. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26739. // extrusion geometry
  26740. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26741. var tangents = path3D.getTangents();
  26742. var normals = path3D.getNormals();
  26743. var binormals = path3D.getBinormals();
  26744. var distances = path3D.getDistances();
  26745. var angle = 0;
  26746. var returnScale = function () { return scale; };
  26747. var returnRotation = function () { return rotation; };
  26748. var rotate = custom ? rotateFunction : returnRotation;
  26749. var scl = custom ? scaleFunction : returnScale;
  26750. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26751. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26752. for (var i = 0; i < curve.length; i++) {
  26753. var shapePath = new Array();
  26754. var angleStep = rotate(i, distances[i]);
  26755. var scaleRatio = scl(i, distances[i]);
  26756. for (var p = 0; p < shape.length; p++) {
  26757. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26758. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26759. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26760. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26761. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26762. shapePath[p] = rotated;
  26763. }
  26764. shapePaths[index] = shapePath;
  26765. angle += angleStep;
  26766. index++;
  26767. }
  26768. // cap
  26769. var capPath = function (shapePath) {
  26770. var pointCap = Array();
  26771. var barycenter = BABYLON.Vector3.Zero();
  26772. var i;
  26773. for (i = 0; i < shapePath.length; i++) {
  26774. barycenter.addInPlace(shapePath[i]);
  26775. }
  26776. barycenter.scaleInPlace(1.0 / shapePath.length);
  26777. for (i = 0; i < shapePath.length; i++) {
  26778. pointCap.push(barycenter);
  26779. }
  26780. return pointCap;
  26781. };
  26782. switch (cap) {
  26783. case BABYLON.Mesh.NO_CAP:
  26784. break;
  26785. case BABYLON.Mesh.CAP_START:
  26786. shapePaths[0] = capPath(shapePaths[2]);
  26787. shapePaths[1] = shapePaths[2];
  26788. break;
  26789. case BABYLON.Mesh.CAP_END:
  26790. shapePaths[index] = shapePaths[index - 1];
  26791. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26792. break;
  26793. case BABYLON.Mesh.CAP_ALL:
  26794. shapePaths[0] = capPath(shapePaths[2]);
  26795. shapePaths[1] = shapePaths[2];
  26796. shapePaths[index] = shapePaths[index - 1];
  26797. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26798. break;
  26799. default:
  26800. break;
  26801. }
  26802. return shapePaths;
  26803. };
  26804. var path3D;
  26805. var pathArray;
  26806. if (instance) {
  26807. path3D = (instance.path3D).update(curve);
  26808. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26809. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26810. return instance;
  26811. }
  26812. // extruded shape creation
  26813. path3D = new BABYLON.Path3D(curve);
  26814. var newShapePaths = new Array();
  26815. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26816. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26817. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26818. extrudedGeneric.pathArray = pathArray;
  26819. extrudedGeneric.path3D = path3D;
  26820. extrudedGeneric.cap = cap;
  26821. return extrudedGeneric;
  26822. };
  26823. return MeshBuilder;
  26824. }());
  26825. BABYLON.MeshBuilder = MeshBuilder;
  26826. })(BABYLON || (BABYLON = {}));
  26827. //# sourceMappingURL=babylon.meshBuilder.js.map
  26828. var BABYLON;
  26829. (function (BABYLON) {
  26830. var BaseTexture = (function () {
  26831. function BaseTexture(scene) {
  26832. this.hasAlpha = false;
  26833. this.getAlphaFromRGB = false;
  26834. this.level = 1;
  26835. this.coordinatesIndex = 0;
  26836. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26837. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26838. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26839. this.anisotropicFilteringLevel = 4;
  26840. this.isCube = false;
  26841. this.isRenderTarget = false;
  26842. this.animations = new Array();
  26843. /**
  26844. * An event triggered when the texture is disposed.
  26845. * @type {BABYLON.Observable}
  26846. */
  26847. this.onDisposeObservable = new BABYLON.Observable();
  26848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26849. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26850. this._scene.textures.push(this);
  26851. this._uid = null;
  26852. }
  26853. Object.defineProperty(BaseTexture.prototype, "uid", {
  26854. get: function () {
  26855. if (!this._uid) {
  26856. this._uid = BABYLON.Tools.RandomId();
  26857. }
  26858. return this._uid;
  26859. },
  26860. enumerable: true,
  26861. configurable: true
  26862. });
  26863. BaseTexture.prototype.toString = function () {
  26864. return this.name;
  26865. };
  26866. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26867. set: function (callback) {
  26868. if (this._onDisposeObserver) {
  26869. this.onDisposeObservable.remove(this._onDisposeObserver);
  26870. }
  26871. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26872. },
  26873. enumerable: true,
  26874. configurable: true
  26875. });
  26876. BaseTexture.prototype.getScene = function () {
  26877. return this._scene;
  26878. };
  26879. BaseTexture.prototype.getTextureMatrix = function () {
  26880. return null;
  26881. };
  26882. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26883. return null;
  26884. };
  26885. BaseTexture.prototype.getInternalTexture = function () {
  26886. return this._texture;
  26887. };
  26888. BaseTexture.prototype.isReady = function () {
  26889. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26890. return true;
  26891. }
  26892. if (this._texture) {
  26893. return this._texture.isReady;
  26894. }
  26895. return false;
  26896. };
  26897. BaseTexture.prototype.getSize = function () {
  26898. if (this._texture._width) {
  26899. return new BABYLON.Size(this._texture._width, this._texture._height);
  26900. }
  26901. if (this._texture._size) {
  26902. return new BABYLON.Size(this._texture._size, this._texture._size);
  26903. }
  26904. return BABYLON.Size.Zero();
  26905. };
  26906. BaseTexture.prototype.getBaseSize = function () {
  26907. if (!this.isReady() || !this._texture)
  26908. return BABYLON.Size.Zero();
  26909. if (this._texture._size) {
  26910. return new BABYLON.Size(this._texture._size, this._texture._size);
  26911. }
  26912. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26913. };
  26914. BaseTexture.prototype.scale = function (ratio) {
  26915. };
  26916. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26917. get: function () {
  26918. return false;
  26919. },
  26920. enumerable: true,
  26921. configurable: true
  26922. });
  26923. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26924. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26925. for (var index = 0; index < texturesCache.length; index++) {
  26926. var texturesCacheEntry = texturesCache[index];
  26927. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26928. texturesCache.splice(index, 1);
  26929. return;
  26930. }
  26931. }
  26932. };
  26933. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26934. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26935. for (var index = 0; index < texturesCache.length; index++) {
  26936. var texturesCacheEntry = texturesCache[index];
  26937. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26938. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26939. texturesCacheEntry.references++;
  26940. return texturesCacheEntry;
  26941. }
  26942. }
  26943. }
  26944. return null;
  26945. };
  26946. BaseTexture.prototype.delayLoad = function () {
  26947. };
  26948. BaseTexture.prototype.clone = function () {
  26949. return null;
  26950. };
  26951. BaseTexture.prototype.releaseInternalTexture = function () {
  26952. if (this._texture) {
  26953. this._scene.getEngine().releaseInternalTexture(this._texture);
  26954. delete this._texture;
  26955. }
  26956. };
  26957. BaseTexture.prototype.dispose = function () {
  26958. // Animations
  26959. this.getScene().stopAnimation(this);
  26960. // Remove from scene
  26961. this._scene._removePendingData(this);
  26962. var index = this._scene.textures.indexOf(this);
  26963. if (index >= 0) {
  26964. this._scene.textures.splice(index, 1);
  26965. }
  26966. if (this._texture === undefined) {
  26967. return;
  26968. }
  26969. // Release
  26970. this.releaseInternalTexture();
  26971. // Callback
  26972. this.onDisposeObservable.notifyObservers(this);
  26973. this.onDisposeObservable.clear();
  26974. };
  26975. BaseTexture.prototype.serialize = function () {
  26976. if (!this.name) {
  26977. return null;
  26978. }
  26979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26980. // Animations
  26981. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26982. return serializationObject;
  26983. };
  26984. return BaseTexture;
  26985. }());
  26986. __decorate([
  26987. BABYLON.serialize()
  26988. ], BaseTexture.prototype, "name", void 0);
  26989. __decorate([
  26990. BABYLON.serialize()
  26991. ], BaseTexture.prototype, "hasAlpha", void 0);
  26992. __decorate([
  26993. BABYLON.serialize()
  26994. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26995. __decorate([
  26996. BABYLON.serialize()
  26997. ], BaseTexture.prototype, "level", void 0);
  26998. __decorate([
  26999. BABYLON.serialize()
  27000. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27001. __decorate([
  27002. BABYLON.serialize()
  27003. ], BaseTexture.prototype, "coordinatesMode", void 0);
  27004. __decorate([
  27005. BABYLON.serialize()
  27006. ], BaseTexture.prototype, "wrapU", void 0);
  27007. __decorate([
  27008. BABYLON.serialize()
  27009. ], BaseTexture.prototype, "wrapV", void 0);
  27010. __decorate([
  27011. BABYLON.serialize()
  27012. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27013. __decorate([
  27014. BABYLON.serialize()
  27015. ], BaseTexture.prototype, "isCube", void 0);
  27016. __decorate([
  27017. BABYLON.serialize()
  27018. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27019. BABYLON.BaseTexture = BaseTexture;
  27020. })(BABYLON || (BABYLON = {}));
  27021. //# sourceMappingURL=babylon.baseTexture.js.map
  27022. var BABYLON;
  27023. (function (BABYLON) {
  27024. var Texture = (function (_super) {
  27025. __extends(Texture, _super);
  27026. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27027. if (noMipmap === void 0) { noMipmap = false; }
  27028. if (invertY === void 0) { invertY = true; }
  27029. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27030. if (onLoad === void 0) { onLoad = null; }
  27031. if (onError === void 0) { onError = null; }
  27032. if (buffer === void 0) { buffer = null; }
  27033. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27034. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27035. var _this = _super.call(this, scene) || this;
  27036. _this.uOffset = 0;
  27037. _this.vOffset = 0;
  27038. _this.uScale = 1.0;
  27039. _this.vScale = 1.0;
  27040. _this.uAng = 0;
  27041. _this.vAng = 0;
  27042. _this.wAng = 0;
  27043. _this.name = url;
  27044. _this.url = url;
  27045. _this._noMipmap = noMipmap;
  27046. _this._invertY = invertY;
  27047. _this._samplingMode = samplingMode;
  27048. _this._buffer = buffer;
  27049. _this._deleteBuffer = deleteBuffer;
  27050. _this._format = format;
  27051. if (!url) {
  27052. return _this;
  27053. }
  27054. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  27055. var load = function () {
  27056. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  27057. _this.onLoadObservable.notifyObservers(true);
  27058. }
  27059. if (onLoad) {
  27060. onLoad();
  27061. }
  27062. };
  27063. if (!_this._texture) {
  27064. if (!scene.useDelayedTextureLoading) {
  27065. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  27066. if (deleteBuffer) {
  27067. delete _this._buffer;
  27068. }
  27069. }
  27070. else {
  27071. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27072. _this._delayedOnLoad = load;
  27073. _this._delayedOnError = onError;
  27074. }
  27075. }
  27076. else {
  27077. if (_this._texture.isReady) {
  27078. BABYLON.Tools.SetImmediate(function () { return load(); });
  27079. }
  27080. else {
  27081. _this._texture.onLoadedCallbacks.push(load);
  27082. }
  27083. }
  27084. return _this;
  27085. }
  27086. Object.defineProperty(Texture.prototype, "noMipmap", {
  27087. get: function () {
  27088. return this._noMipmap;
  27089. },
  27090. enumerable: true,
  27091. configurable: true
  27092. });
  27093. Texture.prototype.delayLoad = function () {
  27094. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27095. return;
  27096. }
  27097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27098. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27099. if (!this._texture) {
  27100. 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);
  27101. if (this._deleteBuffer) {
  27102. delete this._buffer;
  27103. }
  27104. }
  27105. };
  27106. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27107. if (!this._texture) {
  27108. return;
  27109. }
  27110. this._samplingMode = samplingMode;
  27111. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27112. };
  27113. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27114. x *= this.uScale;
  27115. y *= this.vScale;
  27116. x -= 0.5 * this.uScale;
  27117. y -= 0.5 * this.vScale;
  27118. z -= 0.5;
  27119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27120. t.x += 0.5 * this.uScale + this.uOffset;
  27121. t.y += 0.5 * this.vScale + this.vOffset;
  27122. t.z += 0.5;
  27123. };
  27124. Texture.prototype.getTextureMatrix = function () {
  27125. if (this.uOffset === this._cachedUOffset &&
  27126. this.vOffset === this._cachedVOffset &&
  27127. this.uScale === this._cachedUScale &&
  27128. this.vScale === this._cachedVScale &&
  27129. this.uAng === this._cachedUAng &&
  27130. this.vAng === this._cachedVAng &&
  27131. this.wAng === this._cachedWAng) {
  27132. return this._cachedTextureMatrix;
  27133. }
  27134. this._cachedUOffset = this.uOffset;
  27135. this._cachedVOffset = this.vOffset;
  27136. this._cachedUScale = this.uScale;
  27137. this._cachedVScale = this.vScale;
  27138. this._cachedUAng = this.uAng;
  27139. this._cachedVAng = this.vAng;
  27140. this._cachedWAng = this.wAng;
  27141. if (!this._cachedTextureMatrix) {
  27142. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27143. this._rowGenerationMatrix = new BABYLON.Matrix();
  27144. this._t0 = BABYLON.Vector3.Zero();
  27145. this._t1 = BABYLON.Vector3.Zero();
  27146. this._t2 = BABYLON.Vector3.Zero();
  27147. }
  27148. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27149. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27150. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27151. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27152. this._t1.subtractInPlace(this._t0);
  27153. this._t2.subtractInPlace(this._t0);
  27154. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27155. this._cachedTextureMatrix.m[0] = this._t1.x;
  27156. this._cachedTextureMatrix.m[1] = this._t1.y;
  27157. this._cachedTextureMatrix.m[2] = this._t1.z;
  27158. this._cachedTextureMatrix.m[4] = this._t2.x;
  27159. this._cachedTextureMatrix.m[5] = this._t2.y;
  27160. this._cachedTextureMatrix.m[6] = this._t2.z;
  27161. this._cachedTextureMatrix.m[8] = this._t0.x;
  27162. this._cachedTextureMatrix.m[9] = this._t0.y;
  27163. this._cachedTextureMatrix.m[10] = this._t0.z;
  27164. return this._cachedTextureMatrix;
  27165. };
  27166. Texture.prototype.getReflectionTextureMatrix = function () {
  27167. if (this.uOffset === this._cachedUOffset &&
  27168. this.vOffset === this._cachedVOffset &&
  27169. this.uScale === this._cachedUScale &&
  27170. this.vScale === this._cachedVScale &&
  27171. this.coordinatesMode === this._cachedCoordinatesMode) {
  27172. return this._cachedTextureMatrix;
  27173. }
  27174. if (!this._cachedTextureMatrix) {
  27175. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27176. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27177. }
  27178. this._cachedCoordinatesMode = this.coordinatesMode;
  27179. switch (this.coordinatesMode) {
  27180. case Texture.PLANAR_MODE:
  27181. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27182. this._cachedTextureMatrix[0] = this.uScale;
  27183. this._cachedTextureMatrix[5] = this.vScale;
  27184. this._cachedTextureMatrix[12] = this.uOffset;
  27185. this._cachedTextureMatrix[13] = this.vOffset;
  27186. break;
  27187. case Texture.PROJECTION_MODE:
  27188. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27189. this._projectionModeMatrix.m[0] = 0.5;
  27190. this._projectionModeMatrix.m[5] = -0.5;
  27191. this._projectionModeMatrix.m[10] = 0.0;
  27192. this._projectionModeMatrix.m[12] = 0.5;
  27193. this._projectionModeMatrix.m[13] = 0.5;
  27194. this._projectionModeMatrix.m[14] = 1.0;
  27195. this._projectionModeMatrix.m[15] = 1.0;
  27196. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27197. break;
  27198. default:
  27199. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27200. break;
  27201. }
  27202. return this._cachedTextureMatrix;
  27203. };
  27204. Texture.prototype.clone = function () {
  27205. var _this = this;
  27206. return BABYLON.SerializationHelper.Clone(function () {
  27207. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27208. }, this);
  27209. };
  27210. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27211. get: function () {
  27212. if (!this._onLoadObservarble) {
  27213. this._onLoadObservarble = new BABYLON.Observable();
  27214. }
  27215. return this._onLoadObservarble;
  27216. },
  27217. enumerable: true,
  27218. configurable: true
  27219. });
  27220. // Statics
  27221. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27222. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27223. if (onLoad === void 0) { onLoad = null; }
  27224. if (onError === void 0) { onError = null; }
  27225. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27226. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27227. };
  27228. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27229. if (parsedTexture.customType) {
  27230. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27231. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27232. }
  27233. if (parsedTexture.isCube) {
  27234. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27235. }
  27236. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27237. return null;
  27238. }
  27239. var texture = BABYLON.SerializationHelper.Parse(function () {
  27240. if (parsedTexture.mirrorPlane) {
  27241. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27242. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27243. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27244. return mirrorTexture;
  27245. }
  27246. else if (parsedTexture.isRenderTarget) {
  27247. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27248. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27249. return renderTargetTexture;
  27250. }
  27251. else {
  27252. var texture;
  27253. if (parsedTexture.base64String) {
  27254. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27255. }
  27256. else {
  27257. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27258. }
  27259. return texture;
  27260. }
  27261. }, parsedTexture, scene);
  27262. // Animations
  27263. if (parsedTexture.animations) {
  27264. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27265. var parsedAnimation = parsedTexture.animations[animationIndex];
  27266. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27267. }
  27268. }
  27269. return texture;
  27270. };
  27271. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27272. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27273. if (noMipmap === void 0) { noMipmap = false; }
  27274. if (invertY === void 0) { invertY = true; }
  27275. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27276. if (onLoad === void 0) { onLoad = null; }
  27277. if (onError === void 0) { onError = null; }
  27278. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27279. if (name.substr(0, 5) !== "data:") {
  27280. name = "data:" + name;
  27281. }
  27282. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27283. };
  27284. return Texture;
  27285. }(BABYLON.BaseTexture));
  27286. // Constants
  27287. Texture.NEAREST_SAMPLINGMODE = 1;
  27288. Texture.BILINEAR_SAMPLINGMODE = 2;
  27289. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27290. Texture.EXPLICIT_MODE = 0;
  27291. Texture.SPHERICAL_MODE = 1;
  27292. Texture.PLANAR_MODE = 2;
  27293. Texture.CUBIC_MODE = 3;
  27294. Texture.PROJECTION_MODE = 4;
  27295. Texture.SKYBOX_MODE = 5;
  27296. Texture.INVCUBIC_MODE = 6;
  27297. Texture.EQUIRECTANGULAR_MODE = 7;
  27298. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27299. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27300. Texture.CLAMP_ADDRESSMODE = 0;
  27301. Texture.WRAP_ADDRESSMODE = 1;
  27302. Texture.MIRROR_ADDRESSMODE = 2;
  27303. __decorate([
  27304. BABYLON.serialize()
  27305. ], Texture.prototype, "url", void 0);
  27306. __decorate([
  27307. BABYLON.serialize()
  27308. ], Texture.prototype, "uOffset", void 0);
  27309. __decorate([
  27310. BABYLON.serialize()
  27311. ], Texture.prototype, "vOffset", void 0);
  27312. __decorate([
  27313. BABYLON.serialize()
  27314. ], Texture.prototype, "uScale", void 0);
  27315. __decorate([
  27316. BABYLON.serialize()
  27317. ], Texture.prototype, "vScale", void 0);
  27318. __decorate([
  27319. BABYLON.serialize()
  27320. ], Texture.prototype, "uAng", void 0);
  27321. __decorate([
  27322. BABYLON.serialize()
  27323. ], Texture.prototype, "vAng", void 0);
  27324. __decorate([
  27325. BABYLON.serialize()
  27326. ], Texture.prototype, "wAng", void 0);
  27327. BABYLON.Texture = Texture;
  27328. })(BABYLON || (BABYLON = {}));
  27329. //# sourceMappingURL=babylon.texture.js.map
  27330. var BABYLON;
  27331. (function (BABYLON) {
  27332. var CubeTexture = (function (_super) {
  27333. __extends(CubeTexture, _super);
  27334. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27335. if (onLoad === void 0) { onLoad = null; }
  27336. if (onError === void 0) { onError = null; }
  27337. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27338. var _this = _super.call(this, scene) || this;
  27339. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27340. _this.name = rootUrl;
  27341. _this.url = rootUrl;
  27342. _this._noMipmap = noMipmap;
  27343. _this.hasAlpha = false;
  27344. _this._format = format;
  27345. if (!rootUrl && !files) {
  27346. return _this;
  27347. }
  27348. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27349. if (!files) {
  27350. if (!extensions) {
  27351. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27352. }
  27353. files = [];
  27354. for (var index = 0; index < extensions.length; index++) {
  27355. files.push(rootUrl + extensions[index]);
  27356. }
  27357. _this._extensions = extensions;
  27358. }
  27359. _this._files = files;
  27360. if (!_this._texture) {
  27361. if (!scene.useDelayedTextureLoading) {
  27362. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27363. }
  27364. else {
  27365. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27366. }
  27367. }
  27368. else if (onLoad) {
  27369. if (_this._texture.isReady) {
  27370. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27371. }
  27372. else {
  27373. _this._texture.onLoadedCallbacks.push(onLoad);
  27374. }
  27375. }
  27376. _this.isCube = true;
  27377. _this._textureMatrix = BABYLON.Matrix.Identity();
  27378. return _this;
  27379. }
  27380. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27381. return new CubeTexture("", scene, null, noMipmap, files);
  27382. };
  27383. // Methods
  27384. CubeTexture.prototype.delayLoad = function () {
  27385. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27386. return;
  27387. }
  27388. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27389. this._texture = this._getFromCache(this.url, this._noMipmap);
  27390. if (!this._texture) {
  27391. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27392. }
  27393. };
  27394. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27395. return this._textureMatrix;
  27396. };
  27397. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27398. var texture = BABYLON.SerializationHelper.Parse(function () {
  27399. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27400. }, parsedTexture, scene);
  27401. // Animations
  27402. if (parsedTexture.animations) {
  27403. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27404. var parsedAnimation = parsedTexture.animations[animationIndex];
  27405. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27406. }
  27407. }
  27408. return texture;
  27409. };
  27410. CubeTexture.prototype.clone = function () {
  27411. var _this = this;
  27412. return BABYLON.SerializationHelper.Clone(function () {
  27413. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27414. }, this);
  27415. };
  27416. return CubeTexture;
  27417. }(BABYLON.BaseTexture));
  27418. BABYLON.CubeTexture = CubeTexture;
  27419. })(BABYLON || (BABYLON = {}));
  27420. //# sourceMappingURL=babylon.cubeTexture.js.map
  27421. var BABYLON;
  27422. (function (BABYLON) {
  27423. var RenderTargetTexture = (function (_super) {
  27424. __extends(RenderTargetTexture, _super);
  27425. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27426. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27427. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27428. if (isCube === void 0) { isCube = false; }
  27429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27430. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27431. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27432. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27433. _this.isCube = isCube;
  27434. /**
  27435. * Use this list to define the list of mesh you want to render.
  27436. */
  27437. _this.renderList = new Array();
  27438. _this.renderParticles = true;
  27439. _this.renderSprites = false;
  27440. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27441. // Events
  27442. /**
  27443. * An event triggered when the texture is unbind.
  27444. * @type {BABYLON.Observable}
  27445. */
  27446. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27447. /**
  27448. * An event triggered before rendering the texture
  27449. * @type {BABYLON.Observable}
  27450. */
  27451. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27452. /**
  27453. * An event triggered after rendering the texture
  27454. * @type {BABYLON.Observable}
  27455. */
  27456. _this.onAfterRenderObservable = new BABYLON.Observable();
  27457. /**
  27458. * An event triggered after the texture clear
  27459. * @type {BABYLON.Observable}
  27460. */
  27461. _this.onClearObservable = new BABYLON.Observable();
  27462. _this._currentRefreshId = -1;
  27463. _this._refreshRate = 1;
  27464. _this._samples = 1;
  27465. _this.name = name;
  27466. _this.isRenderTarget = true;
  27467. _this._size = size;
  27468. _this._generateMipMaps = generateMipMaps;
  27469. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27470. _this._renderTargetOptions = {
  27471. generateMipMaps: generateMipMaps,
  27472. type: type,
  27473. samplingMode: samplingMode,
  27474. generateDepthBuffer: generateDepthBuffer,
  27475. generateStencilBuffer: generateStencilBuffer
  27476. };
  27477. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27478. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27479. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27480. }
  27481. if (isCube) {
  27482. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27483. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27484. _this._textureMatrix = BABYLON.Matrix.Identity();
  27485. }
  27486. else {
  27487. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27488. }
  27489. // Rendering groups
  27490. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27491. return _this;
  27492. }
  27493. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27494. get: function () {
  27495. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27496. },
  27497. enumerable: true,
  27498. configurable: true
  27499. });
  27500. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27501. get: function () {
  27502. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27503. },
  27504. enumerable: true,
  27505. configurable: true
  27506. });
  27507. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27508. get: function () {
  27509. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27510. },
  27511. enumerable: true,
  27512. configurable: true
  27513. });
  27514. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27515. set: function (callback) {
  27516. if (this._onAfterUnbindObserver) {
  27517. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27518. }
  27519. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27520. },
  27521. enumerable: true,
  27522. configurable: true
  27523. });
  27524. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27525. set: function (callback) {
  27526. if (this._onBeforeRenderObserver) {
  27527. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27528. }
  27529. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27530. },
  27531. enumerable: true,
  27532. configurable: true
  27533. });
  27534. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  27535. set: function (callback) {
  27536. if (this._onAfterRenderObserver) {
  27537. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27538. }
  27539. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27540. },
  27541. enumerable: true,
  27542. configurable: true
  27543. });
  27544. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27545. set: function (callback) {
  27546. if (this._onClearObserver) {
  27547. this.onClearObservable.remove(this._onClearObserver);
  27548. }
  27549. this._onClearObserver = this.onClearObservable.add(callback);
  27550. },
  27551. enumerable: true,
  27552. configurable: true
  27553. });
  27554. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27555. get: function () {
  27556. return this._samples;
  27557. },
  27558. set: function (value) {
  27559. if (this._samples === value) {
  27560. return;
  27561. }
  27562. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27563. },
  27564. enumerable: true,
  27565. configurable: true
  27566. });
  27567. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27568. this._currentRefreshId = -1;
  27569. };
  27570. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27571. get: function () {
  27572. return this._refreshRate;
  27573. },
  27574. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27575. set: function (value) {
  27576. this._refreshRate = value;
  27577. this.resetRefreshCounter();
  27578. },
  27579. enumerable: true,
  27580. configurable: true
  27581. });
  27582. RenderTargetTexture.prototype._shouldRender = function () {
  27583. if (this._currentRefreshId === -1) {
  27584. this._currentRefreshId = 1;
  27585. return true;
  27586. }
  27587. if (this.refreshRate === this._currentRefreshId) {
  27588. this._currentRefreshId = 1;
  27589. return true;
  27590. }
  27591. this._currentRefreshId++;
  27592. return false;
  27593. };
  27594. RenderTargetTexture.prototype.isReady = function () {
  27595. if (!this.getScene().renderTargetsEnabled) {
  27596. return false;
  27597. }
  27598. return _super.prototype.isReady.call(this);
  27599. };
  27600. RenderTargetTexture.prototype.getRenderSize = function () {
  27601. return this._size;
  27602. };
  27603. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27604. get: function () {
  27605. return true;
  27606. },
  27607. enumerable: true,
  27608. configurable: true
  27609. });
  27610. RenderTargetTexture.prototype.scale = function (ratio) {
  27611. var newSize = this._size * ratio;
  27612. this.resize(newSize);
  27613. };
  27614. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27615. if (this.isCube) {
  27616. return this._textureMatrix;
  27617. }
  27618. return _super.prototype.getReflectionTextureMatrix.call(this);
  27619. };
  27620. RenderTargetTexture.prototype.resize = function (size) {
  27621. this.releaseInternalTexture();
  27622. if (this.isCube) {
  27623. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27624. }
  27625. else {
  27626. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27627. }
  27628. };
  27629. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27630. var scene = this.getScene();
  27631. var engine = scene.getEngine();
  27632. if (this.useCameraPostProcesses !== undefined) {
  27633. useCameraPostProcess = this.useCameraPostProcesses;
  27634. }
  27635. if (this._waitingRenderList) {
  27636. this.renderList = [];
  27637. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27638. var id = this._waitingRenderList[index];
  27639. this.renderList.push(scene.getMeshByID(id));
  27640. }
  27641. delete this._waitingRenderList;
  27642. }
  27643. // Is predicate defined?
  27644. if (this.renderListPredicate) {
  27645. this.renderList.splice(0); // Clear previous renderList
  27646. var sceneMeshes = this.getScene().meshes;
  27647. for (var index = 0; index < sceneMeshes.length; index++) {
  27648. var mesh = sceneMeshes[index];
  27649. if (this.renderListPredicate(mesh)) {
  27650. this.renderList.push(mesh);
  27651. }
  27652. }
  27653. }
  27654. if (this.renderList && this.renderList.length === 0) {
  27655. return;
  27656. }
  27657. // Set custom projection.
  27658. // Needs to be before binding to prevent changing the aspect ratio.
  27659. if (this.activeCamera) {
  27660. engine.setViewport(this.activeCamera.viewport);
  27661. if (this.activeCamera !== scene.activeCamera) {
  27662. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27663. }
  27664. }
  27665. else {
  27666. engine.setViewport(scene.activeCamera.viewport);
  27667. }
  27668. // Prepare renderingManager
  27669. this._renderingManager.reset();
  27670. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27671. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27672. var sceneRenderId = scene.getRenderId();
  27673. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27674. var mesh = currentRenderList[meshIndex];
  27675. if (mesh) {
  27676. if (!mesh.isReady()) {
  27677. // Reset _currentRefreshId
  27678. this.resetRefreshCounter();
  27679. continue;
  27680. }
  27681. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27682. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27683. mesh._activate(sceneRenderId);
  27684. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27685. var subMesh = mesh.subMeshes[subIndex];
  27686. scene._activeIndices.addCount(subMesh.indexCount, false);
  27687. this._renderingManager.dispatch(subMesh);
  27688. }
  27689. }
  27690. }
  27691. }
  27692. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27693. var particleSystem = scene.particleSystems[particleIndex];
  27694. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27695. continue;
  27696. }
  27697. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27698. this._renderingManager.dispatchParticles(particleSystem);
  27699. }
  27700. }
  27701. if (this.isCube) {
  27702. for (var face = 0; face < 6; face++) {
  27703. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27704. scene.incrementRenderId();
  27705. scene.resetCachedMaterial();
  27706. }
  27707. }
  27708. else {
  27709. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27710. }
  27711. this.onAfterUnbindObservable.notifyObservers(this);
  27712. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27713. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27714. }
  27715. engine.setViewport(scene.activeCamera.viewport);
  27716. scene.resetCachedMaterial();
  27717. };
  27718. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27719. var _this = this;
  27720. var scene = this.getScene();
  27721. var engine = scene.getEngine();
  27722. // Bind
  27723. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27724. if (this.isCube) {
  27725. engine.bindFramebuffer(this._texture, faceIndex);
  27726. }
  27727. else {
  27728. engine.bindFramebuffer(this._texture);
  27729. }
  27730. }
  27731. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27732. // Clear
  27733. if (this.onClearObservable.hasObservers()) {
  27734. this.onClearObservable.notifyObservers(engine);
  27735. }
  27736. else {
  27737. engine.clear(scene.clearColor, true, true, true);
  27738. }
  27739. if (!this._doNotChangeAspectRatio) {
  27740. scene.updateTransformMatrix(true);
  27741. }
  27742. // Render
  27743. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27744. if (useCameraPostProcess) {
  27745. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27746. }
  27747. if (!this._doNotChangeAspectRatio) {
  27748. scene.updateTransformMatrix(true);
  27749. }
  27750. // Dump ?
  27751. if (dumpForDebug) {
  27752. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27753. }
  27754. // Unbind
  27755. if (!this.isCube || faceIndex === 5) {
  27756. if (this.isCube) {
  27757. if (faceIndex === 5) {
  27758. engine.generateMipMapsForCubemap(this._texture);
  27759. }
  27760. }
  27761. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  27762. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  27763. });
  27764. }
  27765. else {
  27766. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27767. }
  27768. };
  27769. /**
  27770. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27771. * This allowed control for front to back rendering or reversly depending of the special needs.
  27772. *
  27773. * @param renderingGroupId The rendering group id corresponding to its index
  27774. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27775. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27776. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27777. */
  27778. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27779. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27780. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27781. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27782. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27783. };
  27784. /**
  27785. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27786. *
  27787. * @param renderingGroupId The rendering group id corresponding to its index
  27788. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27789. */
  27790. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27791. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27792. };
  27793. RenderTargetTexture.prototype.clone = function () {
  27794. var textureSize = this.getSize();
  27795. 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);
  27796. // Base texture
  27797. newTexture.hasAlpha = this.hasAlpha;
  27798. newTexture.level = this.level;
  27799. // RenderTarget Texture
  27800. newTexture.coordinatesMode = this.coordinatesMode;
  27801. newTexture.renderList = this.renderList.slice(0);
  27802. return newTexture;
  27803. };
  27804. RenderTargetTexture.prototype.serialize = function () {
  27805. if (!this.name) {
  27806. return null;
  27807. }
  27808. var serializationObject = _super.prototype.serialize.call(this);
  27809. serializationObject.renderTargetSize = this.getRenderSize();
  27810. serializationObject.renderList = [];
  27811. for (var index = 0; index < this.renderList.length; index++) {
  27812. serializationObject.renderList.push(this.renderList[index].id);
  27813. }
  27814. return serializationObject;
  27815. };
  27816. return RenderTargetTexture;
  27817. }(BABYLON.Texture));
  27818. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27819. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27820. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27821. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27822. })(BABYLON || (BABYLON = {}));
  27823. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27824. var BABYLON;
  27825. (function (BABYLON) {
  27826. var ProceduralTexture = (function (_super) {
  27827. __extends(ProceduralTexture, _super);
  27828. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27830. if (isCube === void 0) { isCube = false; }
  27831. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27832. _this.isCube = isCube;
  27833. _this.isEnabled = true;
  27834. _this._currentRefreshId = -1;
  27835. _this._refreshRate = 1;
  27836. _this._vertexBuffers = {};
  27837. _this._uniforms = new Array();
  27838. _this._samplers = new Array();
  27839. _this._textures = new Array();
  27840. _this._floats = new Array();
  27841. _this._floatsArrays = {};
  27842. _this._colors3 = new Array();
  27843. _this._colors4 = new Array();
  27844. _this._vectors2 = new Array();
  27845. _this._vectors3 = new Array();
  27846. _this._matrices = new Array();
  27847. _this._fallbackTextureUsed = false;
  27848. scene._proceduralTextures.push(_this);
  27849. _this.name = name;
  27850. _this.isRenderTarget = true;
  27851. _this._size = size;
  27852. _this._generateMipMaps = generateMipMaps;
  27853. _this.setFragment(fragment);
  27854. _this._fallbackTexture = fallbackTexture;
  27855. var engine = scene.getEngine();
  27856. if (isCube) {
  27857. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27858. _this.setFloat("face", 0);
  27859. }
  27860. else {
  27861. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27862. }
  27863. // VBO
  27864. var vertices = [];
  27865. vertices.push(1, 1);
  27866. vertices.push(-1, 1);
  27867. vertices.push(-1, -1);
  27868. vertices.push(1, -1);
  27869. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27870. // Indices
  27871. var indices = [];
  27872. indices.push(0);
  27873. indices.push(1);
  27874. indices.push(2);
  27875. indices.push(0);
  27876. indices.push(2);
  27877. indices.push(3);
  27878. _this._indexBuffer = engine.createIndexBuffer(indices);
  27879. return _this;
  27880. }
  27881. ProceduralTexture.prototype.reset = function () {
  27882. if (this._effect === undefined) {
  27883. return;
  27884. }
  27885. var engine = this.getScene().getEngine();
  27886. engine._releaseEffect(this._effect);
  27887. };
  27888. ProceduralTexture.prototype.isReady = function () {
  27889. var _this = this;
  27890. var engine = this.getScene().getEngine();
  27891. var shaders;
  27892. if (!this._fragment) {
  27893. return false;
  27894. }
  27895. if (this._fallbackTextureUsed) {
  27896. return true;
  27897. }
  27898. if (this._fragment.fragmentElement !== undefined) {
  27899. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27900. }
  27901. else {
  27902. shaders = { vertex: "procedural", fragment: this._fragment };
  27903. }
  27904. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27905. _this.releaseInternalTexture();
  27906. if (_this._fallbackTexture) {
  27907. _this._texture = _this._fallbackTexture._texture;
  27908. _this._texture.references++;
  27909. }
  27910. _this._fallbackTextureUsed = true;
  27911. });
  27912. return this._effect.isReady();
  27913. };
  27914. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27915. this._currentRefreshId = -1;
  27916. };
  27917. ProceduralTexture.prototype.setFragment = function (fragment) {
  27918. this._fragment = fragment;
  27919. };
  27920. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27921. get: function () {
  27922. return this._refreshRate;
  27923. },
  27924. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27925. set: function (value) {
  27926. this._refreshRate = value;
  27927. this.resetRefreshCounter();
  27928. },
  27929. enumerable: true,
  27930. configurable: true
  27931. });
  27932. ProceduralTexture.prototype._shouldRender = function () {
  27933. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27934. return false;
  27935. }
  27936. if (this._fallbackTextureUsed) {
  27937. return false;
  27938. }
  27939. if (this._currentRefreshId === -1) {
  27940. this._currentRefreshId = 1;
  27941. return true;
  27942. }
  27943. if (this.refreshRate === this._currentRefreshId) {
  27944. this._currentRefreshId = 1;
  27945. return true;
  27946. }
  27947. this._currentRefreshId++;
  27948. return false;
  27949. };
  27950. ProceduralTexture.prototype.getRenderSize = function () {
  27951. return this._size;
  27952. };
  27953. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27954. if (this._fallbackTextureUsed) {
  27955. return;
  27956. }
  27957. this.releaseInternalTexture();
  27958. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27959. };
  27960. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27961. if (this._uniforms.indexOf(uniformName) === -1) {
  27962. this._uniforms.push(uniformName);
  27963. }
  27964. };
  27965. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27966. if (this._samplers.indexOf(name) === -1) {
  27967. this._samplers.push(name);
  27968. }
  27969. this._textures[name] = texture;
  27970. return this;
  27971. };
  27972. ProceduralTexture.prototype.setFloat = function (name, value) {
  27973. this._checkUniform(name);
  27974. this._floats[name] = value;
  27975. return this;
  27976. };
  27977. ProceduralTexture.prototype.setFloats = function (name, value) {
  27978. this._checkUniform(name);
  27979. this._floatsArrays[name] = value;
  27980. return this;
  27981. };
  27982. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27983. this._checkUniform(name);
  27984. this._colors3[name] = value;
  27985. return this;
  27986. };
  27987. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27988. this._checkUniform(name);
  27989. this._colors4[name] = value;
  27990. return this;
  27991. };
  27992. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27993. this._checkUniform(name);
  27994. this._vectors2[name] = value;
  27995. return this;
  27996. };
  27997. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27998. this._checkUniform(name);
  27999. this._vectors3[name] = value;
  28000. return this;
  28001. };
  28002. ProceduralTexture.prototype.setMatrix = function (name, value) {
  28003. this._checkUniform(name);
  28004. this._matrices[name] = value;
  28005. return this;
  28006. };
  28007. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28008. var scene = this.getScene();
  28009. var engine = scene.getEngine();
  28010. // Render
  28011. engine.enableEffect(this._effect);
  28012. engine.setState(false);
  28013. // Texture
  28014. for (var name in this._textures) {
  28015. this._effect.setTexture(name, this._textures[name]);
  28016. }
  28017. // Float
  28018. for (name in this._floats) {
  28019. this._effect.setFloat(name, this._floats[name]);
  28020. }
  28021. // Floats
  28022. for (name in this._floatsArrays) {
  28023. this._effect.setArray(name, this._floatsArrays[name]);
  28024. }
  28025. // Color3
  28026. for (name in this._colors3) {
  28027. this._effect.setColor3(name, this._colors3[name]);
  28028. }
  28029. // Color4
  28030. for (name in this._colors4) {
  28031. var color = this._colors4[name];
  28032. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28033. }
  28034. // Vector2
  28035. for (name in this._vectors2) {
  28036. this._effect.setVector2(name, this._vectors2[name]);
  28037. }
  28038. // Vector3
  28039. for (name in this._vectors3) {
  28040. this._effect.setVector3(name, this._vectors3[name]);
  28041. }
  28042. // Matrix
  28043. for (name in this._matrices) {
  28044. this._effect.setMatrix(name, this._matrices[name]);
  28045. }
  28046. if (this.isCube) {
  28047. for (var face = 0; face < 6; face++) {
  28048. engine.bindFramebuffer(this._texture, face);
  28049. // VBOs
  28050. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28051. this._effect.setFloat("face", face);
  28052. // Clear
  28053. engine.clear(scene.clearColor, true, true, true);
  28054. // Draw order
  28055. engine.draw(true, 0, 6);
  28056. // Mipmaps
  28057. if (face === 5) {
  28058. engine.generateMipMapsForCubemap(this._texture);
  28059. }
  28060. }
  28061. }
  28062. else {
  28063. engine.bindFramebuffer(this._texture);
  28064. // VBOs
  28065. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28066. // Clear
  28067. engine.clear(scene.clearColor, true, true, true);
  28068. // Draw order
  28069. engine.draw(true, 0, 6);
  28070. }
  28071. // Unbind
  28072. engine.unBindFramebuffer(this._texture, this.isCube);
  28073. if (this.onGenerated) {
  28074. this.onGenerated();
  28075. }
  28076. };
  28077. ProceduralTexture.prototype.clone = function () {
  28078. var textureSize = this.getSize();
  28079. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  28080. // Base texture
  28081. newTexture.hasAlpha = this.hasAlpha;
  28082. newTexture.level = this.level;
  28083. // RenderTarget Texture
  28084. newTexture.coordinatesMode = this.coordinatesMode;
  28085. return newTexture;
  28086. };
  28087. ProceduralTexture.prototype.dispose = function () {
  28088. var index = this.getScene()._proceduralTextures.indexOf(this);
  28089. if (index >= 0) {
  28090. this.getScene()._proceduralTextures.splice(index, 1);
  28091. }
  28092. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28093. if (vertexBuffer) {
  28094. vertexBuffer.dispose();
  28095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28096. }
  28097. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28098. this._indexBuffer = null;
  28099. }
  28100. _super.prototype.dispose.call(this);
  28101. };
  28102. return ProceduralTexture;
  28103. }(BABYLON.Texture));
  28104. BABYLON.ProceduralTexture = ProceduralTexture;
  28105. })(BABYLON || (BABYLON = {}));
  28106. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28107. /// <reference path="babylon.renderTargetTexture.ts" />
  28108. var BABYLON;
  28109. (function (BABYLON) {
  28110. var MirrorTexture = (function (_super) {
  28111. __extends(MirrorTexture, _super);
  28112. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28113. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28115. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28116. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28117. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28118. _this._transformMatrix = BABYLON.Matrix.Zero();
  28119. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28120. _this.onBeforeRenderObservable.add(function () {
  28121. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28122. _this._savedViewMatrix = scene.getViewMatrix();
  28123. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28124. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28125. scene.clipPlane = _this.mirrorPlane;
  28126. scene.getEngine().cullBackFaces = false;
  28127. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28128. });
  28129. _this.onAfterRenderObservable.add(function () {
  28130. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28131. scene.getEngine().cullBackFaces = true;
  28132. scene._mirroredCameraPosition = null;
  28133. delete scene.clipPlane;
  28134. });
  28135. return _this;
  28136. }
  28137. MirrorTexture.prototype.clone = function () {
  28138. var textureSize = this.getSize();
  28139. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28140. // Base texture
  28141. newTexture.hasAlpha = this.hasAlpha;
  28142. newTexture.level = this.level;
  28143. // Mirror Texture
  28144. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28145. newTexture.renderList = this.renderList.slice(0);
  28146. return newTexture;
  28147. };
  28148. MirrorTexture.prototype.serialize = function () {
  28149. if (!this.name) {
  28150. return null;
  28151. }
  28152. var serializationObject = _super.prototype.serialize.call(this);
  28153. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28154. return serializationObject;
  28155. };
  28156. return MirrorTexture;
  28157. }(BABYLON.RenderTargetTexture));
  28158. BABYLON.MirrorTexture = MirrorTexture;
  28159. })(BABYLON || (BABYLON = {}));
  28160. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28161. /// <reference path="babylon.renderTargetTexture.ts" />
  28162. var BABYLON;
  28163. (function (BABYLON) {
  28164. /**
  28165. * Creates a refraction texture used by refraction channel of the standard material.
  28166. * @param name the texture name
  28167. * @param size size of the underlying texture
  28168. * @param scene root scene
  28169. */
  28170. var RefractionTexture = (function (_super) {
  28171. __extends(RefractionTexture, _super);
  28172. function RefractionTexture(name, size, scene, generateMipMaps) {
  28173. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28174. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28175. _this.depth = 2.0;
  28176. _this.onBeforeRenderObservable.add(function () {
  28177. scene.clipPlane = _this.refractionPlane;
  28178. });
  28179. _this.onAfterRenderObservable.add(function () {
  28180. delete scene.clipPlane;
  28181. });
  28182. return _this;
  28183. }
  28184. RefractionTexture.prototype.clone = function () {
  28185. var textureSize = this.getSize();
  28186. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28187. // Base texture
  28188. newTexture.hasAlpha = this.hasAlpha;
  28189. newTexture.level = this.level;
  28190. // Refraction Texture
  28191. newTexture.refractionPlane = this.refractionPlane.clone();
  28192. newTexture.renderList = this.renderList.slice(0);
  28193. newTexture.depth = this.depth;
  28194. return newTexture;
  28195. };
  28196. RefractionTexture.prototype.serialize = function () {
  28197. if (!this.name) {
  28198. return null;
  28199. }
  28200. var serializationObject = _super.prototype.serialize.call(this);
  28201. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28202. serializationObject.depth = this.depth;
  28203. return serializationObject;
  28204. };
  28205. return RefractionTexture;
  28206. }(BABYLON.RenderTargetTexture));
  28207. BABYLON.RefractionTexture = RefractionTexture;
  28208. })(BABYLON || (BABYLON = {}));
  28209. //# sourceMappingURL=babylon.refractionTexture.js.map
  28210. /// <reference path="babylon.texture.ts" />
  28211. var BABYLON;
  28212. (function (BABYLON) {
  28213. var DynamicTexture = (function (_super) {
  28214. __extends(DynamicTexture, _super);
  28215. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28217. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28218. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28219. _this.name = name;
  28220. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28221. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28222. _this._generateMipMaps = generateMipMaps;
  28223. if (options.getContext) {
  28224. _this._canvas = options;
  28225. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28226. }
  28227. else {
  28228. _this._canvas = document.createElement("canvas");
  28229. if (options.width) {
  28230. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28231. }
  28232. else {
  28233. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28234. }
  28235. }
  28236. var textureSize = _this.getSize();
  28237. _this._canvas.width = textureSize.width;
  28238. _this._canvas.height = textureSize.height;
  28239. _this._context = _this._canvas.getContext("2d");
  28240. return _this;
  28241. }
  28242. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28243. get: function () {
  28244. return true;
  28245. },
  28246. enumerable: true,
  28247. configurable: true
  28248. });
  28249. DynamicTexture.prototype.scale = function (ratio) {
  28250. var textureSize = this.getSize();
  28251. textureSize.width *= ratio;
  28252. textureSize.height *= ratio;
  28253. this._canvas.width = textureSize.width;
  28254. this._canvas.height = textureSize.height;
  28255. this.releaseInternalTexture();
  28256. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28257. };
  28258. DynamicTexture.prototype.getContext = function () {
  28259. return this._context;
  28260. };
  28261. DynamicTexture.prototype.clear = function () {
  28262. var size = this.getSize();
  28263. this._context.fillRect(0, 0, size.width, size.height);
  28264. };
  28265. DynamicTexture.prototype.update = function (invertY) {
  28266. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28267. };
  28268. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28269. if (update === void 0) { update = true; }
  28270. var size = this.getSize();
  28271. if (clearColor) {
  28272. this._context.fillStyle = clearColor;
  28273. this._context.fillRect(0, 0, size.width, size.height);
  28274. }
  28275. this._context.font = font;
  28276. if (x === null || x === undefined) {
  28277. var textSize = this._context.measureText(text);
  28278. x = (size.width - textSize.width) / 2;
  28279. }
  28280. if (y === null || y === undefined) {
  28281. var fontSize = parseInt((font.replace(/\D/g, '')));
  28282. ;
  28283. y = (size.height / 2) + (fontSize / 3.65);
  28284. }
  28285. this._context.fillStyle = color;
  28286. this._context.fillText(text, x, y);
  28287. if (update) {
  28288. this.update(invertY);
  28289. }
  28290. };
  28291. DynamicTexture.prototype.clone = function () {
  28292. var textureSize = this.getSize();
  28293. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28294. // Base texture
  28295. newTexture.hasAlpha = this.hasAlpha;
  28296. newTexture.level = this.level;
  28297. // Dynamic Texture
  28298. newTexture.wrapU = this.wrapU;
  28299. newTexture.wrapV = this.wrapV;
  28300. return newTexture;
  28301. };
  28302. return DynamicTexture;
  28303. }(BABYLON.Texture));
  28304. BABYLON.DynamicTexture = DynamicTexture;
  28305. })(BABYLON || (BABYLON = {}));
  28306. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28307. var BABYLON;
  28308. (function (BABYLON) {
  28309. var VideoTexture = (function (_super) {
  28310. __extends(VideoTexture, _super);
  28311. /**
  28312. * Creates a video texture.
  28313. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28314. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28315. * @param {BABYLON.Scene} scene is obviously the current scene.
  28316. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28317. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28318. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28319. */
  28320. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28321. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28322. if (invertY === void 0) { invertY = false; }
  28323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28324. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28325. _this._autoLaunch = true;
  28326. var urls;
  28327. _this.name = name;
  28328. if (urlsOrVideo instanceof HTMLVideoElement) {
  28329. _this.video = urlsOrVideo;
  28330. }
  28331. else {
  28332. urls = urlsOrVideo;
  28333. _this.video = document.createElement("video");
  28334. _this.video.autoplay = false;
  28335. _this.video.loop = true;
  28336. }
  28337. _this._generateMipMaps = generateMipMaps;
  28338. _this._samplingMode = samplingMode;
  28339. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28340. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28341. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28342. }
  28343. else {
  28344. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28345. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28346. _this._generateMipMaps = false;
  28347. }
  28348. if (urls) {
  28349. _this.video.addEventListener("canplaythrough", function () {
  28350. _this._createTexture();
  28351. });
  28352. urls.forEach(function (url) {
  28353. var source = document.createElement("source");
  28354. source.src = url;
  28355. _this.video.appendChild(source);
  28356. });
  28357. }
  28358. else {
  28359. _this._createTexture();
  28360. }
  28361. _this._lastUpdate = BABYLON.Tools.Now;
  28362. return _this;
  28363. }
  28364. VideoTexture.prototype._createTexture = function () {
  28365. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28366. this._texture.isReady = true;
  28367. };
  28368. VideoTexture.prototype.update = function () {
  28369. if (this._autoLaunch) {
  28370. this._autoLaunch = false;
  28371. this.video.play();
  28372. }
  28373. var now = BABYLON.Tools.Now;
  28374. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28375. return false;
  28376. }
  28377. this._lastUpdate = now;
  28378. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28379. return true;
  28380. };
  28381. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28382. var video = document.createElement("video");
  28383. var constraintsDeviceId;
  28384. if (constraints && constraints.deviceId) {
  28385. constraintsDeviceId = {
  28386. exact: constraints.deviceId
  28387. };
  28388. }
  28389. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28390. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28391. if (navigator.getUserMedia) {
  28392. navigator.getUserMedia({
  28393. video: {
  28394. deviceId: constraintsDeviceId,
  28395. width: {
  28396. min: (constraints && constraints.minWidth) || 256,
  28397. max: (constraints && constraints.maxWidth) || 640
  28398. },
  28399. height: {
  28400. min: (constraints && constraints.minHeight) || 256,
  28401. max: (constraints && constraints.maxHeight) || 480
  28402. }
  28403. }
  28404. }, function (stream) {
  28405. if (video.mozSrcObject !== undefined) {
  28406. video.mozSrcObject = stream;
  28407. }
  28408. else {
  28409. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28410. }
  28411. video.play();
  28412. if (onReady) {
  28413. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28414. }
  28415. }, function (e) {
  28416. BABYLON.Tools.Error(e.name);
  28417. });
  28418. }
  28419. };
  28420. return VideoTexture;
  28421. }(BABYLON.Texture));
  28422. BABYLON.VideoTexture = VideoTexture;
  28423. })(BABYLON || (BABYLON = {}));
  28424. //# sourceMappingURL=babylon.videoTexture.js.map
  28425. /// <reference path="babylon.proceduralTexture.ts" />
  28426. var BABYLON;
  28427. (function (BABYLON) {
  28428. var CustomProceduralTexture = (function (_super) {
  28429. __extends(CustomProceduralTexture, _super);
  28430. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28431. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28432. _this._animate = true;
  28433. _this._time = 0;
  28434. _this._texturePath = texturePath;
  28435. //Try to load json
  28436. _this.loadJson(texturePath);
  28437. _this.refreshRate = 1;
  28438. return _this;
  28439. }
  28440. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28441. var _this = this;
  28442. var that = this;
  28443. function noConfigFile() {
  28444. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28445. try {
  28446. that.setFragment(that._texturePath);
  28447. }
  28448. catch (ex) {
  28449. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28450. }
  28451. }
  28452. var configFileUrl = jsonUrl + "/config.json";
  28453. var xhr = new XMLHttpRequest();
  28454. xhr.open("GET", configFileUrl, true);
  28455. xhr.addEventListener("load", function () {
  28456. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28457. try {
  28458. _this._config = JSON.parse(xhr.response);
  28459. _this.updateShaderUniforms();
  28460. _this.updateTextures();
  28461. _this.setFragment(_this._texturePath + "/custom");
  28462. _this._animate = _this._config.animate;
  28463. _this.refreshRate = _this._config.refreshrate;
  28464. }
  28465. catch (ex) {
  28466. noConfigFile();
  28467. }
  28468. }
  28469. else {
  28470. noConfigFile();
  28471. }
  28472. }, false);
  28473. xhr.addEventListener("error", function () {
  28474. noConfigFile();
  28475. }, false);
  28476. try {
  28477. xhr.send();
  28478. }
  28479. catch (ex) {
  28480. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28481. }
  28482. };
  28483. CustomProceduralTexture.prototype.isReady = function () {
  28484. if (!_super.prototype.isReady.call(this)) {
  28485. return false;
  28486. }
  28487. for (var name in this._textures) {
  28488. var texture = this._textures[name];
  28489. if (!texture.isReady()) {
  28490. return false;
  28491. }
  28492. }
  28493. return true;
  28494. };
  28495. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28496. if (this._animate) {
  28497. this._time += this.getScene().getAnimationRatio() * 0.03;
  28498. this.updateShaderUniforms();
  28499. }
  28500. _super.prototype.render.call(this, useCameraPostProcess);
  28501. };
  28502. CustomProceduralTexture.prototype.updateTextures = function () {
  28503. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28504. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28505. }
  28506. };
  28507. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28508. if (this._config) {
  28509. for (var j = 0; j < this._config.uniforms.length; j++) {
  28510. var uniform = this._config.uniforms[j];
  28511. switch (uniform.type) {
  28512. case "float":
  28513. this.setFloat(uniform.name, uniform.value);
  28514. break;
  28515. case "color3":
  28516. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28517. break;
  28518. case "color4":
  28519. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28520. break;
  28521. case "vector2":
  28522. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28523. break;
  28524. case "vector3":
  28525. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28526. break;
  28527. }
  28528. }
  28529. }
  28530. this.setFloat("time", this._time);
  28531. };
  28532. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28533. get: function () {
  28534. return this._animate;
  28535. },
  28536. set: function (value) {
  28537. this._animate = value;
  28538. },
  28539. enumerable: true,
  28540. configurable: true
  28541. });
  28542. return CustomProceduralTexture;
  28543. }(BABYLON.ProceduralTexture));
  28544. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  28545. })(BABYLON || (BABYLON = {}));
  28546. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  28547. var BABYLON;
  28548. (function (BABYLON) {
  28549. var EffectFallbacks = (function () {
  28550. function EffectFallbacks() {
  28551. this._defines = {};
  28552. this._currentRank = 32;
  28553. this._maxRank = -1;
  28554. }
  28555. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28556. if (!this._defines[rank]) {
  28557. if (rank < this._currentRank) {
  28558. this._currentRank = rank;
  28559. }
  28560. if (rank > this._maxRank) {
  28561. this._maxRank = rank;
  28562. }
  28563. this._defines[rank] = new Array();
  28564. }
  28565. this._defines[rank].push(define);
  28566. };
  28567. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28568. this._meshRank = rank;
  28569. this._mesh = mesh;
  28570. if (rank < this._currentRank) {
  28571. this._currentRank = rank;
  28572. }
  28573. if (rank > this._maxRank) {
  28574. this._maxRank = rank;
  28575. }
  28576. };
  28577. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28578. get: function () {
  28579. return this._currentRank <= this._maxRank;
  28580. },
  28581. enumerable: true,
  28582. configurable: true
  28583. });
  28584. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28585. // First we try to switch to CPU skinning
  28586. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  28587. this._mesh.computeBonesUsingShaders = false;
  28588. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28589. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28590. var scene = this._mesh.getScene();
  28591. for (var index = 0; index < scene.meshes.length; index++) {
  28592. var otherMesh = scene.meshes[index];
  28593. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  28594. otherMesh.computeBonesUsingShaders = false;
  28595. }
  28596. }
  28597. }
  28598. else {
  28599. var currentFallbacks = this._defines[this._currentRank];
  28600. if (currentFallbacks) {
  28601. for (var index = 0; index < currentFallbacks.length; index++) {
  28602. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28603. }
  28604. }
  28605. this._currentRank++;
  28606. }
  28607. return currentDefines;
  28608. };
  28609. return EffectFallbacks;
  28610. }());
  28611. BABYLON.EffectFallbacks = EffectFallbacks;
  28612. var Effect = (function () {
  28613. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28614. var _this = this;
  28615. this.uniqueId = 0;
  28616. this._isReady = false;
  28617. this._compilationError = "";
  28618. this._valueCache = {};
  28619. this._engine = engine;
  28620. this.name = baseName;
  28621. this.defines = defines;
  28622. this._uniformsNames = uniformsNames.concat(samplers);
  28623. this._samplers = samplers;
  28624. this._attributesNames = attributesNames;
  28625. this.onError = onError;
  28626. this.onCompiled = onCompiled;
  28627. this._indexParameters = indexParameters;
  28628. this.uniqueId = Effect._uniqueIdSeed++;
  28629. var vertexSource;
  28630. var fragmentSource;
  28631. if (baseName.vertexElement) {
  28632. vertexSource = document.getElementById(baseName.vertexElement);
  28633. if (!vertexSource) {
  28634. vertexSource = baseName.vertexElement;
  28635. }
  28636. }
  28637. else {
  28638. vertexSource = baseName.vertex || baseName;
  28639. }
  28640. if (baseName.fragmentElement) {
  28641. fragmentSource = document.getElementById(baseName.fragmentElement);
  28642. if (!fragmentSource) {
  28643. fragmentSource = baseName.fragmentElement;
  28644. }
  28645. }
  28646. else {
  28647. fragmentSource = baseName.fragment || baseName;
  28648. }
  28649. this._loadVertexShader(vertexSource, function (vertexCode) {
  28650. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28651. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28652. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28653. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28654. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28655. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28656. });
  28657. });
  28658. });
  28659. });
  28660. });
  28661. });
  28662. }
  28663. Object.defineProperty(Effect.prototype, "key", {
  28664. get: function () {
  28665. return this._key;
  28666. },
  28667. enumerable: true,
  28668. configurable: true
  28669. });
  28670. // Properties
  28671. Effect.prototype.isReady = function () {
  28672. return this._isReady;
  28673. };
  28674. Effect.prototype.getProgram = function () {
  28675. return this._program;
  28676. };
  28677. Effect.prototype.getAttributesNames = function () {
  28678. return this._attributesNames;
  28679. };
  28680. Effect.prototype.getAttributeLocation = function (index) {
  28681. return this._attributes[index];
  28682. };
  28683. Effect.prototype.getAttributeLocationByName = function (name) {
  28684. var index = this._attributesNames.indexOf(name);
  28685. return this._attributes[index];
  28686. };
  28687. Effect.prototype.getAttributesCount = function () {
  28688. return this._attributes.length;
  28689. };
  28690. Effect.prototype.getUniformIndex = function (uniformName) {
  28691. return this._uniformsNames.indexOf(uniformName);
  28692. };
  28693. Effect.prototype.getUniform = function (uniformName) {
  28694. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28695. };
  28696. Effect.prototype.getSamplers = function () {
  28697. return this._samplers;
  28698. };
  28699. Effect.prototype.getCompilationError = function () {
  28700. return this._compilationError;
  28701. };
  28702. Effect.prototype.getVertexShaderSource = function () {
  28703. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28704. };
  28705. Effect.prototype.getFragmentShaderSource = function () {
  28706. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28707. };
  28708. // Methods
  28709. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28710. // DOM element ?
  28711. if (vertex instanceof HTMLElement) {
  28712. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28713. callback(vertexCode);
  28714. return;
  28715. }
  28716. // Base64 encoded ?
  28717. if (vertex.substr(0, 7) === "base64:") {
  28718. var vertexBinary = window.atob(vertex.substr(7));
  28719. callback(vertexBinary);
  28720. return;
  28721. }
  28722. // Is in local store ?
  28723. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28724. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28725. return;
  28726. }
  28727. var vertexShaderUrl;
  28728. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28729. vertexShaderUrl = vertex;
  28730. }
  28731. else {
  28732. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28733. }
  28734. // Vertex shader
  28735. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28736. };
  28737. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28738. // DOM element ?
  28739. if (fragment instanceof HTMLElement) {
  28740. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28741. callback(fragmentCode);
  28742. return;
  28743. }
  28744. // Base64 encoded ?
  28745. if (fragment.substr(0, 7) === "base64:") {
  28746. var fragmentBinary = window.atob(fragment.substr(7));
  28747. callback(fragmentBinary);
  28748. return;
  28749. }
  28750. // Is in local store ?
  28751. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28752. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28753. return;
  28754. }
  28755. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28756. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28757. return;
  28758. }
  28759. var fragmentShaderUrl;
  28760. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28761. fragmentShaderUrl = fragment;
  28762. }
  28763. else {
  28764. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28765. }
  28766. // Fragment shader
  28767. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28768. };
  28769. Effect.prototype._dumpShadersName = function () {
  28770. if (this.name.vertexElement) {
  28771. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28772. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28773. }
  28774. else if (this.name.vertex) {
  28775. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28776. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28777. }
  28778. else {
  28779. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28780. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28781. }
  28782. };
  28783. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28784. var preparedSourceCode = this._processPrecision(sourceCode);
  28785. if (this._engine.webGLVersion == 1) {
  28786. callback(preparedSourceCode);
  28787. return;
  28788. }
  28789. // Already converted
  28790. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28791. callback(preparedSourceCode);
  28792. return;
  28793. }
  28794. // Remove extensions
  28795. // #extension GL_OES_standard_derivatives : enable
  28796. // #extension GL_EXT_shader_texture_lod : enable
  28797. // #extension GL_EXT_frag_depth : enable
  28798. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28799. var result = preparedSourceCode.replace(regex, "");
  28800. // Migrate to GLSL v300
  28801. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28802. result = result.replace(/attribute[ \t]/g, "in ");
  28803. result = result.replace(/[ \t]attribute/g, " in");
  28804. if (isFragment) {
  28805. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28806. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28807. result = result.replace(/texture2D\(/g, "texture(");
  28808. result = result.replace(/textureCube\(/g, "texture(");
  28809. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28810. result = result.replace(/gl_FragColor/g, "glFragColor");
  28811. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28812. }
  28813. callback(result);
  28814. };
  28815. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28816. var _this = this;
  28817. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28818. var match = regex.exec(sourceCode);
  28819. var returnValue = new String(sourceCode);
  28820. while (match != null) {
  28821. var includeFile = match[1];
  28822. if (Effect.IncludesShadersStore[includeFile]) {
  28823. // Substitution
  28824. var includeContent = Effect.IncludesShadersStore[includeFile];
  28825. if (match[2]) {
  28826. var splits = match[3].split(",");
  28827. for (var index = 0; index < splits.length; index += 2) {
  28828. var source = new RegExp(splits[index], "g");
  28829. var dest = splits[index + 1];
  28830. includeContent = includeContent.replace(source, dest);
  28831. }
  28832. }
  28833. if (match[4]) {
  28834. var indexString = match[5];
  28835. if (indexString.indexOf("..") !== -1) {
  28836. var indexSplits = indexString.split("..");
  28837. var minIndex = parseInt(indexSplits[0]);
  28838. var maxIndex = parseInt(indexSplits[1]);
  28839. var sourceIncludeContent = includeContent.slice(0);
  28840. includeContent = "";
  28841. if (isNaN(maxIndex)) {
  28842. maxIndex = this._indexParameters[indexSplits[1]];
  28843. }
  28844. for (var i = minIndex; i <= maxIndex; i++) {
  28845. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28846. }
  28847. }
  28848. else {
  28849. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28850. }
  28851. }
  28852. // Replace
  28853. returnValue = returnValue.replace(match[0], includeContent);
  28854. }
  28855. else {
  28856. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28857. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28858. Effect.IncludesShadersStore[includeFile] = fileContent;
  28859. _this._processIncludes(returnValue, callback);
  28860. });
  28861. return;
  28862. }
  28863. match = regex.exec(sourceCode);
  28864. }
  28865. callback(returnValue);
  28866. };
  28867. Effect.prototype._processPrecision = function (source) {
  28868. if (source.indexOf("precision highp float") === -1) {
  28869. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28870. source = "precision mediump float;\n" + source;
  28871. }
  28872. else {
  28873. source = "precision highp float;\n" + source;
  28874. }
  28875. }
  28876. else {
  28877. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28878. source = source.replace("precision highp float", "precision mediump float");
  28879. }
  28880. }
  28881. return source;
  28882. };
  28883. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28884. try {
  28885. var engine = this._engine;
  28886. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28887. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28888. this._attributes = engine.getAttributes(this._program, attributesNames);
  28889. var index;
  28890. for (index = 0; index < this._samplers.length; index++) {
  28891. var sampler = this.getUniform(this._samplers[index]);
  28892. if (sampler == null) {
  28893. this._samplers.splice(index, 1);
  28894. index--;
  28895. }
  28896. }
  28897. engine.bindSamplers(this);
  28898. this._compilationError = "";
  28899. this._isReady = true;
  28900. if (this.onCompiled) {
  28901. this.onCompiled(this);
  28902. }
  28903. }
  28904. catch (e) {
  28905. this._compilationError = e.message;
  28906. // Let's go through fallbacks then
  28907. BABYLON.Tools.Error("Unable to compile effect: ");
  28908. BABYLON.Tools.Error("Defines: " + defines);
  28909. BABYLON.Tools.Error("Error: " + this._compilationError);
  28910. this._dumpShadersName();
  28911. if (fallbacks && fallbacks.isMoreFallbacks) {
  28912. BABYLON.Tools.Error("Trying next fallback.");
  28913. defines = fallbacks.reduce(defines);
  28914. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28915. }
  28916. else {
  28917. if (this.onError) {
  28918. this.onError(this, this._compilationError);
  28919. }
  28920. }
  28921. }
  28922. };
  28923. Object.defineProperty(Effect.prototype, "isSupported", {
  28924. get: function () {
  28925. return this._compilationError === "";
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Effect.prototype._bindTexture = function (channel, texture) {
  28931. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28932. };
  28933. Effect.prototype.setTexture = function (channel, texture) {
  28934. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28935. };
  28936. Effect.prototype.setTextureArray = function (channel, textures) {
  28937. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28938. var initialPos = this._samplers.indexOf(channel);
  28939. for (var index = 1; index < textures.length; index++) {
  28940. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28941. }
  28942. }
  28943. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28944. };
  28945. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28946. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28947. };
  28948. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28949. var changed = false;
  28950. var cache = this._valueCache[uniformName];
  28951. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28952. changed = true;
  28953. cache = new BABYLON.Matrix();
  28954. }
  28955. var tm = cache.m;
  28956. var om = matrix.m;
  28957. for (var index = 0; index < 16; index++) {
  28958. if (tm[index] !== om[index]) {
  28959. tm[index] = om[index];
  28960. changed = true;
  28961. }
  28962. }
  28963. this._valueCache[uniformName] = cache;
  28964. return changed;
  28965. };
  28966. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28967. var cache = this._valueCache[uniformName];
  28968. if (!cache) {
  28969. cache = [x, y];
  28970. this._valueCache[uniformName] = cache;
  28971. return true;
  28972. }
  28973. var changed = false;
  28974. if (cache[0] !== x) {
  28975. cache[0] = x;
  28976. changed = true;
  28977. }
  28978. if (cache[1] !== y) {
  28979. cache[1] = y;
  28980. changed = true;
  28981. }
  28982. return changed;
  28983. };
  28984. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28985. var cache = this._valueCache[uniformName];
  28986. if (!cache) {
  28987. cache = [x, y, z];
  28988. this._valueCache[uniformName] = cache;
  28989. return true;
  28990. }
  28991. var changed = false;
  28992. if (cache[0] !== x) {
  28993. cache[0] = x;
  28994. changed = true;
  28995. }
  28996. if (cache[1] !== y) {
  28997. cache[1] = y;
  28998. changed = true;
  28999. }
  29000. if (cache[2] !== z) {
  29001. cache[2] = z;
  29002. changed = true;
  29003. }
  29004. return changed;
  29005. };
  29006. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  29007. var cache = this._valueCache[uniformName];
  29008. if (!cache) {
  29009. cache = [x, y, z, w];
  29010. this._valueCache[uniformName] = cache;
  29011. return true;
  29012. }
  29013. var changed = false;
  29014. if (cache[0] !== x) {
  29015. cache[0] = x;
  29016. changed = true;
  29017. }
  29018. if (cache[1] !== y) {
  29019. cache[1] = y;
  29020. changed = true;
  29021. }
  29022. if (cache[2] !== z) {
  29023. cache[2] = z;
  29024. changed = true;
  29025. }
  29026. if (cache[3] !== w) {
  29027. cache[3] = w;
  29028. changed = true;
  29029. }
  29030. return changed;
  29031. };
  29032. Effect.prototype.setIntArray = function (uniformName, array) {
  29033. this._valueCache[uniformName] = null;
  29034. this._engine.setIntArray(this.getUniform(uniformName), array);
  29035. return this;
  29036. };
  29037. Effect.prototype.setIntArray2 = function (uniformName, array) {
  29038. this._valueCache[uniformName] = null;
  29039. this._engine.setIntArray2(this.getUniform(uniformName), array);
  29040. return this;
  29041. };
  29042. Effect.prototype.setIntArray3 = function (uniformName, array) {
  29043. this._valueCache[uniformName] = null;
  29044. this._engine.setIntArray3(this.getUniform(uniformName), array);
  29045. return this;
  29046. };
  29047. Effect.prototype.setIntArray4 = function (uniformName, array) {
  29048. this._valueCache[uniformName] = null;
  29049. this._engine.setIntArray4(this.getUniform(uniformName), array);
  29050. return this;
  29051. };
  29052. Effect.prototype.setFloatArray = function (uniformName, array) {
  29053. this._valueCache[uniformName] = null;
  29054. this._engine.setFloatArray(this.getUniform(uniformName), array);
  29055. return this;
  29056. };
  29057. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  29058. this._valueCache[uniformName] = null;
  29059. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  29060. return this;
  29061. };
  29062. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  29063. this._valueCache[uniformName] = null;
  29064. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  29065. return this;
  29066. };
  29067. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  29068. this._valueCache[uniformName] = null;
  29069. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  29070. return this;
  29071. };
  29072. Effect.prototype.setArray = function (uniformName, array) {
  29073. this._valueCache[uniformName] = null;
  29074. this._engine.setArray(this.getUniform(uniformName), array);
  29075. return this;
  29076. };
  29077. Effect.prototype.setArray2 = function (uniformName, array) {
  29078. this._valueCache[uniformName] = null;
  29079. this._engine.setArray2(this.getUniform(uniformName), array);
  29080. return this;
  29081. };
  29082. Effect.prototype.setArray3 = function (uniformName, array) {
  29083. this._valueCache[uniformName] = null;
  29084. this._engine.setArray3(this.getUniform(uniformName), array);
  29085. return this;
  29086. };
  29087. Effect.prototype.setArray4 = function (uniformName, array) {
  29088. this._valueCache[uniformName] = null;
  29089. this._engine.setArray4(this.getUniform(uniformName), array);
  29090. return this;
  29091. };
  29092. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29093. this._valueCache[uniformName] = null;
  29094. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29095. return this;
  29096. };
  29097. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29098. if (this._cacheMatrix(uniformName, matrix)) {
  29099. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29100. }
  29101. return this;
  29102. };
  29103. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29104. this._valueCache[uniformName] = null;
  29105. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29106. return this;
  29107. };
  29108. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29109. this._valueCache[uniformName] = null;
  29110. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29111. return this;
  29112. };
  29113. Effect.prototype.setFloat = function (uniformName, value) {
  29114. var cache = this._valueCache[uniformName];
  29115. if (cache !== undefined && cache === value)
  29116. return this;
  29117. this._valueCache[uniformName] = value;
  29118. this._engine.setFloat(this.getUniform(uniformName), value);
  29119. return this;
  29120. };
  29121. Effect.prototype.setBool = function (uniformName, bool) {
  29122. var cache = this._valueCache[uniformName];
  29123. if (cache !== undefined && cache === bool)
  29124. return this;
  29125. this._valueCache[uniformName] = bool;
  29126. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29127. return this;
  29128. };
  29129. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29130. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29131. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29132. }
  29133. return this;
  29134. };
  29135. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29136. if (this._cacheFloat2(uniformName, x, y)) {
  29137. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29138. }
  29139. return this;
  29140. };
  29141. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29142. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29143. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29144. }
  29145. return this;
  29146. };
  29147. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29148. if (this._cacheFloat3(uniformName, x, y, z)) {
  29149. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29150. }
  29151. return this;
  29152. };
  29153. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29154. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29155. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29156. }
  29157. return this;
  29158. };
  29159. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29160. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29161. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29162. }
  29163. return this;
  29164. };
  29165. Effect.prototype.setColor3 = function (uniformName, color3) {
  29166. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29167. this._engine.setColor3(this.getUniform(uniformName), color3);
  29168. }
  29169. return this;
  29170. };
  29171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29174. }
  29175. return this;
  29176. };
  29177. Effect.prototype._recombineShader = function (node) {
  29178. if (node.define) {
  29179. if (node.condition) {
  29180. var defineIndex = this.defines.indexOf("#define " + node.define);
  29181. if (defineIndex === -1) {
  29182. return null;
  29183. }
  29184. var nextComma = this.defines.indexOf("\n", defineIndex);
  29185. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29186. var condition = defineValue + node.condition;
  29187. if (!eval(condition)) {
  29188. return null;
  29189. }
  29190. }
  29191. else if (node.ndef) {
  29192. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29193. return null;
  29194. }
  29195. }
  29196. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29197. return null;
  29198. }
  29199. }
  29200. var result = "";
  29201. for (var index = 0; index < node.children.length; index++) {
  29202. var line = node.children[index];
  29203. if (line.children) {
  29204. var combined = this._recombineShader(line);
  29205. if (combined !== null) {
  29206. result += combined + "\r\n";
  29207. }
  29208. continue;
  29209. }
  29210. if (line.length > 0) {
  29211. result += line + "\r\n";
  29212. }
  29213. }
  29214. return result;
  29215. };
  29216. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29217. var root = {
  29218. children: []
  29219. };
  29220. var currentNode = root;
  29221. var lines = shaderString.split("\n");
  29222. for (var index = 0; index < lines.length; index++) {
  29223. var line = lines[index].trim();
  29224. // #ifdef
  29225. var pos = line.indexOf("#ifdef ");
  29226. if (pos !== -1) {
  29227. var define = line.substr(pos + 7);
  29228. var newNode = {
  29229. condition: null,
  29230. ndef: false,
  29231. define: define,
  29232. children: [],
  29233. parent: currentNode
  29234. };
  29235. currentNode.children.push(newNode);
  29236. currentNode = newNode;
  29237. continue;
  29238. }
  29239. // #ifndef
  29240. var pos = line.indexOf("#ifndef ");
  29241. if (pos !== -1) {
  29242. var define = line.substr(pos + 8);
  29243. newNode = {
  29244. condition: null,
  29245. define: define,
  29246. ndef: true,
  29247. children: [],
  29248. parent: currentNode
  29249. };
  29250. currentNode.children.push(newNode);
  29251. currentNode = newNode;
  29252. continue;
  29253. }
  29254. // #if
  29255. var pos = line.indexOf("#if ");
  29256. if (pos !== -1) {
  29257. var define = line.substr(pos + 4).trim();
  29258. var conditionPos = define.indexOf(" ");
  29259. newNode = {
  29260. condition: define.substr(conditionPos + 1),
  29261. define: define.substr(0, conditionPos),
  29262. ndef: false,
  29263. children: [],
  29264. parent: currentNode
  29265. };
  29266. currentNode.children.push(newNode);
  29267. currentNode = newNode;
  29268. continue;
  29269. }
  29270. // #endif
  29271. pos = line.indexOf("#endif");
  29272. if (pos !== -1) {
  29273. currentNode = currentNode.parent;
  29274. continue;
  29275. }
  29276. currentNode.children.push(line);
  29277. }
  29278. // Recombine
  29279. return this._recombineShader(root);
  29280. };
  29281. return Effect;
  29282. }());
  29283. Effect._uniqueIdSeed = 0;
  29284. // Statics
  29285. Effect.ShadersStore = {};
  29286. Effect.IncludesShadersStore = {};
  29287. BABYLON.Effect = Effect;
  29288. })(BABYLON || (BABYLON = {}));
  29289. //# sourceMappingURL=babylon.effect.js.map
  29290. var BABYLON;
  29291. (function (BABYLON) {
  29292. var MaterialHelper = (function () {
  29293. function MaterialHelper() {
  29294. }
  29295. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  29296. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29297. var lightIndex = 0;
  29298. var needNormals = false;
  29299. var needRebuild = false;
  29300. var needShadows = false;
  29301. var lightmapMode = false;
  29302. for (var index = 0; index < scene.lights.length; index++) {
  29303. var light = scene.lights[index];
  29304. if (!light.isEnabled()) {
  29305. if (defines["LIGHT" + lightIndex] !== undefined) {
  29306. defines["LIGHT" + lightIndex] = false;
  29307. }
  29308. continue;
  29309. }
  29310. // Excluded check
  29311. if (light._excludedMeshesIds.length > 0) {
  29312. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  29313. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  29314. if (excludedMesh) {
  29315. light.excludedMeshes.push(excludedMesh);
  29316. }
  29317. }
  29318. light._excludedMeshesIds = [];
  29319. }
  29320. // Included check
  29321. if (light._includedOnlyMeshesIds.length > 0) {
  29322. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  29323. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  29324. if (includedOnlyMesh) {
  29325. light.includedOnlyMeshes.push(includedOnlyMesh);
  29326. }
  29327. }
  29328. light._includedOnlyMeshesIds = [];
  29329. }
  29330. if (!light.canAffectMesh(mesh)) {
  29331. if (defines["LIGHT" + lightIndex] !== undefined) {
  29332. defines["LIGHT" + lightIndex] = false;
  29333. }
  29334. continue;
  29335. }
  29336. needNormals = true;
  29337. if (defines["LIGHT" + lightIndex] === undefined) {
  29338. needRebuild = true;
  29339. }
  29340. defines["LIGHT" + lightIndex] = true;
  29341. var type;
  29342. if (light instanceof BABYLON.SpotLight) {
  29343. type = "SPOTLIGHT" + lightIndex;
  29344. }
  29345. else if (light instanceof BABYLON.HemisphericLight) {
  29346. type = "HEMILIGHT" + lightIndex;
  29347. }
  29348. else if (light instanceof BABYLON.PointLight) {
  29349. type = "POINTLIGHT" + lightIndex;
  29350. }
  29351. else {
  29352. type = "DIRLIGHT" + lightIndex;
  29353. }
  29354. if (defines[type] === undefined) {
  29355. needRebuild = true;
  29356. }
  29357. defines[type] = true;
  29358. // Specular
  29359. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  29360. defines["SPECULARTERM"] = true;
  29361. }
  29362. // Shadows
  29363. if (scene.shadowsEnabled) {
  29364. var shadowGenerator = light.getShadowGenerator();
  29365. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29366. if (defines["SHADOW" + lightIndex] === undefined) {
  29367. needRebuild = true;
  29368. }
  29369. defines["SHADOW" + lightIndex] = true;
  29370. defines["SHADOWS"] = true;
  29371. if (shadowGenerator.usePoissonSampling) {
  29372. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  29373. needRebuild = true;
  29374. }
  29375. defines["SHADOWPCF" + lightIndex] = true;
  29376. }
  29377. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  29378. if (defines["SHADOWESM" + lightIndex] === undefined) {
  29379. needRebuild = true;
  29380. }
  29381. defines["SHADOWESM" + lightIndex] = true;
  29382. }
  29383. needShadows = true;
  29384. }
  29385. }
  29386. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29387. lightmapMode = true;
  29388. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29389. needRebuild = true;
  29390. }
  29391. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29392. needRebuild = true;
  29393. }
  29394. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29395. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  29396. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  29397. }
  29398. }
  29399. lightIndex++;
  29400. if (lightIndex === maxSimultaneousLights)
  29401. break;
  29402. }
  29403. // Resetting all other lights if any
  29404. for (var index = scene.lights.length; index < maxSimultaneousLights; index++) {
  29405. if (defines["LIGHT" + lightIndex] !== undefined) {
  29406. defines["LIGHT" + lightIndex] = false;
  29407. }
  29408. }
  29409. var caps = scene.getEngine().getCaps();
  29410. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  29411. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29412. needRebuild = true;
  29413. }
  29414. defines["SHADOWFULLFLOAT"] = true;
  29415. }
  29416. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  29417. needRebuild = true;
  29418. }
  29419. if (lightmapMode) {
  29420. defines["LIGHTMAPEXCLUDED"] = true;
  29421. }
  29422. if (needRebuild) {
  29423. defines.rebuild();
  29424. }
  29425. return needNormals;
  29426. };
  29427. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29428. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29429. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29430. if (!defines["LIGHT" + lightIndex]) {
  29431. break;
  29432. }
  29433. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29434. samplersList.push("shadowSampler" + lightIndex);
  29435. }
  29436. };
  29437. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29438. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29439. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29440. if (!defines["LIGHT" + lightIndex]) {
  29441. break;
  29442. }
  29443. if (lightIndex > 0) {
  29444. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29445. }
  29446. if (defines["SHADOW" + lightIndex]) {
  29447. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29448. }
  29449. if (defines["SHADOWPCF" + lightIndex]) {
  29450. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29451. }
  29452. if (defines["SHADOWESM" + lightIndex]) {
  29453. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29454. }
  29455. }
  29456. };
  29457. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29458. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29459. fallbacks.addCPUSkinningFallback(0, mesh);
  29460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29462. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29465. }
  29466. }
  29467. };
  29468. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29469. if (defines["INSTANCES"]) {
  29470. attribs.push("world0");
  29471. attribs.push("world1");
  29472. attribs.push("world2");
  29473. attribs.push("world3");
  29474. }
  29475. };
  29476. // Bindings
  29477. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29478. var shadowGenerator = light.getShadowGenerator();
  29479. if (mesh.receiveShadows && shadowGenerator) {
  29480. if (!light.needCube()) {
  29481. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29482. }
  29483. else {
  29484. if (!depthValuesAlreadySet) {
  29485. depthValuesAlreadySet = true;
  29486. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29487. }
  29488. }
  29489. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29490. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  29491. }
  29492. return depthValuesAlreadySet;
  29493. };
  29494. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29495. if (light instanceof BABYLON.PointLight) {
  29496. // Point Light
  29497. light.transferToEffect(effect, "vLightData" + lightIndex);
  29498. }
  29499. else if (light instanceof BABYLON.DirectionalLight) {
  29500. // Directional Light
  29501. light.transferToEffect(effect, "vLightData" + lightIndex);
  29502. }
  29503. else if (light instanceof BABYLON.SpotLight) {
  29504. // Spot Light
  29505. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29506. }
  29507. else if (light instanceof BABYLON.HemisphericLight) {
  29508. // Hemispheric Light
  29509. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29510. }
  29511. };
  29512. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29513. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29514. var lightIndex = 0;
  29515. var depthValuesAlreadySet = false;
  29516. for (var index = 0; index < scene.lights.length; index++) {
  29517. var light = scene.lights[index];
  29518. if (!light.isEnabled()) {
  29519. continue;
  29520. }
  29521. if (!light.canAffectMesh(mesh)) {
  29522. continue;
  29523. }
  29524. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29525. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29526. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29527. if (defines["SPECULARTERM"]) {
  29528. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29529. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29530. }
  29531. // Shadows
  29532. if (scene.shadowsEnabled) {
  29533. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29534. }
  29535. lightIndex++;
  29536. if (lightIndex === maxSimultaneousLights)
  29537. break;
  29538. }
  29539. };
  29540. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  29541. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  29542. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  29543. effect.setColor3("vFogColor", scene.fogColor);
  29544. }
  29545. };
  29546. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  29547. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29548. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  29549. if (matrices) {
  29550. effect.setMatrices("mBones", matrices);
  29551. }
  29552. }
  29553. };
  29554. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  29555. if (defines["LOGARITHMICDEPTH"]) {
  29556. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  29557. }
  29558. };
  29559. MaterialHelper.BindClipPlane = function (effect, scene) {
  29560. if (scene.clipPlane) {
  29561. var clipPlane = scene.clipPlane;
  29562. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29563. }
  29564. };
  29565. return MaterialHelper;
  29566. }());
  29567. BABYLON.MaterialHelper = MaterialHelper;
  29568. })(BABYLON || (BABYLON = {}));
  29569. //# sourceMappingURL=babylon.materialHelper.js.map
  29570. var BABYLON;
  29571. (function (BABYLON) {
  29572. var FresnelParameters = (function () {
  29573. function FresnelParameters() {
  29574. this.isEnabled = true;
  29575. this.leftColor = BABYLON.Color3.White();
  29576. this.rightColor = BABYLON.Color3.Black();
  29577. this.bias = 0;
  29578. this.power = 1;
  29579. }
  29580. FresnelParameters.prototype.clone = function () {
  29581. var newFresnelParameters = new FresnelParameters();
  29582. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29583. return newFresnelParameters;
  29584. };
  29585. FresnelParameters.prototype.serialize = function () {
  29586. var serializationObject = {};
  29587. serializationObject.isEnabled = this.isEnabled;
  29588. serializationObject.leftColor = this.leftColor;
  29589. serializationObject.rightColor = this.rightColor;
  29590. serializationObject.bias = this.bias;
  29591. serializationObject.power = this.power;
  29592. return serializationObject;
  29593. };
  29594. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29595. var fresnelParameters = new FresnelParameters();
  29596. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29597. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29598. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29599. fresnelParameters.bias = parsedFresnelParameters.bias;
  29600. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29601. return fresnelParameters;
  29602. };
  29603. return FresnelParameters;
  29604. }());
  29605. BABYLON.FresnelParameters = FresnelParameters;
  29606. })(BABYLON || (BABYLON = {}));
  29607. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29608. var BABYLON;
  29609. (function (BABYLON) {
  29610. var MaterialDefines = (function () {
  29611. function MaterialDefines() {
  29612. this._isDirty = true;
  29613. }
  29614. MaterialDefines.prototype.rebuild = function (trackIsDirty) {
  29615. if (this._keys) {
  29616. delete this._keys;
  29617. }
  29618. this._keys = Object.keys(this);
  29619. if (!trackIsDirty) {
  29620. return;
  29621. }
  29622. for (var key in Object.keys(this)) {
  29623. if (Object.getOwnPropertyDescriptor(this, key).get) {
  29624. continue;
  29625. }
  29626. this["_" + key] = this[key];
  29627. Object.defineProperty(this, key, {
  29628. get: function () {
  29629. return this["_" + key];
  29630. },
  29631. set: function (value) {
  29632. if (this["_" + key] === value) {
  29633. return;
  29634. }
  29635. this["_" + key] = value;
  29636. this._isDirty = true;
  29637. },
  29638. enumerable: true,
  29639. configurable: true
  29640. });
  29641. }
  29642. };
  29643. MaterialDefines.prototype.isEqual = function (other) {
  29644. if (this._keys.length !== other._keys.length) {
  29645. return false;
  29646. }
  29647. for (var index = 0; index < this._keys.length; index++) {
  29648. var prop = this._keys[index];
  29649. if (this[prop] !== other[prop]) {
  29650. return false;
  29651. }
  29652. }
  29653. return true;
  29654. };
  29655. MaterialDefines.prototype.cloneTo = function (other) {
  29656. if (this._keys.length !== other._keys.length) {
  29657. other._keys = this._keys.slice(0);
  29658. }
  29659. for (var index = 0; index < this._keys.length; index++) {
  29660. var prop = this._keys[index];
  29661. other[prop] = this[prop];
  29662. }
  29663. };
  29664. MaterialDefines.prototype.reset = function () {
  29665. for (var index = 0; index < this._keys.length; index++) {
  29666. var prop = this._keys[index];
  29667. if (typeof (this[prop]) === "number") {
  29668. this[prop] = 0;
  29669. }
  29670. else {
  29671. this[prop] = false;
  29672. }
  29673. }
  29674. };
  29675. MaterialDefines.prototype.toString = function () {
  29676. var result = "";
  29677. for (var index = 0; index < this._keys.length; index++) {
  29678. var prop = this._keys[index];
  29679. if (typeof (this[prop]) === "number") {
  29680. result += "#define " + prop + " " + this[prop] + "\n";
  29681. }
  29682. else if (this[prop]) {
  29683. result += "#define " + prop + "\n";
  29684. }
  29685. }
  29686. return result;
  29687. };
  29688. return MaterialDefines;
  29689. }());
  29690. BABYLON.MaterialDefines = MaterialDefines;
  29691. var Material = (function () {
  29692. function Material(name, scene, doNotAdd) {
  29693. this.checkReadyOnEveryCall = false;
  29694. this.checkReadyOnlyOnce = false;
  29695. this.state = "";
  29696. this.alpha = 1.0;
  29697. this.backFaceCulling = true;
  29698. this.doNotSerialize = false;
  29699. /**
  29700. * An event triggered when the material is disposed.
  29701. * @type {BABYLON.Observable}
  29702. */
  29703. this.onDisposeObservable = new BABYLON.Observable();
  29704. /**
  29705. * An event triggered when the material is bound.
  29706. * @type {BABYLON.Observable}
  29707. */
  29708. this.onBindObservable = new BABYLON.Observable();
  29709. /**
  29710. * An event triggered when the material is unbound.
  29711. * @type {BABYLON.Observable}
  29712. */
  29713. this.onUnBindObservable = new BABYLON.Observable();
  29714. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29715. this.disableDepthWrite = false;
  29716. this.fogEnabled = true;
  29717. this.pointSize = 1.0;
  29718. this.zOffset = 0;
  29719. this._wasPreviouslyReady = false;
  29720. this._fillMode = Material.TriangleFillMode;
  29721. this.name = name;
  29722. this.id = name;
  29723. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29724. if (this._scene.useRightHandedSystem) {
  29725. this.sideOrientation = Material.ClockWiseSideOrientation;
  29726. }
  29727. else {
  29728. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29729. }
  29730. if (!doNotAdd) {
  29731. this._scene.materials.push(this);
  29732. }
  29733. }
  29734. Object.defineProperty(Material, "TriangleFillMode", {
  29735. get: function () {
  29736. return Material._TriangleFillMode;
  29737. },
  29738. enumerable: true,
  29739. configurable: true
  29740. });
  29741. Object.defineProperty(Material, "WireFrameFillMode", {
  29742. get: function () {
  29743. return Material._WireFrameFillMode;
  29744. },
  29745. enumerable: true,
  29746. configurable: true
  29747. });
  29748. Object.defineProperty(Material, "PointFillMode", {
  29749. get: function () {
  29750. return Material._PointFillMode;
  29751. },
  29752. enumerable: true,
  29753. configurable: true
  29754. });
  29755. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29756. get: function () {
  29757. return Material._ClockWiseSideOrientation;
  29758. },
  29759. enumerable: true,
  29760. configurable: true
  29761. });
  29762. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29763. get: function () {
  29764. return Material._CounterClockWiseSideOrientation;
  29765. },
  29766. enumerable: true,
  29767. configurable: true
  29768. });
  29769. Object.defineProperty(Material.prototype, "onDispose", {
  29770. set: function (callback) {
  29771. if (this._onDisposeObserver) {
  29772. this.onDisposeObservable.remove(this._onDisposeObserver);
  29773. }
  29774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. Object.defineProperty(Material.prototype, "onBind", {
  29780. set: function (callback) {
  29781. if (this._onBindObserver) {
  29782. this.onBindObservable.remove(this._onBindObserver);
  29783. }
  29784. this._onBindObserver = this.onBindObservable.add(callback);
  29785. },
  29786. enumerable: true,
  29787. configurable: true
  29788. });
  29789. Object.defineProperty(Material.prototype, "wireframe", {
  29790. get: function () {
  29791. return this._fillMode === Material.WireFrameFillMode;
  29792. },
  29793. set: function (value) {
  29794. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29795. },
  29796. enumerable: true,
  29797. configurable: true
  29798. });
  29799. Object.defineProperty(Material.prototype, "pointsCloud", {
  29800. get: function () {
  29801. return this._fillMode === Material.PointFillMode;
  29802. },
  29803. set: function (value) {
  29804. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29805. },
  29806. enumerable: true,
  29807. configurable: true
  29808. });
  29809. Object.defineProperty(Material.prototype, "fillMode", {
  29810. get: function () {
  29811. return this._fillMode;
  29812. },
  29813. set: function (value) {
  29814. this._fillMode = value;
  29815. },
  29816. enumerable: true,
  29817. configurable: true
  29818. });
  29819. /**
  29820. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29821. * subclasses should override adding information pertainent to themselves
  29822. */
  29823. Material.prototype.toString = function (fullDetails) {
  29824. var ret = "Name: " + this.name;
  29825. if (fullDetails) {
  29826. }
  29827. return ret;
  29828. };
  29829. Material.prototype.getClassName = function () {
  29830. return "Material";
  29831. };
  29832. Object.defineProperty(Material.prototype, "isFrozen", {
  29833. get: function () {
  29834. return this.checkReadyOnlyOnce;
  29835. },
  29836. enumerable: true,
  29837. configurable: true
  29838. });
  29839. Material.prototype.freeze = function () {
  29840. this.checkReadyOnlyOnce = true;
  29841. };
  29842. Material.prototype.unfreeze = function () {
  29843. this.checkReadyOnlyOnce = false;
  29844. };
  29845. Material.prototype.isReady = function (mesh, useInstances) {
  29846. return true;
  29847. };
  29848. Material.prototype.getEffect = function () {
  29849. return this._effect;
  29850. };
  29851. Material.prototype.getScene = function () {
  29852. return this._scene;
  29853. };
  29854. Material.prototype.needAlphaBlending = function () {
  29855. return (this.alpha < 1.0);
  29856. };
  29857. Material.prototype.needAlphaTesting = function () {
  29858. return false;
  29859. };
  29860. Material.prototype.getAlphaTestTexture = function () {
  29861. return null;
  29862. };
  29863. Material.prototype.markDirty = function () {
  29864. this._wasPreviouslyReady = false;
  29865. };
  29866. Material.prototype._preBind = function () {
  29867. var engine = this._scene.getEngine();
  29868. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29869. engine.enableEffect(this._effect);
  29870. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29871. };
  29872. Material.prototype.bind = function (world, mesh) {
  29873. this._scene._cachedMaterial = this;
  29874. this.onBindObservable.notifyObservers(mesh);
  29875. if (this.disableDepthWrite) {
  29876. var engine = this._scene.getEngine();
  29877. this._cachedDepthWriteState = engine.getDepthWrite();
  29878. engine.setDepthWrite(false);
  29879. }
  29880. };
  29881. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29882. };
  29883. Material.prototype.unbind = function () {
  29884. this.onUnBindObservable.notifyObservers(this);
  29885. if (this.disableDepthWrite) {
  29886. var engine = this._scene.getEngine();
  29887. engine.setDepthWrite(this._cachedDepthWriteState);
  29888. }
  29889. };
  29890. Material.prototype.clone = function (name) {
  29891. return null;
  29892. };
  29893. Material.prototype.getBindedMeshes = function () {
  29894. var result = new Array();
  29895. for (var index = 0; index < this._scene.meshes.length; index++) {
  29896. var mesh = this._scene.meshes[index];
  29897. if (mesh.material === this) {
  29898. result.push(mesh);
  29899. }
  29900. }
  29901. return result;
  29902. };
  29903. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29904. // Animations
  29905. this.getScene().stopAnimation(this);
  29906. // Remove from scene
  29907. var index = this._scene.materials.indexOf(this);
  29908. if (index >= 0) {
  29909. this._scene.materials.splice(index, 1);
  29910. }
  29911. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29912. if (forceDisposeEffect && this._effect) {
  29913. this._scene.getEngine()._releaseEffect(this._effect);
  29914. this._effect = null;
  29915. }
  29916. // Remove from meshes
  29917. for (index = 0; index < this._scene.meshes.length; index++) {
  29918. var mesh = this._scene.meshes[index];
  29919. if (mesh.material === this) {
  29920. mesh.material = null;
  29921. }
  29922. }
  29923. // Callback
  29924. this.onDisposeObservable.notifyObservers(this);
  29925. this.onDisposeObservable.clear();
  29926. this.onBindObservable.clear();
  29927. this.onUnBindObservable.clear();
  29928. };
  29929. Material.prototype.serialize = function () {
  29930. return BABYLON.SerializationHelper.Serialize(this);
  29931. };
  29932. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29933. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29934. multiMaterial.id = parsedMultiMaterial.id;
  29935. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29936. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29937. var subMatId = parsedMultiMaterial.materials[matIndex];
  29938. if (subMatId) {
  29939. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29940. }
  29941. else {
  29942. multiMaterial.subMaterials.push(null);
  29943. }
  29944. }
  29945. return multiMaterial;
  29946. };
  29947. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29948. if (!parsedMaterial.customType) {
  29949. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29950. }
  29951. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29952. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29953. ;
  29954. };
  29955. return Material;
  29956. }());
  29957. Material._TriangleFillMode = 0;
  29958. Material._WireFrameFillMode = 1;
  29959. Material._PointFillMode = 2;
  29960. Material._ClockWiseSideOrientation = 0;
  29961. Material._CounterClockWiseSideOrientation = 1;
  29962. __decorate([
  29963. BABYLON.serialize()
  29964. ], Material.prototype, "id", void 0);
  29965. __decorate([
  29966. BABYLON.serialize()
  29967. ], Material.prototype, "name", void 0);
  29968. __decorate([
  29969. BABYLON.serialize()
  29970. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29971. __decorate([
  29972. BABYLON.serialize()
  29973. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29974. __decorate([
  29975. BABYLON.serialize()
  29976. ], Material.prototype, "state", void 0);
  29977. __decorate([
  29978. BABYLON.serialize()
  29979. ], Material.prototype, "alpha", void 0);
  29980. __decorate([
  29981. BABYLON.serialize()
  29982. ], Material.prototype, "backFaceCulling", void 0);
  29983. __decorate([
  29984. BABYLON.serialize()
  29985. ], Material.prototype, "sideOrientation", void 0);
  29986. __decorate([
  29987. BABYLON.serialize()
  29988. ], Material.prototype, "alphaMode", void 0);
  29989. __decorate([
  29990. BABYLON.serialize()
  29991. ], Material.prototype, "disableDepthWrite", void 0);
  29992. __decorate([
  29993. BABYLON.serialize()
  29994. ], Material.prototype, "fogEnabled", void 0);
  29995. __decorate([
  29996. BABYLON.serialize()
  29997. ], Material.prototype, "pointSize", void 0);
  29998. __decorate([
  29999. BABYLON.serialize()
  30000. ], Material.prototype, "zOffset", void 0);
  30001. __decorate([
  30002. BABYLON.serialize()
  30003. ], Material.prototype, "wireframe", null);
  30004. __decorate([
  30005. BABYLON.serialize()
  30006. ], Material.prototype, "pointsCloud", null);
  30007. __decorate([
  30008. BABYLON.serialize()
  30009. ], Material.prototype, "fillMode", null);
  30010. BABYLON.Material = Material;
  30011. })(BABYLON || (BABYLON = {}));
  30012. //# sourceMappingURL=babylon.material.js.map
  30013. var BABYLON;
  30014. (function (BABYLON) {
  30015. var StandardMaterialDefines = (function (_super) {
  30016. __extends(StandardMaterialDefines, _super);
  30017. function StandardMaterialDefines() {
  30018. var _this = _super.call(this) || this;
  30019. _this.DIFFUSE = false;
  30020. _this.AMBIENT = false;
  30021. _this.OPACITY = false;
  30022. _this.OPACITYRGB = false;
  30023. _this.REFLECTION = false;
  30024. _this.EMISSIVE = false;
  30025. _this.SPECULAR = false;
  30026. _this.BUMP = false;
  30027. _this.PARALLAX = false;
  30028. _this.PARALLAXOCCLUSION = false;
  30029. _this.SPECULAROVERALPHA = false;
  30030. _this.CLIPPLANE = false;
  30031. _this.ALPHATEST = false;
  30032. _this.ALPHAFROMDIFFUSE = false;
  30033. _this.POINTSIZE = false;
  30034. _this.FOG = false;
  30035. _this.SPECULARTERM = false;
  30036. _this.DIFFUSEFRESNEL = false;
  30037. _this.OPACITYFRESNEL = false;
  30038. _this.REFLECTIONFRESNEL = false;
  30039. _this.REFRACTIONFRESNEL = false;
  30040. _this.EMISSIVEFRESNEL = false;
  30041. _this.FRESNEL = false;
  30042. _this.NORMAL = false;
  30043. _this.UV1 = false;
  30044. _this.UV2 = false;
  30045. _this.VERTEXCOLOR = false;
  30046. _this.VERTEXALPHA = false;
  30047. _this.NUM_BONE_INFLUENCERS = 0;
  30048. _this.BonesPerMesh = 0;
  30049. _this.INSTANCES = false;
  30050. _this.GLOSSINESS = false;
  30051. _this.ROUGHNESS = false;
  30052. _this.EMISSIVEASILLUMINATION = false;
  30053. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30054. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30055. _this.LIGHTMAP = false;
  30056. _this.USELIGHTMAPASSHADOWMAP = false;
  30057. _this.REFLECTIONMAP_3D = false;
  30058. _this.REFLECTIONMAP_SPHERICAL = false;
  30059. _this.REFLECTIONMAP_PLANAR = false;
  30060. _this.REFLECTIONMAP_CUBIC = false;
  30061. _this.REFLECTIONMAP_PROJECTION = false;
  30062. _this.REFLECTIONMAP_SKYBOX = false;
  30063. _this.REFLECTIONMAP_EXPLICIT = false;
  30064. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30065. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30066. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30067. _this.INVERTCUBICMAP = false;
  30068. _this.LOGARITHMICDEPTH = false;
  30069. _this.REFRACTION = false;
  30070. _this.REFRACTIONMAP_3D = false;
  30071. _this.REFLECTIONOVERALPHA = false;
  30072. _this.INVERTNORMALMAPX = false;
  30073. _this.INVERTNORMALMAPY = false;
  30074. _this.TWOSIDEDLIGHTING = false;
  30075. _this.SHADOWFULLFLOAT = false;
  30076. _this.CAMERACOLORGRADING = false;
  30077. _this.CAMERACOLORCURVES = false;
  30078. _this.rebuild(true);
  30079. return _this;
  30080. }
  30081. return StandardMaterialDefines;
  30082. }(BABYLON.MaterialDefines));
  30083. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30084. var StandardMaterial = (function (_super) {
  30085. __extends(StandardMaterial, _super);
  30086. function StandardMaterial(name, scene) {
  30087. var _this = _super.call(this, name, scene) || this;
  30088. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30089. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30090. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30091. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30092. _this.specularPower = 64;
  30093. _this.useAlphaFromDiffuseTexture = false;
  30094. _this.useEmissiveAsIllumination = false;
  30095. _this.linkEmissiveWithDiffuse = false;
  30096. _this.useReflectionFresnelFromSpecular = false;
  30097. _this.useSpecularOverAlpha = false;
  30098. _this.useReflectionOverAlpha = false;
  30099. _this.disableLighting = false;
  30100. _this.useParallax = false;
  30101. _this.useParallaxOcclusion = false;
  30102. _this.parallaxScaleBias = 0.05;
  30103. _this.roughness = 0;
  30104. _this.indexOfRefraction = 0.98;
  30105. _this.invertRefractionY = true;
  30106. _this.useLightmapAsShadowmap = false;
  30107. _this.useGlossinessFromSpecularMapAlpha = false;
  30108. _this.maxSimultaneousLights = 4;
  30109. /**
  30110. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30111. */
  30112. _this.invertNormalMapX = false;
  30113. /**
  30114. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30115. */
  30116. _this.invertNormalMapY = false;
  30117. /**
  30118. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30119. */
  30120. _this.twoSidedLighting = false;
  30121. /**
  30122. * Color Grading 2D Lookup Texture.
  30123. * This allows special effects like sepia, black and white to sixties rendering style.
  30124. */
  30125. _this.cameraColorGradingTexture = null;
  30126. /**
  30127. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30128. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30129. * 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;
  30130. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30131. */
  30132. _this.cameraColorCurves = null;
  30133. _this._renderTargets = new BABYLON.SmartArray(16);
  30134. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30135. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30136. _this._defines = new StandardMaterialDefines();
  30137. _this.getRenderTargetTextures = function () {
  30138. _this._renderTargets.reset();
  30139. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  30140. _this._renderTargets.push(_this.reflectionTexture);
  30141. }
  30142. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  30143. _this._renderTargets.push(_this.refractionTexture);
  30144. }
  30145. return _this._renderTargets;
  30146. };
  30147. return _this;
  30148. }
  30149. StandardMaterial.prototype.getClassName = function () {
  30150. return "StandardMaterial";
  30151. };
  30152. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30153. get: function () {
  30154. return this._useLogarithmicDepth;
  30155. },
  30156. set: function (value) {
  30157. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30158. },
  30159. enumerable: true,
  30160. configurable: true
  30161. });
  30162. StandardMaterial.prototype.needAlphaBlending = function () {
  30163. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30164. };
  30165. StandardMaterial.prototype.needAlphaTesting = function () {
  30166. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30167. };
  30168. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30169. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30170. };
  30171. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30172. return this.diffuseTexture;
  30173. };
  30174. // Methods
  30175. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  30176. if (!mesh) {
  30177. return true;
  30178. }
  30179. if (this._defines.INSTANCES !== useInstances) {
  30180. return false;
  30181. }
  30182. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  30183. return true;
  30184. }
  30185. return false;
  30186. };
  30187. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  30188. if (this.isFrozen) {
  30189. if (this._wasPreviouslyReady) {
  30190. return true;
  30191. }
  30192. }
  30193. var scene = this.getScene();
  30194. var engine = scene.getEngine();
  30195. var needUVs = false;
  30196. var needNormals = false;
  30197. // Lights
  30198. if (scene.lightsEnabled && !this.disableLighting) {
  30199. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  30200. }
  30201. if (!this.checkReadyOnEveryCall) {
  30202. if (this._renderId === scene.getRenderId()) {
  30203. if (this._checkCache(scene, mesh, useInstances)) {
  30204. return true;
  30205. }
  30206. }
  30207. }
  30208. // Textures
  30209. if (scene.texturesEnabled) {
  30210. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30211. if (!this.diffuseTexture.isReady()) {
  30212. return false;
  30213. }
  30214. else {
  30215. needUVs = true;
  30216. this._defines.DIFFUSE = true;
  30217. }
  30218. }
  30219. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30220. if (!this.ambientTexture.isReady()) {
  30221. return false;
  30222. }
  30223. else {
  30224. needUVs = true;
  30225. this._defines.AMBIENT = true;
  30226. }
  30227. }
  30228. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30229. if (!this.opacityTexture.isReady()) {
  30230. return false;
  30231. }
  30232. else {
  30233. needUVs = true;
  30234. this._defines.OPACITY = true;
  30235. if (this.opacityTexture.getAlphaFromRGB) {
  30236. this._defines.OPACITYRGB = true;
  30237. }
  30238. }
  30239. }
  30240. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30241. if (!this.reflectionTexture.isReady()) {
  30242. return false;
  30243. }
  30244. else {
  30245. needNormals = true;
  30246. this._defines.REFLECTION = true;
  30247. if (this.roughness > 0) {
  30248. this._defines.ROUGHNESS = true;
  30249. }
  30250. if (this.useReflectionOverAlpha) {
  30251. this._defines.REFLECTIONOVERALPHA = true;
  30252. }
  30253. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30254. this._defines.INVERTCUBICMAP = true;
  30255. }
  30256. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  30257. switch (this.reflectionTexture.coordinatesMode) {
  30258. case BABYLON.Texture.CUBIC_MODE:
  30259. case BABYLON.Texture.INVCUBIC_MODE:
  30260. this._defines.REFLECTIONMAP_CUBIC = true;
  30261. break;
  30262. case BABYLON.Texture.EXPLICIT_MODE:
  30263. this._defines.REFLECTIONMAP_EXPLICIT = true;
  30264. break;
  30265. case BABYLON.Texture.PLANAR_MODE:
  30266. this._defines.REFLECTIONMAP_PLANAR = true;
  30267. break;
  30268. case BABYLON.Texture.PROJECTION_MODE:
  30269. this._defines.REFLECTIONMAP_PROJECTION = true;
  30270. break;
  30271. case BABYLON.Texture.SKYBOX_MODE:
  30272. this._defines.REFLECTIONMAP_SKYBOX = true;
  30273. break;
  30274. case BABYLON.Texture.SPHERICAL_MODE:
  30275. this._defines.REFLECTIONMAP_SPHERICAL = true;
  30276. break;
  30277. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30278. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30279. break;
  30280. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30281. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30282. break;
  30283. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30284. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30285. break;
  30286. }
  30287. }
  30288. }
  30289. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30290. if (!this.emissiveTexture.isReady()) {
  30291. return false;
  30292. }
  30293. else {
  30294. needUVs = true;
  30295. this._defines.EMISSIVE = true;
  30296. }
  30297. }
  30298. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30299. if (!this.lightmapTexture.isReady()) {
  30300. return false;
  30301. }
  30302. else {
  30303. needUVs = true;
  30304. this._defines.LIGHTMAP = true;
  30305. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  30306. }
  30307. }
  30308. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30309. if (!this.specularTexture.isReady()) {
  30310. return false;
  30311. }
  30312. else {
  30313. needUVs = true;
  30314. this._defines.SPECULAR = true;
  30315. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  30316. }
  30317. }
  30318. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30319. if (!this.bumpTexture.isReady()) {
  30320. return false;
  30321. }
  30322. else {
  30323. needUVs = true;
  30324. this._defines.BUMP = true;
  30325. if (this.useParallax) {
  30326. this._defines.PARALLAX = true;
  30327. if (this.useParallaxOcclusion) {
  30328. this._defines.PARALLAXOCCLUSION = true;
  30329. }
  30330. }
  30331. if (this.invertNormalMapX) {
  30332. this._defines.INVERTNORMALMAPX = true;
  30333. }
  30334. if (this.invertNormalMapY) {
  30335. this._defines.INVERTNORMALMAPY = true;
  30336. }
  30337. if (scene._mirroredCameraPosition) {
  30338. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30339. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30340. }
  30341. }
  30342. }
  30343. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30344. if (!this.refractionTexture.isReady()) {
  30345. return false;
  30346. }
  30347. else {
  30348. needUVs = true;
  30349. this._defines.REFRACTION = true;
  30350. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  30351. }
  30352. }
  30353. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30354. if (!this.cameraColorGradingTexture.isReady()) {
  30355. return false;
  30356. }
  30357. else {
  30358. this._defines.CAMERACOLORGRADING = true;
  30359. }
  30360. }
  30361. if (!this.backFaceCulling && this.twoSidedLighting) {
  30362. this._defines.TWOSIDEDLIGHTING = true;
  30363. }
  30364. }
  30365. // Effect
  30366. if (scene.clipPlane) {
  30367. this._defines.CLIPPLANE = true;
  30368. }
  30369. if (engine.getAlphaTesting()) {
  30370. this._defines.ALPHATEST = true;
  30371. }
  30372. if (this._shouldUseAlphaFromDiffuseTexture()) {
  30373. this._defines.ALPHAFROMDIFFUSE = true;
  30374. }
  30375. if (this.useEmissiveAsIllumination) {
  30376. this._defines.EMISSIVEASILLUMINATION = true;
  30377. }
  30378. if (this.linkEmissiveWithDiffuse) {
  30379. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  30380. }
  30381. if (this.useLogarithmicDepth) {
  30382. this._defines.LOGARITHMICDEPTH = true;
  30383. }
  30384. if (this.cameraColorCurves) {
  30385. this._defines.CAMERACOLORCURVES = true;
  30386. }
  30387. // Point size
  30388. if (this.pointsCloud || scene.forcePointsCloud) {
  30389. this._defines.POINTSIZE = true;
  30390. }
  30391. // Fog
  30392. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30393. this._defines.FOG = true;
  30394. }
  30395. if (StandardMaterial.FresnelEnabled) {
  30396. // Fresnel
  30397. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  30398. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  30399. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  30400. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  30401. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30402. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30403. this._defines.DIFFUSEFRESNEL = true;
  30404. }
  30405. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30406. this._defines.OPACITYFRESNEL = true;
  30407. }
  30408. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30409. this._defines.REFLECTIONFRESNEL = true;
  30410. if (this.useReflectionFresnelFromSpecular) {
  30411. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  30412. }
  30413. }
  30414. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30415. this._defines.REFRACTIONFRESNEL = true;
  30416. }
  30417. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30418. this._defines.EMISSIVEFRESNEL = true;
  30419. }
  30420. needNormals = true;
  30421. this._defines.FRESNEL = true;
  30422. }
  30423. }
  30424. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  30425. this._defines.SPECULAROVERALPHA = true;
  30426. }
  30427. // Attribs
  30428. if (mesh) {
  30429. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30430. this._defines.NORMAL = true;
  30431. }
  30432. if (needUVs) {
  30433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30434. this._defines.UV1 = true;
  30435. }
  30436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30437. this._defines.UV2 = true;
  30438. }
  30439. }
  30440. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30441. this._defines.VERTEXCOLOR = true;
  30442. if (mesh.hasVertexAlpha) {
  30443. this._defines.VERTEXALPHA = true;
  30444. }
  30445. }
  30446. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30447. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30448. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30449. }
  30450. // Instances
  30451. if (useInstances) {
  30452. this._defines.INSTANCES = true;
  30453. }
  30454. }
  30455. // Get correct effect
  30456. if (this._defines._isDirty) {
  30457. scene.resetCachedMaterial();
  30458. // Fallbacks
  30459. var fallbacks = new BABYLON.EffectFallbacks();
  30460. if (this._defines.REFLECTION) {
  30461. fallbacks.addFallback(0, "REFLECTION");
  30462. }
  30463. if (this._defines.SPECULAR) {
  30464. fallbacks.addFallback(0, "SPECULAR");
  30465. }
  30466. if (this._defines.BUMP) {
  30467. fallbacks.addFallback(0, "BUMP");
  30468. }
  30469. if (this._defines.PARALLAX) {
  30470. fallbacks.addFallback(1, "PARALLAX");
  30471. }
  30472. if (this._defines.PARALLAXOCCLUSION) {
  30473. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30474. }
  30475. if (this._defines.SPECULAROVERALPHA) {
  30476. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30477. }
  30478. if (this._defines.FOG) {
  30479. fallbacks.addFallback(1, "FOG");
  30480. }
  30481. if (this._defines.POINTSIZE) {
  30482. fallbacks.addFallback(0, "POINTSIZE");
  30483. }
  30484. if (this._defines.LOGARITHMICDEPTH) {
  30485. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30486. }
  30487. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  30488. if (this._defines.SPECULARTERM) {
  30489. fallbacks.addFallback(0, "SPECULARTERM");
  30490. }
  30491. if (this._defines.DIFFUSEFRESNEL) {
  30492. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30493. }
  30494. if (this._defines.OPACITYFRESNEL) {
  30495. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30496. }
  30497. if (this._defines.REFLECTIONFRESNEL) {
  30498. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30499. }
  30500. if (this._defines.EMISSIVEFRESNEL) {
  30501. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30502. }
  30503. if (this._defines.FRESNEL) {
  30504. fallbacks.addFallback(4, "FRESNEL");
  30505. }
  30506. //Attributes
  30507. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30508. if (this._defines.NORMAL) {
  30509. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30510. }
  30511. if (this._defines.UV1) {
  30512. attribs.push(BABYLON.VertexBuffer.UVKind);
  30513. }
  30514. if (this._defines.UV2) {
  30515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30516. }
  30517. if (this._defines.VERTEXCOLOR) {
  30518. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30519. }
  30520. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30521. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30522. var shaderName = "default";
  30523. var join = this._defines.toString();
  30524. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30525. "vFogInfos", "vFogColor", "pointSize",
  30526. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30527. "mBones",
  30528. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30529. "depthValues",
  30530. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30531. "logarithmicDepthConstant"
  30532. ];
  30533. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30534. if (this._defines.CAMERACOLORCURVES) {
  30535. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30536. }
  30537. if (this._defines.CAMERACOLORGRADING) {
  30538. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30539. }
  30540. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  30541. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  30542. }
  30543. if (!this._effect.isReady()) {
  30544. return false;
  30545. }
  30546. this._renderId = scene.getRenderId();
  30547. this._wasPreviouslyReady = true;
  30548. if (mesh) {
  30549. if (!mesh._materialDefines) {
  30550. mesh._materialDefines = new StandardMaterialDefines();
  30551. }
  30552. this._defines.cloneTo(mesh._materialDefines);
  30553. }
  30554. return true;
  30555. };
  30556. StandardMaterial.prototype.unbind = function () {
  30557. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  30558. this._effect.setTexture("reflection2DSampler", null);
  30559. }
  30560. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  30561. this._effect.setTexture("refraction2DSampler", null);
  30562. }
  30563. _super.prototype.unbind.call(this);
  30564. };
  30565. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30566. this._effect.setMatrix("world", world);
  30567. };
  30568. StandardMaterial.prototype.bind = function (world, mesh) {
  30569. var scene = this.getScene();
  30570. // Matrices
  30571. this.bindOnlyWorldMatrix(world);
  30572. // Bones
  30573. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30574. if (scene.getCachedMaterial() !== this) {
  30575. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30576. if (StandardMaterial.FresnelEnabled) {
  30577. // Fresnel
  30578. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30579. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30580. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30581. }
  30582. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30583. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30584. }
  30585. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30586. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30587. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30588. }
  30589. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30590. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30591. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30592. }
  30593. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30594. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30595. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30596. }
  30597. }
  30598. // Textures
  30599. if (scene.texturesEnabled) {
  30600. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30601. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  30602. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  30603. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  30604. }
  30605. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30606. this._effect.setTexture("ambientSampler", this.ambientTexture);
  30607. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  30608. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  30609. }
  30610. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30611. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30612. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30613. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30614. }
  30615. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30616. if (this.reflectionTexture.isCube) {
  30617. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30618. }
  30619. else {
  30620. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30621. }
  30622. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30623. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30624. }
  30625. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30626. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30627. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30628. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30629. }
  30630. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30631. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30632. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30633. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30634. }
  30635. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30636. this._effect.setTexture("specularSampler", this.specularTexture);
  30637. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30638. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30639. }
  30640. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30641. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30642. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30643. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30644. }
  30645. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30646. var depth = 1.0;
  30647. if (this.refractionTexture.isCube) {
  30648. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30649. }
  30650. else {
  30651. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30652. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30653. if (this.refractionTexture.depth) {
  30654. depth = this.refractionTexture.depth;
  30655. }
  30656. }
  30657. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30658. }
  30659. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30660. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30661. }
  30662. }
  30663. // Clip plane
  30664. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30665. // Point size
  30666. if (this.pointsCloud) {
  30667. this._effect.setFloat("pointSize", this.pointSize);
  30668. }
  30669. // Colors
  30670. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30671. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30672. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30673. if (this._defines.SPECULARTERM) {
  30674. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30675. }
  30676. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30677. }
  30678. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30679. // Diffuse
  30680. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30681. // Lights
  30682. if (scene.lightsEnabled && !this.disableLighting) {
  30683. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30684. }
  30685. // View
  30686. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30687. this._effect.setMatrix("view", scene.getViewMatrix());
  30688. }
  30689. // Fog
  30690. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30691. // Log. depth
  30692. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30693. // Color Curves
  30694. if (this.cameraColorCurves) {
  30695. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30696. }
  30697. }
  30698. _super.prototype.bind.call(this, world, mesh);
  30699. };
  30700. StandardMaterial.prototype.getAnimatables = function () {
  30701. var results = [];
  30702. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30703. results.push(this.diffuseTexture);
  30704. }
  30705. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30706. results.push(this.ambientTexture);
  30707. }
  30708. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30709. results.push(this.opacityTexture);
  30710. }
  30711. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30712. results.push(this.reflectionTexture);
  30713. }
  30714. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30715. results.push(this.emissiveTexture);
  30716. }
  30717. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30718. results.push(this.specularTexture);
  30719. }
  30720. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30721. results.push(this.bumpTexture);
  30722. }
  30723. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30724. results.push(this.lightmapTexture);
  30725. }
  30726. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30727. results.push(this.refractionTexture);
  30728. }
  30729. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30730. results.push(this.cameraColorGradingTexture);
  30731. }
  30732. return results;
  30733. };
  30734. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30735. if (forceDisposeTextures) {
  30736. if (this.diffuseTexture) {
  30737. this.diffuseTexture.dispose();
  30738. }
  30739. if (this.ambientTexture) {
  30740. this.ambientTexture.dispose();
  30741. }
  30742. if (this.opacityTexture) {
  30743. this.opacityTexture.dispose();
  30744. }
  30745. if (this.reflectionTexture) {
  30746. this.reflectionTexture.dispose();
  30747. }
  30748. if (this.emissiveTexture) {
  30749. this.emissiveTexture.dispose();
  30750. }
  30751. if (this.specularTexture) {
  30752. this.specularTexture.dispose();
  30753. }
  30754. if (this.bumpTexture) {
  30755. this.bumpTexture.dispose();
  30756. }
  30757. if (this.lightmapTexture) {
  30758. this.lightmapTexture.dispose();
  30759. }
  30760. if (this.refractionTexture) {
  30761. this.refractionTexture.dispose();
  30762. }
  30763. if (this.cameraColorGradingTexture) {
  30764. this.cameraColorGradingTexture.dispose();
  30765. }
  30766. }
  30767. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30768. };
  30769. StandardMaterial.prototype.clone = function (name) {
  30770. var _this = this;
  30771. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30772. };
  30773. StandardMaterial.prototype.serialize = function () {
  30774. return BABYLON.SerializationHelper.Serialize(this);
  30775. };
  30776. // Statics
  30777. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30778. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30779. };
  30780. return StandardMaterial;
  30781. }(BABYLON.Material));
  30782. // Flags used to enable or disable a type of texture for all Standard Materials
  30783. StandardMaterial.DiffuseTextureEnabled = true;
  30784. StandardMaterial.AmbientTextureEnabled = true;
  30785. StandardMaterial.OpacityTextureEnabled = true;
  30786. StandardMaterial.ReflectionTextureEnabled = true;
  30787. StandardMaterial.EmissiveTextureEnabled = true;
  30788. StandardMaterial.SpecularTextureEnabled = true;
  30789. StandardMaterial.BumpTextureEnabled = true;
  30790. StandardMaterial.FresnelEnabled = true;
  30791. StandardMaterial.LightmapTextureEnabled = true;
  30792. StandardMaterial.RefractionTextureEnabled = true;
  30793. StandardMaterial.ColorGradingTextureEnabled = true;
  30794. __decorate([
  30795. BABYLON.serializeAsTexture()
  30796. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30797. __decorate([
  30798. BABYLON.serializeAsTexture()
  30799. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30800. __decorate([
  30801. BABYLON.serializeAsTexture()
  30802. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30803. __decorate([
  30804. BABYLON.serializeAsTexture()
  30805. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30806. __decorate([
  30807. BABYLON.serializeAsTexture()
  30808. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30809. __decorate([
  30810. BABYLON.serializeAsTexture()
  30811. ], StandardMaterial.prototype, "specularTexture", void 0);
  30812. __decorate([
  30813. BABYLON.serializeAsTexture()
  30814. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30815. __decorate([
  30816. BABYLON.serializeAsTexture()
  30817. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30818. __decorate([
  30819. BABYLON.serializeAsTexture()
  30820. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30821. __decorate([
  30822. BABYLON.serializeAsColor3("ambient")
  30823. ], StandardMaterial.prototype, "ambientColor", void 0);
  30824. __decorate([
  30825. BABYLON.serializeAsColor3("diffuse")
  30826. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30827. __decorate([
  30828. BABYLON.serializeAsColor3("specular")
  30829. ], StandardMaterial.prototype, "specularColor", void 0);
  30830. __decorate([
  30831. BABYLON.serializeAsColor3("emissive")
  30832. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30833. __decorate([
  30834. BABYLON.serialize()
  30835. ], StandardMaterial.prototype, "specularPower", void 0);
  30836. __decorate([
  30837. BABYLON.serialize()
  30838. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30839. __decorate([
  30840. BABYLON.serialize()
  30841. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30842. __decorate([
  30843. BABYLON.serialize()
  30844. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30845. __decorate([
  30846. BABYLON.serialize()
  30847. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30848. __decorate([
  30849. BABYLON.serialize()
  30850. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30851. __decorate([
  30852. BABYLON.serialize()
  30853. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30854. __decorate([
  30855. BABYLON.serialize()
  30856. ], StandardMaterial.prototype, "disableLighting", void 0);
  30857. __decorate([
  30858. BABYLON.serialize()
  30859. ], StandardMaterial.prototype, "useParallax", void 0);
  30860. __decorate([
  30861. BABYLON.serialize()
  30862. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30863. __decorate([
  30864. BABYLON.serialize()
  30865. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30866. __decorate([
  30867. BABYLON.serialize()
  30868. ], StandardMaterial.prototype, "roughness", void 0);
  30869. __decorate([
  30870. BABYLON.serialize()
  30871. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30872. __decorate([
  30873. BABYLON.serialize()
  30874. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30875. __decorate([
  30876. BABYLON.serialize()
  30877. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30878. __decorate([
  30879. BABYLON.serializeAsFresnelParameters()
  30880. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30881. __decorate([
  30882. BABYLON.serializeAsFresnelParameters()
  30883. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30884. __decorate([
  30885. BABYLON.serializeAsFresnelParameters()
  30886. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30887. __decorate([
  30888. BABYLON.serializeAsFresnelParameters()
  30889. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30890. __decorate([
  30891. BABYLON.serializeAsFresnelParameters()
  30892. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30893. __decorate([
  30894. BABYLON.serialize()
  30895. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30896. __decorate([
  30897. BABYLON.serialize()
  30898. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30899. __decorate([
  30900. BABYLON.serialize()
  30901. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30902. __decorate([
  30903. BABYLON.serialize()
  30904. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30908. __decorate([
  30909. BABYLON.serializeAsTexture()
  30910. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30911. __decorate([
  30912. BABYLON.serializeAsColorCurves()
  30913. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30914. __decorate([
  30915. BABYLON.serialize()
  30916. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30917. BABYLON.StandardMaterial = StandardMaterial;
  30918. })(BABYLON || (BABYLON = {}));
  30919. //# sourceMappingURL=babylon.standardMaterial.js.map
  30920. var BABYLON;
  30921. (function (BABYLON) {
  30922. var MultiMaterial = (function (_super) {
  30923. __extends(MultiMaterial, _super);
  30924. function MultiMaterial(name, scene) {
  30925. var _this = _super.call(this, name, scene, true) || this;
  30926. _this.subMaterials = new Array();
  30927. scene.multiMaterials.push(_this);
  30928. return _this;
  30929. }
  30930. // Properties
  30931. MultiMaterial.prototype.getSubMaterial = function (index) {
  30932. if (index < 0 || index >= this.subMaterials.length) {
  30933. return this.getScene().defaultMaterial;
  30934. }
  30935. return this.subMaterials[index];
  30936. };
  30937. // Methods
  30938. MultiMaterial.prototype.getClassName = function () {
  30939. return "MultiMaterial";
  30940. };
  30941. MultiMaterial.prototype.isReady = function (mesh) {
  30942. for (var index = 0; index < this.subMaterials.length; index++) {
  30943. var subMaterial = this.subMaterials[index];
  30944. if (subMaterial) {
  30945. if (!this.subMaterials[index].isReady(mesh)) {
  30946. return false;
  30947. }
  30948. }
  30949. }
  30950. return true;
  30951. };
  30952. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30953. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30954. for (var index = 0; index < this.subMaterials.length; index++) {
  30955. var subMaterial = null;
  30956. if (cloneChildren) {
  30957. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30958. }
  30959. else {
  30960. subMaterial = this.subMaterials[index];
  30961. }
  30962. newMultiMaterial.subMaterials.push(subMaterial);
  30963. }
  30964. return newMultiMaterial;
  30965. };
  30966. MultiMaterial.prototype.serialize = function () {
  30967. var serializationObject = {};
  30968. serializationObject.name = this.name;
  30969. serializationObject.id = this.id;
  30970. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30971. serializationObject.materials = [];
  30972. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30973. var subMat = this.subMaterials[matIndex];
  30974. if (subMat) {
  30975. serializationObject.materials.push(subMat.id);
  30976. }
  30977. else {
  30978. serializationObject.materials.push(null);
  30979. }
  30980. }
  30981. return serializationObject;
  30982. };
  30983. return MultiMaterial;
  30984. }(BABYLON.Material));
  30985. BABYLON.MultiMaterial = MultiMaterial;
  30986. })(BABYLON || (BABYLON = {}));
  30987. //# sourceMappingURL=babylon.multiMaterial.js.map
  30988. var BABYLON;
  30989. (function (BABYLON) {
  30990. var SceneLoader = (function () {
  30991. function SceneLoader() {
  30992. }
  30993. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30994. get: function () {
  30995. return 0;
  30996. },
  30997. enumerable: true,
  30998. configurable: true
  30999. });
  31000. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  31001. get: function () {
  31002. return 1;
  31003. },
  31004. enumerable: true,
  31005. configurable: true
  31006. });
  31007. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  31008. get: function () {
  31009. return 2;
  31010. },
  31011. enumerable: true,
  31012. configurable: true
  31013. });
  31014. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  31015. get: function () {
  31016. return 3;
  31017. },
  31018. enumerable: true,
  31019. configurable: true
  31020. });
  31021. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  31022. get: function () {
  31023. return SceneLoader._ForceFullSceneLoadingForIncremental;
  31024. },
  31025. set: function (value) {
  31026. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  31032. get: function () {
  31033. return SceneLoader._ShowLoadingScreen;
  31034. },
  31035. set: function (value) {
  31036. SceneLoader._ShowLoadingScreen = value;
  31037. },
  31038. enumerable: true,
  31039. configurable: true
  31040. });
  31041. Object.defineProperty(SceneLoader, "loggingLevel", {
  31042. get: function () {
  31043. return SceneLoader._loggingLevel;
  31044. },
  31045. set: function (value) {
  31046. SceneLoader._loggingLevel = value;
  31047. },
  31048. enumerable: true,
  31049. configurable: true
  31050. });
  31051. SceneLoader._getDefaultPlugin = function () {
  31052. return SceneLoader._registeredPlugins[".babylon"];
  31053. };
  31054. SceneLoader._getPluginForExtension = function (extension) {
  31055. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  31056. if (registeredPlugin) {
  31057. return registeredPlugin;
  31058. }
  31059. return SceneLoader._getDefaultPlugin();
  31060. };
  31061. SceneLoader._getPluginForFilename = function (sceneFilename) {
  31062. if (sceneFilename.name) {
  31063. sceneFilename = sceneFilename.name;
  31064. }
  31065. var dotPosition = sceneFilename.lastIndexOf(".");
  31066. var queryStringPosition = sceneFilename.indexOf("?");
  31067. if (queryStringPosition === -1) {
  31068. queryStringPosition = sceneFilename.length;
  31069. }
  31070. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  31071. return SceneLoader._getPluginForExtension(extension);
  31072. };
  31073. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  31074. SceneLoader._getDirectLoad = function (sceneFilename) {
  31075. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  31076. return sceneFilename.substr(5);
  31077. }
  31078. return null;
  31079. };
  31080. // Public functions
  31081. SceneLoader.GetPluginForExtension = function (extension) {
  31082. return SceneLoader._getPluginForExtension(extension).plugin;
  31083. };
  31084. SceneLoader.RegisterPlugin = function (plugin) {
  31085. if (typeof plugin.extensions === "string") {
  31086. var extension = plugin.extensions;
  31087. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31088. plugin: plugin,
  31089. isBinary: false
  31090. };
  31091. }
  31092. else {
  31093. var extensions = plugin.extensions;
  31094. Object.keys(extensions).forEach(function (extension) {
  31095. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31096. plugin: plugin,
  31097. isBinary: extensions[extension].isBinary
  31098. };
  31099. });
  31100. }
  31101. };
  31102. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31103. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31104. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31105. return;
  31106. }
  31107. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31108. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31109. return;
  31110. }
  31111. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31112. var loadingToken = {};
  31113. scene._addPendingData(loadingToken);
  31114. var manifestChecked = function (success) {
  31115. scene.database = database;
  31116. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31117. var plugin = registeredPlugin.plugin;
  31118. var useArrayBuffer = registeredPlugin.isBinary;
  31119. var importMeshFromData = function (data) {
  31120. var meshes = [];
  31121. var particleSystems = [];
  31122. var skeletons = [];
  31123. if (scene.isDisposed) {
  31124. if (onerror) {
  31125. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  31126. }
  31127. return;
  31128. }
  31129. try {
  31130. if (plugin.importMesh) {
  31131. var syncedPlugin = plugin;
  31132. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  31133. if (onerror) {
  31134. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31135. }
  31136. scene._removePendingData(loadingToken);
  31137. return;
  31138. }
  31139. if (onsuccess) {
  31140. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31141. onsuccess(meshes, particleSystems, skeletons);
  31142. scene._removePendingData(loadingToken);
  31143. }
  31144. }
  31145. else {
  31146. var asyncedPlugin = plugin;
  31147. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  31148. if (onsuccess) {
  31149. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31150. onsuccess(meshes, particleSystems, skeletons);
  31151. scene._removePendingData(loadingToken);
  31152. }
  31153. }, function () {
  31154. if (onerror) {
  31155. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31156. }
  31157. scene._removePendingData(loadingToken);
  31158. });
  31159. }
  31160. }
  31161. catch (e) {
  31162. if (onerror) {
  31163. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  31164. }
  31165. scene._removePendingData(loadingToken);
  31166. }
  31167. };
  31168. if (directLoad) {
  31169. importMeshFromData(directLoad);
  31170. return;
  31171. }
  31172. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  31173. importMeshFromData(data);
  31174. }, progressCallBack, database, useArrayBuffer, function () {
  31175. if (onerror) {
  31176. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  31177. }
  31178. });
  31179. };
  31180. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  31181. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31182. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31183. }
  31184. else {
  31185. // If the scene is a data stream or offline support is not enabled, it's a direct load
  31186. manifestChecked(true);
  31187. }
  31188. };
  31189. /**
  31190. * Load a scene
  31191. * @param rootUrl a string that defines the root url for scene and resources
  31192. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31193. * @param engine is the instance of BABYLON.Engine to use to create the scene
  31194. */
  31195. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  31196. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  31197. };
  31198. /**
  31199. * Append a scene
  31200. * @param rootUrl a string that defines the root url for scene and resources
  31201. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31202. * @param scene is the instance of BABYLON.Scene to append to
  31203. */
  31204. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31205. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31206. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31207. return;
  31208. }
  31209. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31210. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31211. var plugin = registeredPlugin.plugin;
  31212. var useArrayBuffer = registeredPlugin.isBinary;
  31213. var database;
  31214. var loadingToken = {};
  31215. scene._addPendingData(loadingToken);
  31216. if (SceneLoader.ShowLoadingScreen) {
  31217. scene.getEngine().displayLoadingUI();
  31218. }
  31219. var loadSceneFromData = function (data) {
  31220. scene.database = database;
  31221. if (plugin.load) {
  31222. var syncedPlugin = plugin;
  31223. if (!syncedPlugin.load(scene, data, rootUrl)) {
  31224. if (onerror) {
  31225. onerror(scene);
  31226. }
  31227. scene._removePendingData(loadingToken);
  31228. scene.getEngine().hideLoadingUI();
  31229. return;
  31230. }
  31231. if (onsuccess) {
  31232. onsuccess(scene);
  31233. }
  31234. scene._removePendingData(loadingToken);
  31235. }
  31236. else {
  31237. var asyncedPlugin = plugin;
  31238. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  31239. if (onsuccess) {
  31240. onsuccess(scene);
  31241. }
  31242. scene._removePendingData(loadingToken);
  31243. }, function () {
  31244. if (onerror) {
  31245. onerror(scene);
  31246. }
  31247. scene._removePendingData(loadingToken);
  31248. scene.getEngine().hideLoadingUI();
  31249. });
  31250. }
  31251. if (SceneLoader.ShowLoadingScreen) {
  31252. scene.executeWhenReady(function () {
  31253. scene.getEngine().hideLoadingUI();
  31254. });
  31255. }
  31256. };
  31257. var manifestChecked = function (success) {
  31258. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  31259. };
  31260. if (directLoad) {
  31261. loadSceneFromData(directLoad);
  31262. return;
  31263. }
  31264. if (rootUrl.indexOf("file:") === -1) {
  31265. if (scene.getEngine().enableOfflineSupport) {
  31266. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31267. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31268. }
  31269. else {
  31270. manifestChecked(true);
  31271. }
  31272. }
  31273. else {
  31274. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  31275. }
  31276. };
  31277. return SceneLoader;
  31278. }());
  31279. // Flags
  31280. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  31281. SceneLoader._ShowLoadingScreen = true;
  31282. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  31283. // Members
  31284. SceneLoader._registeredPlugins = {};
  31285. BABYLON.SceneLoader = SceneLoader;
  31286. ;
  31287. })(BABYLON || (BABYLON = {}));
  31288. //# sourceMappingURL=babylon.sceneLoader.js.map
  31289. var BABYLON;
  31290. (function (BABYLON) {
  31291. var Internals;
  31292. (function (Internals) {
  31293. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  31294. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31295. var parsedMaterial = parsedData.materials[index];
  31296. if (parsedMaterial.id === id) {
  31297. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31298. }
  31299. }
  31300. return null;
  31301. };
  31302. var isDescendantOf = function (mesh, names, hierarchyIds) {
  31303. names = (names instanceof Array) ? names : [names];
  31304. for (var i in names) {
  31305. if (mesh.name === names[i]) {
  31306. hierarchyIds.push(mesh.id);
  31307. return true;
  31308. }
  31309. }
  31310. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  31311. hierarchyIds.push(mesh.id);
  31312. return true;
  31313. }
  31314. return false;
  31315. };
  31316. var logOperation = function (operation, producer) {
  31317. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  31318. };
  31319. BABYLON.SceneLoader.RegisterPlugin({
  31320. extensions: ".babylon",
  31321. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  31322. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31323. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31324. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31325. // and avoid problems with multiple concurrent .babylon loads.
  31326. var log = "importMesh has failed JSON parse";
  31327. try {
  31328. var parsedData = JSON.parse(data);
  31329. log = "";
  31330. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31331. var loadedSkeletonsIds = [];
  31332. var loadedMaterialsIds = [];
  31333. var hierarchyIds = [];
  31334. var index;
  31335. var cache;
  31336. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31337. var parsedMesh = parsedData.meshes[index];
  31338. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  31339. if (meshesNames instanceof Array) {
  31340. // Remove found mesh name from list.
  31341. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  31342. }
  31343. //Geometry?
  31344. if (parsedMesh.geometryId) {
  31345. //does the file contain geometries?
  31346. if (parsedData.geometries) {
  31347. //find the correct geometry and add it to the scene
  31348. var found = false;
  31349. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  31350. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  31351. return;
  31352. }
  31353. else {
  31354. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  31355. if (parsedGeometryData.id === parsedMesh.geometryId) {
  31356. switch (geometryType) {
  31357. case "boxes":
  31358. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  31359. break;
  31360. case "spheres":
  31361. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  31362. break;
  31363. case "cylinders":
  31364. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  31365. break;
  31366. case "toruses":
  31367. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  31368. break;
  31369. case "grounds":
  31370. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  31371. break;
  31372. case "planes":
  31373. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  31374. break;
  31375. case "torusKnots":
  31376. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  31377. break;
  31378. case "vertexData":
  31379. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  31380. break;
  31381. }
  31382. found = true;
  31383. }
  31384. });
  31385. }
  31386. });
  31387. if (!found) {
  31388. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  31389. }
  31390. }
  31391. }
  31392. // Material ?
  31393. if (parsedMesh.materialId) {
  31394. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  31395. if (!materialFound && parsedData.multiMaterials) {
  31396. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  31397. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  31398. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  31399. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  31400. var subMatId = parsedMultiMaterial.materials[matIndex];
  31401. loadedMaterialsIds.push(subMatId);
  31402. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  31403. log += "\n\tMaterial " + mat.toString(fullDetails);
  31404. }
  31405. loadedMaterialsIds.push(parsedMultiMaterial.id);
  31406. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31407. materialFound = true;
  31408. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  31409. break;
  31410. }
  31411. }
  31412. }
  31413. if (!materialFound) {
  31414. loadedMaterialsIds.push(parsedMesh.materialId);
  31415. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  31416. if (!mat) {
  31417. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  31418. }
  31419. else {
  31420. log += "\n\tMaterial " + mat.toString(fullDetails);
  31421. }
  31422. }
  31423. }
  31424. // Skeleton ?
  31425. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  31426. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  31427. if (!skeletonAlreadyLoaded) {
  31428. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  31429. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  31430. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  31431. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31432. skeletons.push(skeleton);
  31433. loadedSkeletonsIds.push(parsedSkeleton.id);
  31434. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  31435. }
  31436. }
  31437. }
  31438. }
  31439. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31440. meshes.push(mesh);
  31441. log += "\n\tMesh " + mesh.toString(fullDetails);
  31442. }
  31443. }
  31444. // Connecting parents
  31445. var currentMesh;
  31446. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31447. currentMesh = scene.meshes[index];
  31448. if (currentMesh._waitingParentId) {
  31449. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  31450. currentMesh._waitingParentId = undefined;
  31451. }
  31452. }
  31453. // freeze and compute world matrix application
  31454. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31455. currentMesh = scene.meshes[index];
  31456. if (currentMesh._waitingFreezeWorldMatrix) {
  31457. currentMesh.freezeWorldMatrix();
  31458. currentMesh._waitingFreezeWorldMatrix = undefined;
  31459. }
  31460. else {
  31461. currentMesh.computeWorldMatrix(true);
  31462. }
  31463. }
  31464. // Particles
  31465. if (parsedData.particleSystems) {
  31466. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31467. var parsedParticleSystem = parsedData.particleSystems[index];
  31468. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  31469. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  31470. }
  31471. }
  31472. }
  31473. return true;
  31474. }
  31475. catch (err) {
  31476. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  31477. log = null;
  31478. throw err;
  31479. }
  31480. finally {
  31481. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31482. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31483. }
  31484. }
  31485. },
  31486. load: function (scene, data, rootUrl) {
  31487. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31488. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31489. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31490. // and avoid problems with multiple concurrent .babylon loads.
  31491. var log = "importScene has failed JSON parse";
  31492. try {
  31493. var parsedData = JSON.parse(data);
  31494. log = "";
  31495. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31496. // Scene
  31497. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  31498. scene.autoClear = parsedData.autoClear;
  31499. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  31500. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  31501. if (parsedData.gravity) {
  31502. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  31503. }
  31504. // Fog
  31505. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  31506. scene.fogMode = parsedData.fogMode;
  31507. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  31508. scene.fogStart = parsedData.fogStart;
  31509. scene.fogEnd = parsedData.fogEnd;
  31510. scene.fogDensity = parsedData.fogDensity;
  31511. log += "\tFog mode for scene: ";
  31512. switch (scene.fogMode) {
  31513. // getters not compiling, so using hardcoded
  31514. case 1:
  31515. log += "exp\n";
  31516. break;
  31517. case 2:
  31518. log += "exp2\n";
  31519. break;
  31520. case 3:
  31521. log += "linear\n";
  31522. break;
  31523. }
  31524. }
  31525. //Physics
  31526. if (parsedData.physicsEnabled) {
  31527. var physicsPlugin;
  31528. if (parsedData.physicsEngine === "cannon") {
  31529. physicsPlugin = new BABYLON.CannonJSPlugin();
  31530. }
  31531. else if (parsedData.physicsEngine === "oimo") {
  31532. physicsPlugin = new BABYLON.OimoJSPlugin();
  31533. }
  31534. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  31535. //else - default engine, which is currently oimo
  31536. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  31537. scene.enablePhysics(physicsGravity, physicsPlugin);
  31538. }
  31539. // Metadata
  31540. if (parsedData.metadata !== undefined) {
  31541. scene.metadata = parsedData.metadata;
  31542. }
  31543. //collisions, if defined. otherwise, default is true
  31544. if (parsedData.collisionsEnabled != undefined) {
  31545. scene.collisionsEnabled = parsedData.collisionsEnabled;
  31546. }
  31547. scene.workerCollisions = !!parsedData.workerCollisions;
  31548. var index;
  31549. var cache;
  31550. // Lights
  31551. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  31552. var parsedLight = parsedData.lights[index];
  31553. var light = BABYLON.Light.Parse(parsedLight, scene);
  31554. log += (index === 0 ? "\n\tLights:" : "");
  31555. log += "\n\t\t" + light.toString(fullDetails);
  31556. }
  31557. // Animations
  31558. if (parsedData.animations) {
  31559. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  31560. var parsedAnimation = parsedData.animations[index];
  31561. var animation = BABYLON.Animation.Parse(parsedAnimation);
  31562. scene.animations.push(animation);
  31563. log += (index === 0 ? "\n\tAnimations:" : "");
  31564. log += "\n\t\t" + animation.toString(fullDetails);
  31565. }
  31566. }
  31567. if (parsedData.autoAnimate) {
  31568. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  31569. }
  31570. // Materials
  31571. if (parsedData.materials) {
  31572. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31573. var parsedMaterial = parsedData.materials[index];
  31574. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31575. log += (index === 0 ? "\n\tMaterials:" : "");
  31576. log += "\n\t\t" + mat.toString(fullDetails);
  31577. }
  31578. }
  31579. if (parsedData.multiMaterials) {
  31580. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  31581. var parsedMultiMaterial = parsedData.multiMaterials[index];
  31582. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31583. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  31584. log += "\n\t\t" + mmat.toString(fullDetails);
  31585. }
  31586. }
  31587. // Skeletons
  31588. if (parsedData.skeletons) {
  31589. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  31590. var parsedSkeleton = parsedData.skeletons[index];
  31591. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31592. log += (index === 0 ? "\n\tSkeletons:" : "");
  31593. log += "\n\t\t" + skeleton.toString(fullDetails);
  31594. }
  31595. }
  31596. // Geometries
  31597. var geometries = parsedData.geometries;
  31598. if (geometries) {
  31599. // Boxes
  31600. var boxes = geometries.boxes;
  31601. if (boxes) {
  31602. for (index = 0, cache = boxes.length; index < cache; index++) {
  31603. var parsedBox = boxes[index];
  31604. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  31605. }
  31606. }
  31607. // Spheres
  31608. var spheres = geometries.spheres;
  31609. if (spheres) {
  31610. for (index = 0, cache = spheres.length; index < cache; index++) {
  31611. var parsedSphere = spheres[index];
  31612. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  31613. }
  31614. }
  31615. // Cylinders
  31616. var cylinders = geometries.cylinders;
  31617. if (cylinders) {
  31618. for (index = 0, cache = cylinders.length; index < cache; index++) {
  31619. var parsedCylinder = cylinders[index];
  31620. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  31621. }
  31622. }
  31623. // Toruses
  31624. var toruses = geometries.toruses;
  31625. if (toruses) {
  31626. for (index = 0, cache = toruses.length; index < cache; index++) {
  31627. var parsedTorus = toruses[index];
  31628. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31629. }
  31630. }
  31631. // Grounds
  31632. var grounds = geometries.grounds;
  31633. if (grounds) {
  31634. for (index = 0, cache = grounds.length; index < cache; index++) {
  31635. var parsedGround = grounds[index];
  31636. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31637. }
  31638. }
  31639. // Planes
  31640. var planes = geometries.planes;
  31641. if (planes) {
  31642. for (index = 0, cache = planes.length; index < cache; index++) {
  31643. var parsedPlane = planes[index];
  31644. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31645. }
  31646. }
  31647. // TorusKnots
  31648. var torusKnots = geometries.torusKnots;
  31649. if (torusKnots) {
  31650. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31651. var parsedTorusKnot = torusKnots[index];
  31652. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31653. }
  31654. }
  31655. // VertexData
  31656. var vertexData = geometries.vertexData;
  31657. if (vertexData) {
  31658. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31659. var parsedVertexData = vertexData[index];
  31660. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31661. }
  31662. }
  31663. }
  31664. // Meshes
  31665. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31666. var parsedMesh = parsedData.meshes[index];
  31667. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31668. log += (index === 0 ? "\n\tMeshes:" : "");
  31669. log += "\n\t\t" + mesh.toString(fullDetails);
  31670. }
  31671. // Cameras
  31672. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31673. var parsedCamera = parsedData.cameras[index];
  31674. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31675. log += (index === 0 ? "\n\tCameras:" : "");
  31676. log += "\n\t\t" + camera.toString(fullDetails);
  31677. }
  31678. if (parsedData.activeCameraID) {
  31679. scene.setActiveCameraByID(parsedData.activeCameraID);
  31680. }
  31681. // Browsing all the graph to connect the dots
  31682. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31683. var camera = scene.cameras[index];
  31684. if (camera._waitingParentId) {
  31685. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31686. camera._waitingParentId = undefined;
  31687. }
  31688. }
  31689. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31690. var light = scene.lights[index];
  31691. if (light._waitingParentId) {
  31692. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31693. light._waitingParentId = undefined;
  31694. }
  31695. }
  31696. // Sounds
  31697. var loadedSounds = [];
  31698. var loadedSound;
  31699. if (BABYLON.AudioEngine && parsedData.sounds) {
  31700. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31701. var parsedSound = parsedData.sounds[index];
  31702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31703. if (!parsedSound.url)
  31704. parsedSound.url = parsedSound.name;
  31705. if (!loadedSounds[parsedSound.url]) {
  31706. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31707. loadedSounds[parsedSound.url] = loadedSound;
  31708. }
  31709. else {
  31710. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31711. }
  31712. }
  31713. else {
  31714. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31715. }
  31716. }
  31717. }
  31718. loadedSounds = [];
  31719. // Connect parents & children and parse actions
  31720. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31721. var mesh = scene.meshes[index];
  31722. if (mesh._waitingParentId) {
  31723. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31724. mesh._waitingParentId = undefined;
  31725. }
  31726. if (mesh._waitingActions) {
  31727. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31728. mesh._waitingActions = undefined;
  31729. }
  31730. }
  31731. // freeze world matrix application
  31732. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31733. var currentMesh = scene.meshes[index];
  31734. if (currentMesh._waitingFreezeWorldMatrix) {
  31735. currentMesh.freezeWorldMatrix();
  31736. currentMesh._waitingFreezeWorldMatrix = undefined;
  31737. }
  31738. else {
  31739. currentMesh.computeWorldMatrix(true);
  31740. }
  31741. }
  31742. // Particles Systems
  31743. if (parsedData.particleSystems) {
  31744. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31745. var parsedParticleSystem = parsedData.particleSystems[index];
  31746. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31747. }
  31748. }
  31749. // Lens flares
  31750. if (parsedData.lensFlareSystems) {
  31751. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31752. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31753. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31754. }
  31755. }
  31756. // Shadows
  31757. if (parsedData.shadowGenerators) {
  31758. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31759. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31760. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31761. }
  31762. }
  31763. // Actions (scene)
  31764. if (parsedData.actions) {
  31765. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31766. }
  31767. // Finish
  31768. return true;
  31769. }
  31770. catch (err) {
  31771. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31772. log = null;
  31773. throw err;
  31774. }
  31775. finally {
  31776. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31777. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31778. }
  31779. }
  31780. }
  31781. });
  31782. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31783. })(BABYLON || (BABYLON = {}));
  31784. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31785. var BABYLON;
  31786. (function (BABYLON) {
  31787. var SpriteManager = (function () {
  31788. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31789. if (epsilon === void 0) { epsilon = 0.01; }
  31790. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31791. this.name = name;
  31792. this.sprites = new Array();
  31793. this.renderingGroupId = 0;
  31794. this.layerMask = 0x0FFFFFFF;
  31795. this.fogEnabled = true;
  31796. this.isPickable = false;
  31797. /**
  31798. * An event triggered when the manager is disposed.
  31799. * @type {BABYLON.Observable}
  31800. */
  31801. this.onDisposeObservable = new BABYLON.Observable();
  31802. this._vertexBuffers = {};
  31803. this._capacity = capacity;
  31804. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31805. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31806. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31807. if (cellSize.width && cellSize.height) {
  31808. this.cellWidth = cellSize.width;
  31809. this.cellHeight = cellSize.height;
  31810. }
  31811. else if (cellSize !== undefined) {
  31812. this.cellWidth = cellSize;
  31813. this.cellHeight = cellSize;
  31814. }
  31815. else {
  31816. return;
  31817. }
  31818. this._epsilon = epsilon;
  31819. this._scene = scene;
  31820. this._scene.spriteManagers.push(this);
  31821. var indices = [];
  31822. var index = 0;
  31823. for (var count = 0; count < capacity; count++) {
  31824. indices.push(index);
  31825. indices.push(index + 1);
  31826. indices.push(index + 2);
  31827. indices.push(index);
  31828. indices.push(index + 2);
  31829. indices.push(index + 3);
  31830. index += 4;
  31831. }
  31832. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31833. // VBO
  31834. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31835. this._vertexData = new Float32Array(capacity * 16 * 4);
  31836. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31837. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31838. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31839. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31840. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31841. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31842. this._vertexBuffers["options"] = options;
  31843. this._vertexBuffers["cellInfo"] = cellInfo;
  31844. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31845. // Effects
  31846. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31847. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31848. }
  31849. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31850. set: function (callback) {
  31851. if (this._onDisposeObserver) {
  31852. this.onDisposeObservable.remove(this._onDisposeObserver);
  31853. }
  31854. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31855. },
  31856. enumerable: true,
  31857. configurable: true
  31858. });
  31859. Object.defineProperty(SpriteManager.prototype, "texture", {
  31860. get: function () {
  31861. return this._spriteTexture;
  31862. },
  31863. set: function (value) {
  31864. this._spriteTexture = value;
  31865. },
  31866. enumerable: true,
  31867. configurable: true
  31868. });
  31869. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31870. var arrayOffset = index * 16;
  31871. if (offsetX === 0)
  31872. offsetX = this._epsilon;
  31873. else if (offsetX === 1)
  31874. offsetX = 1 - this._epsilon;
  31875. if (offsetY === 0)
  31876. offsetY = this._epsilon;
  31877. else if (offsetY === 1)
  31878. offsetY = 1 - this._epsilon;
  31879. this._vertexData[arrayOffset] = sprite.position.x;
  31880. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31881. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31882. this._vertexData[arrayOffset + 3] = sprite.angle;
  31883. this._vertexData[arrayOffset + 4] = sprite.width;
  31884. this._vertexData[arrayOffset + 5] = sprite.height;
  31885. this._vertexData[arrayOffset + 6] = offsetX;
  31886. this._vertexData[arrayOffset + 7] = offsetY;
  31887. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31888. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31889. var offset = (sprite.cellIndex / rowSize) >> 0;
  31890. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31891. this._vertexData[arrayOffset + 11] = offset;
  31892. // Color
  31893. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31894. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31895. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31896. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31897. };
  31898. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31899. var count = Math.min(this._capacity, this.sprites.length);
  31900. var min = BABYLON.Vector3.Zero();
  31901. var max = BABYLON.Vector3.Zero();
  31902. var distance = Number.MAX_VALUE;
  31903. var currentSprite;
  31904. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31905. var cameraView = camera.getViewMatrix();
  31906. for (var index = 0; index < count; index++) {
  31907. var sprite = this.sprites[index];
  31908. if (!sprite) {
  31909. continue;
  31910. }
  31911. if (predicate) {
  31912. if (!predicate(sprite)) {
  31913. continue;
  31914. }
  31915. }
  31916. else if (!sprite.isPickable) {
  31917. continue;
  31918. }
  31919. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31920. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31921. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31922. if (ray.intersectsBoxMinMax(min, max)) {
  31923. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31924. if (distance > currentDistance) {
  31925. distance = currentDistance;
  31926. currentSprite = sprite;
  31927. if (fastCheck) {
  31928. break;
  31929. }
  31930. }
  31931. }
  31932. }
  31933. if (currentSprite) {
  31934. var result = new BABYLON.PickingInfo();
  31935. result.hit = true;
  31936. result.pickedSprite = currentSprite;
  31937. result.distance = distance;
  31938. return result;
  31939. }
  31940. return null;
  31941. };
  31942. SpriteManager.prototype.render = function () {
  31943. // Check
  31944. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31945. return;
  31946. var engine = this._scene.getEngine();
  31947. var baseSize = this._spriteTexture.getBaseSize();
  31948. // Sprites
  31949. var deltaTime = engine.getDeltaTime();
  31950. var max = Math.min(this._capacity, this.sprites.length);
  31951. var rowSize = baseSize.width / this.cellWidth;
  31952. var offset = 0;
  31953. for (var index = 0; index < max; index++) {
  31954. var sprite = this.sprites[index];
  31955. if (!sprite) {
  31956. continue;
  31957. }
  31958. sprite._animate(deltaTime);
  31959. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31960. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31961. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31962. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31963. }
  31964. this._buffer.update(this._vertexData);
  31965. // Render
  31966. var effect = this._effectBase;
  31967. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31968. effect = this._effectFog;
  31969. }
  31970. engine.enableEffect(effect);
  31971. var viewMatrix = this._scene.getViewMatrix();
  31972. effect.setTexture("diffuseSampler", this._spriteTexture);
  31973. effect.setMatrix("view", viewMatrix);
  31974. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31975. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31976. // Fog
  31977. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31978. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31979. effect.setColor3("vFogColor", this._scene.fogColor);
  31980. }
  31981. // VBOs
  31982. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31983. // Draw order
  31984. engine.setDepthFunctionToLessOrEqual();
  31985. effect.setBool("alphaTest", true);
  31986. engine.setColorWrite(false);
  31987. engine.draw(true, 0, max * 6);
  31988. engine.setColorWrite(true);
  31989. effect.setBool("alphaTest", false);
  31990. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31991. engine.draw(true, 0, max * 6);
  31992. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31993. };
  31994. SpriteManager.prototype.dispose = function () {
  31995. if (this._buffer) {
  31996. this._buffer.dispose();
  31997. this._buffer = null;
  31998. }
  31999. if (this._indexBuffer) {
  32000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32001. this._indexBuffer = null;
  32002. }
  32003. if (this._spriteTexture) {
  32004. this._spriteTexture.dispose();
  32005. this._spriteTexture = null;
  32006. }
  32007. // Remove from scene
  32008. var index = this._scene.spriteManagers.indexOf(this);
  32009. this._scene.spriteManagers.splice(index, 1);
  32010. // Callback
  32011. this.onDisposeObservable.notifyObservers(this);
  32012. this.onDisposeObservable.clear();
  32013. };
  32014. return SpriteManager;
  32015. }());
  32016. BABYLON.SpriteManager = SpriteManager;
  32017. })(BABYLON || (BABYLON = {}));
  32018. //# sourceMappingURL=babylon.spriteManager.js.map
  32019. var BABYLON;
  32020. (function (BABYLON) {
  32021. var Sprite = (function () {
  32022. function Sprite(name, manager) {
  32023. this.name = name;
  32024. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32025. this.width = 1.0;
  32026. this.height = 1.0;
  32027. this.angle = 0;
  32028. this.cellIndex = 0;
  32029. this.invertU = 0;
  32030. this.invertV = 0;
  32031. this.animations = new Array();
  32032. this.isPickable = false;
  32033. this._animationStarted = false;
  32034. this._loopAnimation = false;
  32035. this._fromIndex = 0;
  32036. this._toIndex = 0;
  32037. this._delay = 0;
  32038. this._direction = 1;
  32039. this._frameCount = 0;
  32040. this._time = 0;
  32041. this._manager = manager;
  32042. this._manager.sprites.push(this);
  32043. this.position = BABYLON.Vector3.Zero();
  32044. }
  32045. Object.defineProperty(Sprite.prototype, "size", {
  32046. get: function () {
  32047. return this.width;
  32048. },
  32049. set: function (value) {
  32050. this.width = value;
  32051. this.height = value;
  32052. },
  32053. enumerable: true,
  32054. configurable: true
  32055. });
  32056. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  32057. this._fromIndex = from;
  32058. this._toIndex = to;
  32059. this._loopAnimation = loop;
  32060. this._delay = delay;
  32061. this._animationStarted = true;
  32062. this._direction = from < to ? 1 : -1;
  32063. this.cellIndex = from;
  32064. this._time = 0;
  32065. this._onAnimationEnd = onAnimationEnd;
  32066. };
  32067. Sprite.prototype.stopAnimation = function () {
  32068. this._animationStarted = false;
  32069. };
  32070. Sprite.prototype._animate = function (deltaTime) {
  32071. if (!this._animationStarted)
  32072. return;
  32073. this._time += deltaTime;
  32074. if (this._time > this._delay) {
  32075. this._time = this._time % this._delay;
  32076. this.cellIndex += this._direction;
  32077. if (this.cellIndex === this._toIndex) {
  32078. if (this._loopAnimation) {
  32079. this.cellIndex = this._fromIndex;
  32080. }
  32081. else {
  32082. this._animationStarted = false;
  32083. if (this._onAnimationEnd) {
  32084. this._onAnimationEnd();
  32085. }
  32086. if (this.disposeWhenFinishedAnimating) {
  32087. this.dispose();
  32088. }
  32089. }
  32090. }
  32091. }
  32092. };
  32093. Sprite.prototype.dispose = function () {
  32094. for (var i = 0; i < this._manager.sprites.length; i++) {
  32095. if (this._manager.sprites[i] == this) {
  32096. this._manager.sprites.splice(i, 1);
  32097. }
  32098. }
  32099. };
  32100. return Sprite;
  32101. }());
  32102. BABYLON.Sprite = Sprite;
  32103. })(BABYLON || (BABYLON = {}));
  32104. //# sourceMappingURL=babylon.sprite.js.map
  32105. var BABYLON;
  32106. (function (BABYLON) {
  32107. var Layer = (function () {
  32108. function Layer(name, imgUrl, scene, isBackground, color) {
  32109. this.name = name;
  32110. this.scale = new BABYLON.Vector2(1, 1);
  32111. this.offset = new BABYLON.Vector2(0, 0);
  32112. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  32113. this._vertexBuffers = {};
  32114. // Events
  32115. /**
  32116. * An event triggered when the layer is disposed.
  32117. * @type {BABYLON.Observable}
  32118. */
  32119. this.onDisposeObservable = new BABYLON.Observable();
  32120. /**
  32121. * An event triggered before rendering the scene
  32122. * @type {BABYLON.Observable}
  32123. */
  32124. this.onBeforeRenderObservable = new BABYLON.Observable();
  32125. /**
  32126. * An event triggered after rendering the scene
  32127. * @type {BABYLON.Observable}
  32128. */
  32129. this.onAfterRenderObservable = new BABYLON.Observable();
  32130. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  32131. this.isBackground = isBackground === undefined ? true : isBackground;
  32132. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  32133. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32134. this._scene.layers.push(this);
  32135. var engine = scene.getEngine();
  32136. // VBO
  32137. var vertices = [];
  32138. vertices.push(1, 1);
  32139. vertices.push(-1, 1);
  32140. vertices.push(-1, -1);
  32141. vertices.push(1, -1);
  32142. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32143. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  32144. // Indices
  32145. var indices = [];
  32146. indices.push(0);
  32147. indices.push(1);
  32148. indices.push(2);
  32149. indices.push(0);
  32150. indices.push(2);
  32151. indices.push(3);
  32152. this._indexBuffer = engine.createIndexBuffer(indices);
  32153. // Effects
  32154. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  32155. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  32156. }
  32157. Object.defineProperty(Layer.prototype, "onDispose", {
  32158. set: function (callback) {
  32159. if (this._onDisposeObserver) {
  32160. this.onDisposeObservable.remove(this._onDisposeObserver);
  32161. }
  32162. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32163. },
  32164. enumerable: true,
  32165. configurable: true
  32166. });
  32167. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  32168. set: function (callback) {
  32169. if (this._onBeforeRenderObserver) {
  32170. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32171. }
  32172. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32173. },
  32174. enumerable: true,
  32175. configurable: true
  32176. });
  32177. Object.defineProperty(Layer.prototype, "onAfterRender", {
  32178. set: function (callback) {
  32179. if (this._onAfterRenderObserver) {
  32180. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32181. }
  32182. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32183. },
  32184. enumerable: true,
  32185. configurable: true
  32186. });
  32187. Layer.prototype.render = function () {
  32188. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  32189. // Check
  32190. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  32191. return;
  32192. var engine = this._scene.getEngine();
  32193. this.onBeforeRenderObservable.notifyObservers(this);
  32194. // Render
  32195. engine.enableEffect(currentEffect);
  32196. engine.setState(false);
  32197. // Texture
  32198. currentEffect.setTexture("textureSampler", this.texture);
  32199. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  32200. // Color
  32201. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  32202. // Scale / offset
  32203. currentEffect.setVector2("offset", this.offset);
  32204. currentEffect.setVector2("scale", this.scale);
  32205. // VBOs
  32206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  32207. // Draw order
  32208. if (!this.alphaTest) {
  32209. engine.setAlphaMode(this.alphaBlendingMode);
  32210. engine.draw(true, 0, 6);
  32211. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32212. }
  32213. else {
  32214. engine.draw(true, 0, 6);
  32215. }
  32216. this.onAfterRenderObservable.notifyObservers(this);
  32217. };
  32218. Layer.prototype.dispose = function () {
  32219. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32220. if (vertexBuffer) {
  32221. vertexBuffer.dispose();
  32222. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32223. }
  32224. if (this._indexBuffer) {
  32225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32226. this._indexBuffer = null;
  32227. }
  32228. if (this.texture) {
  32229. this.texture.dispose();
  32230. this.texture = null;
  32231. }
  32232. // Remove from scene
  32233. var index = this._scene.layers.indexOf(this);
  32234. this._scene.layers.splice(index, 1);
  32235. // Callback
  32236. this.onDisposeObservable.notifyObservers(this);
  32237. this.onDisposeObservable.clear();
  32238. this.onAfterRenderObservable.clear();
  32239. this.onBeforeRenderObservable.clear();
  32240. };
  32241. return Layer;
  32242. }());
  32243. BABYLON.Layer = Layer;
  32244. })(BABYLON || (BABYLON = {}));
  32245. //# sourceMappingURL=babylon.layer.js.map
  32246. var BABYLON;
  32247. (function (BABYLON) {
  32248. var Particle = (function () {
  32249. function Particle() {
  32250. this.position = BABYLON.Vector3.Zero();
  32251. this.direction = BABYLON.Vector3.Zero();
  32252. this.color = new BABYLON.Color4(0, 0, 0, 0);
  32253. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  32254. this.lifeTime = 1.0;
  32255. this.age = 0;
  32256. this.size = 0;
  32257. this.angle = 0;
  32258. this.angularSpeed = 0;
  32259. }
  32260. Particle.prototype.copyTo = function (other) {
  32261. other.position.copyFrom(this.position);
  32262. other.direction.copyFrom(this.direction);
  32263. other.color.copyFrom(this.color);
  32264. other.colorStep.copyFrom(this.colorStep);
  32265. other.lifeTime = this.lifeTime;
  32266. other.age = this.age;
  32267. other.size = this.size;
  32268. other.angle = this.angle;
  32269. other.angularSpeed = this.angularSpeed;
  32270. };
  32271. return Particle;
  32272. }());
  32273. BABYLON.Particle = Particle;
  32274. })(BABYLON || (BABYLON = {}));
  32275. //# sourceMappingURL=babylon.particle.js.map
  32276. var BABYLON;
  32277. (function (BABYLON) {
  32278. var randomNumber = function (min, max) {
  32279. if (min === max) {
  32280. return (min);
  32281. }
  32282. var random = Math.random();
  32283. return ((random * (max - min)) + min);
  32284. };
  32285. var ParticleSystem = (function () {
  32286. function ParticleSystem(name, capacity, scene, customEffect) {
  32287. var _this = this;
  32288. this.name = name;
  32289. // Members
  32290. this.animations = [];
  32291. this.renderingGroupId = 0;
  32292. this.emitter = null;
  32293. this.emitRate = 10;
  32294. this.manualEmitCount = -1;
  32295. this.updateSpeed = 0.01;
  32296. this.targetStopDuration = 0;
  32297. this.disposeOnStop = false;
  32298. this.minEmitPower = 1;
  32299. this.maxEmitPower = 1;
  32300. this.minLifeTime = 1;
  32301. this.maxLifeTime = 1;
  32302. this.minSize = 1;
  32303. this.maxSize = 1;
  32304. this.minAngularSpeed = 0;
  32305. this.maxAngularSpeed = 0;
  32306. this.layerMask = 0x0FFFFFFF;
  32307. this.customShader = null;
  32308. this.preventAutoStart = false;
  32309. /**
  32310. * An event triggered when the system is disposed.
  32311. * @type {BABYLON.Observable}
  32312. */
  32313. this.onDisposeObservable = new BABYLON.Observable();
  32314. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  32315. this.forceDepthWrite = false;
  32316. this.gravity = BABYLON.Vector3.Zero();
  32317. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  32318. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  32319. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  32320. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32321. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32322. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32323. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  32324. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32325. this.particles = new Array();
  32326. this._stockParticles = new Array();
  32327. this._newPartsExcess = 0;
  32328. this._vertexBuffers = {};
  32329. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  32330. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  32331. this._scaledDirection = BABYLON.Vector3.Zero();
  32332. this._scaledGravity = BABYLON.Vector3.Zero();
  32333. this._currentRenderId = -1;
  32334. this._started = false;
  32335. this._stopped = false;
  32336. this._actualFrame = 0;
  32337. this.id = name;
  32338. this._capacity = capacity;
  32339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32340. this._customEffect = customEffect;
  32341. scene.particleSystems.push(this);
  32342. var indices = [];
  32343. var index = 0;
  32344. for (var count = 0; count < capacity; count++) {
  32345. indices.push(index);
  32346. indices.push(index + 1);
  32347. indices.push(index + 2);
  32348. indices.push(index);
  32349. indices.push(index + 2);
  32350. indices.push(index + 3);
  32351. index += 4;
  32352. }
  32353. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32354. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  32355. this._vertexData = new Float32Array(capacity * 11 * 4);
  32356. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  32357. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  32358. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  32359. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  32360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32361. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32362. this._vertexBuffers["options"] = options;
  32363. // Default behaviors
  32364. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  32365. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  32366. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  32367. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  32368. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  32369. };
  32370. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  32371. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  32372. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  32373. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  32374. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  32375. };
  32376. this.updateFunction = function (particles) {
  32377. for (var index = 0; index < particles.length; index++) {
  32378. var particle = particles[index];
  32379. particle.age += _this._scaledUpdateSpeed;
  32380. if (particle.age >= particle.lifeTime) {
  32381. _this.recycleParticle(particle);
  32382. index--;
  32383. continue;
  32384. }
  32385. else {
  32386. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  32387. particle.color.addInPlace(_this._scaledColorStep);
  32388. if (particle.color.a < 0)
  32389. particle.color.a = 0;
  32390. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  32391. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  32392. particle.position.addInPlace(_this._scaledDirection);
  32393. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  32394. particle.direction.addInPlace(_this._scaledGravity);
  32395. }
  32396. }
  32397. };
  32398. }
  32399. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  32400. set: function (callback) {
  32401. if (this._onDisposeObserver) {
  32402. this.onDisposeObservable.remove(this._onDisposeObserver);
  32403. }
  32404. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32405. },
  32406. enumerable: true,
  32407. configurable: true
  32408. });
  32409. ParticleSystem.prototype.recycleParticle = function (particle) {
  32410. var lastParticle = this.particles.pop();
  32411. if (lastParticle !== particle) {
  32412. lastParticle.copyTo(particle);
  32413. this._stockParticles.push(lastParticle);
  32414. }
  32415. };
  32416. ParticleSystem.prototype.getCapacity = function () {
  32417. return this._capacity;
  32418. };
  32419. ParticleSystem.prototype.isAlive = function () {
  32420. return this._alive;
  32421. };
  32422. ParticleSystem.prototype.isStarted = function () {
  32423. return this._started;
  32424. };
  32425. ParticleSystem.prototype.start = function () {
  32426. this._started = true;
  32427. this._stopped = false;
  32428. this._actualFrame = 0;
  32429. };
  32430. ParticleSystem.prototype.stop = function () {
  32431. this._stopped = true;
  32432. };
  32433. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  32434. var offset = index * 11;
  32435. this._vertexData[offset] = particle.position.x;
  32436. this._vertexData[offset + 1] = particle.position.y;
  32437. this._vertexData[offset + 2] = particle.position.z;
  32438. this._vertexData[offset + 3] = particle.color.r;
  32439. this._vertexData[offset + 4] = particle.color.g;
  32440. this._vertexData[offset + 5] = particle.color.b;
  32441. this._vertexData[offset + 6] = particle.color.a;
  32442. this._vertexData[offset + 7] = particle.angle;
  32443. this._vertexData[offset + 8] = particle.size;
  32444. this._vertexData[offset + 9] = offsetX;
  32445. this._vertexData[offset + 10] = offsetY;
  32446. };
  32447. ParticleSystem.prototype._update = function (newParticles) {
  32448. // Update current
  32449. this._alive = this.particles.length > 0;
  32450. this.updateFunction(this.particles);
  32451. // Add new ones
  32452. var worldMatrix;
  32453. if (this.emitter.position) {
  32454. worldMatrix = this.emitter.getWorldMatrix();
  32455. }
  32456. else {
  32457. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  32458. }
  32459. var particle;
  32460. for (var index = 0; index < newParticles; index++) {
  32461. if (this.particles.length === this._capacity) {
  32462. break;
  32463. }
  32464. if (this._stockParticles.length !== 0) {
  32465. particle = this._stockParticles.pop();
  32466. particle.age = 0;
  32467. }
  32468. else {
  32469. particle = new BABYLON.Particle();
  32470. }
  32471. this.particles.push(particle);
  32472. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  32473. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  32474. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  32475. particle.size = randomNumber(this.minSize, this.maxSize);
  32476. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  32477. this.startPositionFunction(worldMatrix, particle.position, particle);
  32478. var step = randomNumber(0, 1.0);
  32479. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  32480. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  32481. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  32482. }
  32483. };
  32484. ParticleSystem.prototype._getEffect = function () {
  32485. if (this._customEffect) {
  32486. return this._customEffect;
  32487. }
  32488. ;
  32489. var defines = [];
  32490. if (this._scene.clipPlane) {
  32491. defines.push("#define CLIPPLANE");
  32492. }
  32493. // Effect
  32494. var join = defines.join("\n");
  32495. if (this._cachedDefines !== join) {
  32496. this._cachedDefines = join;
  32497. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  32498. }
  32499. return this._effect;
  32500. };
  32501. ParticleSystem.prototype.animate = function () {
  32502. if (!this._started)
  32503. return;
  32504. var effect = this._getEffect();
  32505. // Check
  32506. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  32507. return;
  32508. if (this._currentRenderId === this._scene.getRenderId()) {
  32509. return;
  32510. }
  32511. this._currentRenderId = this._scene.getRenderId();
  32512. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  32513. // determine the number of particles we need to create
  32514. var newParticles;
  32515. if (this.manualEmitCount > -1) {
  32516. newParticles = this.manualEmitCount;
  32517. this._newPartsExcess = 0;
  32518. this.manualEmitCount = 0;
  32519. }
  32520. else {
  32521. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  32522. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  32523. }
  32524. if (this._newPartsExcess > 1.0) {
  32525. newParticles += this._newPartsExcess >> 0;
  32526. this._newPartsExcess -= this._newPartsExcess >> 0;
  32527. }
  32528. this._alive = false;
  32529. if (!this._stopped) {
  32530. this._actualFrame += this._scaledUpdateSpeed;
  32531. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  32532. this.stop();
  32533. }
  32534. else {
  32535. newParticles = 0;
  32536. }
  32537. this._update(newParticles);
  32538. // Stopped?
  32539. if (this._stopped) {
  32540. if (!this._alive) {
  32541. this._started = false;
  32542. if (this.disposeOnStop) {
  32543. this._scene._toBeDisposed.push(this);
  32544. }
  32545. }
  32546. }
  32547. // Update VBO
  32548. var offset = 0;
  32549. for (var index = 0; index < this.particles.length; index++) {
  32550. var particle = this.particles[index];
  32551. this._appendParticleVertex(offset++, particle, 0, 0);
  32552. this._appendParticleVertex(offset++, particle, 1, 0);
  32553. this._appendParticleVertex(offset++, particle, 1, 1);
  32554. this._appendParticleVertex(offset++, particle, 0, 1);
  32555. }
  32556. this._vertexBuffer.update(this._vertexData);
  32557. };
  32558. ParticleSystem.prototype.render = function () {
  32559. var effect = this._getEffect();
  32560. // Check
  32561. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  32562. return 0;
  32563. var engine = this._scene.getEngine();
  32564. // Render
  32565. engine.enableEffect(effect);
  32566. engine.setState(false);
  32567. var viewMatrix = this._scene.getViewMatrix();
  32568. effect.setTexture("diffuseSampler", this.particleTexture);
  32569. effect.setMatrix("view", viewMatrix);
  32570. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32571. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  32572. if (this._scene.clipPlane) {
  32573. var clipPlane = this._scene.clipPlane;
  32574. var invView = viewMatrix.clone();
  32575. invView.invert();
  32576. effect.setMatrix("invView", invView);
  32577. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  32578. }
  32579. // VBOs
  32580. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32581. // Draw order
  32582. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  32583. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32584. }
  32585. else {
  32586. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32587. }
  32588. if (this.forceDepthWrite) {
  32589. engine.setDepthWrite(true);
  32590. }
  32591. engine.draw(true, 0, this.particles.length * 6);
  32592. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32593. return this.particles.length;
  32594. };
  32595. ParticleSystem.prototype.dispose = function () {
  32596. if (this._vertexBuffer) {
  32597. this._vertexBuffer.dispose();
  32598. this._vertexBuffer = null;
  32599. }
  32600. if (this._indexBuffer) {
  32601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32602. this._indexBuffer = null;
  32603. }
  32604. if (this.particleTexture) {
  32605. this.particleTexture.dispose();
  32606. this.particleTexture = null;
  32607. }
  32608. // Remove from scene
  32609. var index = this._scene.particleSystems.indexOf(this);
  32610. this._scene.particleSystems.splice(index, 1);
  32611. // Callback
  32612. this.onDisposeObservable.notifyObservers(this);
  32613. this.onDisposeObservable.clear();
  32614. };
  32615. // Clone
  32616. ParticleSystem.prototype.clone = function (name, newEmitter) {
  32617. var custom = null;
  32618. var program = null;
  32619. if (this.customShader != null) {
  32620. program = this.customShader;
  32621. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32622. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32623. }
  32624. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32625. result.customShader = program;
  32626. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32627. if (newEmitter === undefined) {
  32628. newEmitter = this.emitter;
  32629. }
  32630. result.emitter = newEmitter;
  32631. if (this.particleTexture) {
  32632. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32633. }
  32634. if (!this.preventAutoStart) {
  32635. result.start();
  32636. }
  32637. return result;
  32638. };
  32639. ParticleSystem.prototype.serialize = function () {
  32640. var serializationObject = {};
  32641. serializationObject.name = this.name;
  32642. serializationObject.id = this.id;
  32643. // Emitter
  32644. if (this.emitter.position) {
  32645. serializationObject.emitterId = this.emitter.id;
  32646. }
  32647. else {
  32648. serializationObject.emitter = this.emitter.asArray();
  32649. }
  32650. serializationObject.capacity = this.getCapacity();
  32651. if (this.particleTexture) {
  32652. serializationObject.textureName = this.particleTexture.name;
  32653. }
  32654. // Animations
  32655. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32656. // Particle system
  32657. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32658. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32659. serializationObject.minSize = this.minSize;
  32660. serializationObject.maxSize = this.maxSize;
  32661. serializationObject.minEmitPower = this.minEmitPower;
  32662. serializationObject.maxEmitPower = this.maxEmitPower;
  32663. serializationObject.minLifeTime = this.minLifeTime;
  32664. serializationObject.maxLifeTime = this.maxLifeTime;
  32665. serializationObject.emitRate = this.emitRate;
  32666. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32667. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32668. serializationObject.gravity = this.gravity.asArray();
  32669. serializationObject.direction1 = this.direction1.asArray();
  32670. serializationObject.direction2 = this.direction2.asArray();
  32671. serializationObject.color1 = this.color1.asArray();
  32672. serializationObject.color2 = this.color2.asArray();
  32673. serializationObject.colorDead = this.colorDead.asArray();
  32674. serializationObject.updateSpeed = this.updateSpeed;
  32675. serializationObject.targetStopDuration = this.targetStopDuration;
  32676. serializationObject.textureMask = this.textureMask.asArray();
  32677. serializationObject.blendMode = this.blendMode;
  32678. serializationObject.customShader = this.customShader;
  32679. serializationObject.preventAutoStart = this.preventAutoStart;
  32680. return serializationObject;
  32681. };
  32682. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32683. var name = parsedParticleSystem.name;
  32684. var custom = null;
  32685. var program = null;
  32686. if (parsedParticleSystem.customShader) {
  32687. program = parsedParticleSystem.customShader;
  32688. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32689. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32690. }
  32691. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32692. particleSystem.customShader = program;
  32693. if (parsedParticleSystem.id) {
  32694. particleSystem.id = parsedParticleSystem.id;
  32695. }
  32696. // Auto start
  32697. if (parsedParticleSystem.preventAutoStart) {
  32698. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32699. }
  32700. // Texture
  32701. if (parsedParticleSystem.textureName) {
  32702. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32703. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32704. }
  32705. // Emitter
  32706. if (parsedParticleSystem.emitterId) {
  32707. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32708. }
  32709. else {
  32710. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32711. }
  32712. // Animations
  32713. if (parsedParticleSystem.animations) {
  32714. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32715. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32716. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32717. }
  32718. }
  32719. if (parsedParticleSystem.autoAnimate) {
  32720. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32721. }
  32722. // Particle system
  32723. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32724. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32725. particleSystem.minSize = parsedParticleSystem.minSize;
  32726. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32727. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32728. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32729. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32730. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32731. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32732. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32733. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32734. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32735. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32736. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32737. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32738. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32739. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32740. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32741. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32742. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32743. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32744. if (!particleSystem.preventAutoStart) {
  32745. particleSystem.start();
  32746. }
  32747. return particleSystem;
  32748. };
  32749. return ParticleSystem;
  32750. }());
  32751. // Statics
  32752. ParticleSystem.BLENDMODE_ONEONE = 0;
  32753. ParticleSystem.BLENDMODE_STANDARD = 1;
  32754. BABYLON.ParticleSystem = ParticleSystem;
  32755. })(BABYLON || (BABYLON = {}));
  32756. //# sourceMappingURL=babylon.particleSystem.js.map
  32757. var BABYLON;
  32758. (function (BABYLON) {
  32759. var AnimationRange = (function () {
  32760. function AnimationRange(name, from, to) {
  32761. this.name = name;
  32762. this.from = from;
  32763. this.to = to;
  32764. }
  32765. AnimationRange.prototype.clone = function () {
  32766. return new AnimationRange(this.name, this.from, this.to);
  32767. };
  32768. return AnimationRange;
  32769. }());
  32770. BABYLON.AnimationRange = AnimationRange;
  32771. /**
  32772. * Composed of a frame, and an action function
  32773. */
  32774. var AnimationEvent = (function () {
  32775. function AnimationEvent(frame, action, onlyOnce) {
  32776. this.frame = frame;
  32777. this.action = action;
  32778. this.onlyOnce = onlyOnce;
  32779. this.isDone = false;
  32780. }
  32781. return AnimationEvent;
  32782. }());
  32783. BABYLON.AnimationEvent = AnimationEvent;
  32784. var PathCursor = (function () {
  32785. function PathCursor(path) {
  32786. this.path = path;
  32787. this._onchange = new Array();
  32788. this.value = 0;
  32789. this.animations = new Array();
  32790. }
  32791. PathCursor.prototype.getPoint = function () {
  32792. var point = this.path.getPointAtLengthPosition(this.value);
  32793. return new BABYLON.Vector3(point.x, 0, point.y);
  32794. };
  32795. PathCursor.prototype.moveAhead = function (step) {
  32796. if (step === void 0) { step = 0.002; }
  32797. this.move(step);
  32798. return this;
  32799. };
  32800. PathCursor.prototype.moveBack = function (step) {
  32801. if (step === void 0) { step = 0.002; }
  32802. this.move(-step);
  32803. return this;
  32804. };
  32805. PathCursor.prototype.move = function (step) {
  32806. if (Math.abs(step) > 1) {
  32807. throw "step size should be less than 1.";
  32808. }
  32809. this.value += step;
  32810. this.ensureLimits();
  32811. this.raiseOnChange();
  32812. return this;
  32813. };
  32814. PathCursor.prototype.ensureLimits = function () {
  32815. while (this.value > 1) {
  32816. this.value -= 1;
  32817. }
  32818. while (this.value < 0) {
  32819. this.value += 1;
  32820. }
  32821. return this;
  32822. };
  32823. // used by animation engine
  32824. PathCursor.prototype.markAsDirty = function (propertyName) {
  32825. this.ensureLimits();
  32826. this.raiseOnChange();
  32827. return this;
  32828. };
  32829. PathCursor.prototype.raiseOnChange = function () {
  32830. var _this = this;
  32831. this._onchange.forEach(function (f) { return f(_this); });
  32832. return this;
  32833. };
  32834. PathCursor.prototype.onchange = function (f) {
  32835. this._onchange.push(f);
  32836. return this;
  32837. };
  32838. return PathCursor;
  32839. }());
  32840. BABYLON.PathCursor = PathCursor;
  32841. var Animation = (function () {
  32842. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32843. this.name = name;
  32844. this.targetProperty = targetProperty;
  32845. this.framePerSecond = framePerSecond;
  32846. this.dataType = dataType;
  32847. this.loopMode = loopMode;
  32848. this.enableBlending = enableBlending;
  32849. this._offsetsCache = {};
  32850. this._highLimitsCache = {};
  32851. this._stopped = false;
  32852. this._blendingFactor = 0;
  32853. // The set of event that will be linked to this animation
  32854. this._events = new Array();
  32855. this.allowMatricesInterpolation = false;
  32856. this.blendingSpeed = 0.01;
  32857. this._ranges = {};
  32858. this.targetPropertyPath = targetProperty.split(".");
  32859. this.dataType = dataType;
  32860. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32861. }
  32862. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32863. var dataType = undefined;
  32864. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32865. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32866. }
  32867. else if (from instanceof BABYLON.Quaternion) {
  32868. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32869. }
  32870. else if (from instanceof BABYLON.Vector3) {
  32871. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32872. }
  32873. else if (from instanceof BABYLON.Vector2) {
  32874. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32875. }
  32876. else if (from instanceof BABYLON.Color3) {
  32877. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32878. }
  32879. else if (from instanceof BABYLON.Size) {
  32880. dataType = Animation.ANIMATIONTYPE_SIZE;
  32881. }
  32882. if (dataType == undefined) {
  32883. return null;
  32884. }
  32885. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32886. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32887. animation.setKeys(keys);
  32888. if (easingFunction !== undefined) {
  32889. animation.setEasingFunction(easingFunction);
  32890. }
  32891. return animation;
  32892. };
  32893. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32894. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32895. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32896. };
  32897. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32898. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32899. node.animations.push(animation);
  32900. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32901. };
  32902. // Methods
  32903. /**
  32904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32905. */
  32906. Animation.prototype.toString = function (fullDetails) {
  32907. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32908. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32909. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32910. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32911. if (fullDetails) {
  32912. ret += ", Ranges: {";
  32913. var first = true;
  32914. for (var name in this._ranges) {
  32915. if (first) {
  32916. ret += ", ";
  32917. first = false;
  32918. }
  32919. ret += name;
  32920. }
  32921. ret += "}";
  32922. }
  32923. return ret;
  32924. };
  32925. /**
  32926. * Add an event to this animation.
  32927. */
  32928. Animation.prototype.addEvent = function (event) {
  32929. this._events.push(event);
  32930. };
  32931. /**
  32932. * Remove all events found at the given frame
  32933. * @param frame
  32934. */
  32935. Animation.prototype.removeEvents = function (frame) {
  32936. for (var index = 0; index < this._events.length; index++) {
  32937. if (this._events[index].frame === frame) {
  32938. this._events.splice(index, 1);
  32939. index--;
  32940. }
  32941. }
  32942. };
  32943. Animation.prototype.createRange = function (name, from, to) {
  32944. // check name not already in use; could happen for bones after serialized
  32945. if (!this._ranges[name]) {
  32946. this._ranges[name] = new AnimationRange(name, from, to);
  32947. }
  32948. };
  32949. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32950. if (deleteFrames === void 0) { deleteFrames = true; }
  32951. if (this._ranges[name]) {
  32952. if (deleteFrames) {
  32953. var from = this._ranges[name].from;
  32954. var to = this._ranges[name].to;
  32955. // this loop MUST go high to low for multiple splices to work
  32956. for (var key = this._keys.length - 1; key >= 0; key--) {
  32957. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32958. this._keys.splice(key, 1);
  32959. }
  32960. }
  32961. }
  32962. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32963. }
  32964. };
  32965. Animation.prototype.getRange = function (name) {
  32966. return this._ranges[name];
  32967. };
  32968. Animation.prototype.reset = function () {
  32969. this._offsetsCache = {};
  32970. this._highLimitsCache = {};
  32971. this.currentFrame = 0;
  32972. this._blendingFactor = 0;
  32973. this._originalBlendValue = null;
  32974. };
  32975. Animation.prototype.isStopped = function () {
  32976. return this._stopped;
  32977. };
  32978. Animation.prototype.getKeys = function () {
  32979. return this._keys;
  32980. };
  32981. Animation.prototype.getHighestFrame = function () {
  32982. var ret = 0;
  32983. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32984. if (ret < this._keys[key].frame) {
  32985. ret = this._keys[key].frame;
  32986. }
  32987. }
  32988. return ret;
  32989. };
  32990. Animation.prototype.getEasingFunction = function () {
  32991. return this._easingFunction;
  32992. };
  32993. Animation.prototype.setEasingFunction = function (easingFunction) {
  32994. this._easingFunction = easingFunction;
  32995. };
  32996. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32997. return startValue + (endValue - startValue) * gradient;
  32998. };
  32999. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  33000. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  33001. };
  33002. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  33003. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  33004. };
  33005. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  33006. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  33007. };
  33008. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  33009. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  33010. };
  33011. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  33012. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  33013. };
  33014. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  33015. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  33016. };
  33017. Animation.prototype.clone = function () {
  33018. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  33019. clone.enableBlending = this.enableBlending;
  33020. clone.blendingSpeed = this.blendingSpeed;
  33021. if (this._keys) {
  33022. clone.setKeys(this._keys);
  33023. }
  33024. if (this._ranges) {
  33025. clone._ranges = {};
  33026. for (var name in this._ranges) {
  33027. clone._ranges[name] = this._ranges[name].clone();
  33028. }
  33029. }
  33030. return clone;
  33031. };
  33032. Animation.prototype.setKeys = function (values) {
  33033. this._keys = values.slice(0);
  33034. this._offsetsCache = {};
  33035. this._highLimitsCache = {};
  33036. };
  33037. Animation.prototype._getKeyValue = function (value) {
  33038. if (typeof value === "function") {
  33039. return value();
  33040. }
  33041. return value;
  33042. };
  33043. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  33044. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  33045. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  33046. }
  33047. this.currentFrame = currentFrame;
  33048. // Try to get a hash to find the right key
  33049. 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));
  33050. if (this._keys[startKey].frame >= currentFrame) {
  33051. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  33052. startKey--;
  33053. }
  33054. }
  33055. for (var key = startKey; key < this._keys.length; key++) {
  33056. if (this._keys[key + 1].frame >= currentFrame) {
  33057. var startValue = this._getKeyValue(this._keys[key].value);
  33058. var endValue = this._getKeyValue(this._keys[key + 1].value);
  33059. // gradient : percent of currentFrame between the frame inf and the frame sup
  33060. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  33061. // check for easingFunction and correction of gradient
  33062. if (this._easingFunction != null) {
  33063. gradient = this._easingFunction.ease(gradient);
  33064. }
  33065. switch (this.dataType) {
  33066. // Float
  33067. case Animation.ANIMATIONTYPE_FLOAT:
  33068. switch (loopMode) {
  33069. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33070. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33071. return this.floatInterpolateFunction(startValue, endValue, gradient);
  33072. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33073. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  33074. }
  33075. break;
  33076. // Quaternion
  33077. case Animation.ANIMATIONTYPE_QUATERNION:
  33078. var quaternion = null;
  33079. switch (loopMode) {
  33080. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33081. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33082. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  33083. break;
  33084. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33085. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33086. break;
  33087. }
  33088. return quaternion;
  33089. // Vector3
  33090. case Animation.ANIMATIONTYPE_VECTOR3:
  33091. switch (loopMode) {
  33092. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33093. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33094. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  33095. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33096. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33097. }
  33098. // Vector2
  33099. case Animation.ANIMATIONTYPE_VECTOR2:
  33100. switch (loopMode) {
  33101. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33102. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33103. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  33104. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33105. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33106. }
  33107. // Size
  33108. case Animation.ANIMATIONTYPE_SIZE:
  33109. switch (loopMode) {
  33110. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33111. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33112. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  33113. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33114. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33115. }
  33116. // Color3
  33117. case Animation.ANIMATIONTYPE_COLOR3:
  33118. switch (loopMode) {
  33119. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33120. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33121. return this.color3InterpolateFunction(startValue, endValue, gradient);
  33122. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33123. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33124. }
  33125. // Matrix
  33126. case Animation.ANIMATIONTYPE_MATRIX:
  33127. switch (loopMode) {
  33128. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33129. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33130. if (this.allowMatricesInterpolation) {
  33131. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  33132. }
  33133. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33134. return startValue;
  33135. }
  33136. default:
  33137. break;
  33138. }
  33139. break;
  33140. }
  33141. }
  33142. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  33143. };
  33144. Animation.prototype.setValue = function (currentValue, blend) {
  33145. if (blend === void 0) { blend = false; }
  33146. // Set value
  33147. var path;
  33148. var destination;
  33149. if (this.targetPropertyPath.length > 1) {
  33150. var property = this._target[this.targetPropertyPath[0]];
  33151. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  33152. property = property[this.targetPropertyPath[index]];
  33153. }
  33154. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  33155. destination = property;
  33156. }
  33157. else {
  33158. path = this.targetPropertyPath[0];
  33159. destination = this._target;
  33160. }
  33161. // Blending
  33162. if (this.enableBlending && this._blendingFactor <= 1.0) {
  33163. if (!this._originalBlendValue) {
  33164. if (destination[path].clone) {
  33165. this._originalBlendValue = destination[path].clone();
  33166. }
  33167. else {
  33168. this._originalBlendValue = destination[path];
  33169. }
  33170. }
  33171. if (this._originalBlendValue.prototype) {
  33172. if (this._originalBlendValue.prototype.Lerp) {
  33173. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  33174. }
  33175. else {
  33176. destination[path] = currentValue;
  33177. }
  33178. }
  33179. else if (this._originalBlendValue.m) {
  33180. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  33181. }
  33182. else {
  33183. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  33184. }
  33185. this._blendingFactor += this.blendingSpeed;
  33186. }
  33187. else {
  33188. destination[path] = currentValue;
  33189. }
  33190. if (this._target.markAsDirty) {
  33191. this._target.markAsDirty(this.targetProperty);
  33192. }
  33193. };
  33194. Animation.prototype.goToFrame = function (frame) {
  33195. if (frame < this._keys[0].frame) {
  33196. frame = this._keys[0].frame;
  33197. }
  33198. else if (frame > this._keys[this._keys.length - 1].frame) {
  33199. frame = this._keys[this._keys.length - 1].frame;
  33200. }
  33201. var currentValue = this._interpolate(frame, 0, this.loopMode);
  33202. this.setValue(currentValue);
  33203. };
  33204. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  33205. if (blend === void 0) { blend = false; }
  33206. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  33207. this._stopped = true;
  33208. return false;
  33209. }
  33210. var returnValue = true;
  33211. // Adding a start key at frame 0 if missing
  33212. if (this._keys[0].frame !== 0) {
  33213. var newKey = { frame: 0, value: this._keys[0].value };
  33214. this._keys.splice(0, 0, newKey);
  33215. }
  33216. // Check limits
  33217. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  33218. from = this._keys[0].frame;
  33219. }
  33220. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  33221. to = this._keys[this._keys.length - 1].frame;
  33222. }
  33223. //to and from cannot be the same key
  33224. if (from === to) {
  33225. from++;
  33226. }
  33227. // Compute ratio
  33228. var range = to - from;
  33229. var offsetValue;
  33230. // ratio represents the frame delta between from and to
  33231. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  33232. var highLimitValue = 0;
  33233. if (ratio > range && !loop) {
  33234. returnValue = false;
  33235. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  33236. }
  33237. else {
  33238. // Get max value if required
  33239. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  33240. var keyOffset = to.toString() + from.toString();
  33241. if (!this._offsetsCache[keyOffset]) {
  33242. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33243. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33244. switch (this.dataType) {
  33245. // Float
  33246. case Animation.ANIMATIONTYPE_FLOAT:
  33247. this._offsetsCache[keyOffset] = toValue - fromValue;
  33248. break;
  33249. // Quaternion
  33250. case Animation.ANIMATIONTYPE_QUATERNION:
  33251. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33252. break;
  33253. // Vector3
  33254. case Animation.ANIMATIONTYPE_VECTOR3:
  33255. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33256. // Vector2
  33257. case Animation.ANIMATIONTYPE_VECTOR2:
  33258. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33259. // Size
  33260. case Animation.ANIMATIONTYPE_SIZE:
  33261. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33262. // Color3
  33263. case Animation.ANIMATIONTYPE_COLOR3:
  33264. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33265. default:
  33266. break;
  33267. }
  33268. this._highLimitsCache[keyOffset] = toValue;
  33269. }
  33270. highLimitValue = this._highLimitsCache[keyOffset];
  33271. offsetValue = this._offsetsCache[keyOffset];
  33272. }
  33273. }
  33274. if (offsetValue === undefined) {
  33275. switch (this.dataType) {
  33276. // Float
  33277. case Animation.ANIMATIONTYPE_FLOAT:
  33278. offsetValue = 0;
  33279. break;
  33280. // Quaternion
  33281. case Animation.ANIMATIONTYPE_QUATERNION:
  33282. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  33283. break;
  33284. // Vector3
  33285. case Animation.ANIMATIONTYPE_VECTOR3:
  33286. offsetValue = BABYLON.Vector3.Zero();
  33287. break;
  33288. // Vector2
  33289. case Animation.ANIMATIONTYPE_VECTOR2:
  33290. offsetValue = BABYLON.Vector2.Zero();
  33291. break;
  33292. // Size
  33293. case Animation.ANIMATIONTYPE_SIZE:
  33294. offsetValue = BABYLON.Size.Zero();
  33295. break;
  33296. // Color3
  33297. case Animation.ANIMATIONTYPE_COLOR3:
  33298. offsetValue = BABYLON.Color3.Black();
  33299. }
  33300. }
  33301. // Compute value
  33302. var repeatCount = (ratio / range) >> 0;
  33303. var currentFrame = returnValue ? from + ratio % range : to;
  33304. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  33305. // Set value
  33306. this.setValue(currentValue);
  33307. // Check events
  33308. for (var index = 0; index < this._events.length; index++) {
  33309. if (currentFrame >= this._events[index].frame) {
  33310. var event = this._events[index];
  33311. if (!event.isDone) {
  33312. // If event should be done only once, remove it.
  33313. if (event.onlyOnce) {
  33314. this._events.splice(index, 1);
  33315. index--;
  33316. }
  33317. event.isDone = true;
  33318. event.action();
  33319. } // Don't do anything if the event has already be done.
  33320. }
  33321. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  33322. // reset event, the animation is looping
  33323. this._events[index].isDone = false;
  33324. }
  33325. }
  33326. if (!returnValue) {
  33327. this._stopped = true;
  33328. }
  33329. return returnValue;
  33330. };
  33331. Animation.prototype.serialize = function () {
  33332. var serializationObject = {};
  33333. serializationObject.name = this.name;
  33334. serializationObject.property = this.targetProperty;
  33335. serializationObject.framePerSecond = this.framePerSecond;
  33336. serializationObject.dataType = this.dataType;
  33337. serializationObject.loopBehavior = this.loopMode;
  33338. serializationObject.enableBlending = this.enableBlending;
  33339. serializationObject.blendingSpeed = this.blendingSpeed;
  33340. var dataType = this.dataType;
  33341. serializationObject.keys = [];
  33342. var keys = this.getKeys();
  33343. for (var index = 0; index < keys.length; index++) {
  33344. var animationKey = keys[index];
  33345. var key = {};
  33346. key.frame = animationKey.frame;
  33347. switch (dataType) {
  33348. case Animation.ANIMATIONTYPE_FLOAT:
  33349. key.values = [animationKey.value];
  33350. break;
  33351. case Animation.ANIMATIONTYPE_QUATERNION:
  33352. case Animation.ANIMATIONTYPE_MATRIX:
  33353. case Animation.ANIMATIONTYPE_VECTOR3:
  33354. case Animation.ANIMATIONTYPE_COLOR3:
  33355. key.values = animationKey.value.asArray();
  33356. break;
  33357. }
  33358. serializationObject.keys.push(key);
  33359. }
  33360. serializationObject.ranges = [];
  33361. for (var name in this._ranges) {
  33362. var range = {};
  33363. range.name = name;
  33364. range.from = this._ranges[name].from;
  33365. range.to = this._ranges[name].to;
  33366. serializationObject.ranges.push(range);
  33367. }
  33368. return serializationObject;
  33369. };
  33370. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  33371. get: function () {
  33372. return Animation._ANIMATIONTYPE_FLOAT;
  33373. },
  33374. enumerable: true,
  33375. configurable: true
  33376. });
  33377. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33378. get: function () {
  33379. return Animation._ANIMATIONTYPE_VECTOR3;
  33380. },
  33381. enumerable: true,
  33382. configurable: true
  33383. });
  33384. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33385. get: function () {
  33386. return Animation._ANIMATIONTYPE_VECTOR2;
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33392. get: function () {
  33393. return Animation._ANIMATIONTYPE_SIZE;
  33394. },
  33395. enumerable: true,
  33396. configurable: true
  33397. });
  33398. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33399. get: function () {
  33400. return Animation._ANIMATIONTYPE_QUATERNION;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33406. get: function () {
  33407. return Animation._ANIMATIONTYPE_MATRIX;
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33413. get: function () {
  33414. return Animation._ANIMATIONTYPE_COLOR3;
  33415. },
  33416. enumerable: true,
  33417. configurable: true
  33418. });
  33419. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33420. get: function () {
  33421. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33422. },
  33423. enumerable: true,
  33424. configurable: true
  33425. });
  33426. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33427. get: function () {
  33428. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33429. },
  33430. enumerable: true,
  33431. configurable: true
  33432. });
  33433. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33434. get: function () {
  33435. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33436. },
  33437. enumerable: true,
  33438. configurable: true
  33439. });
  33440. Animation.Parse = function (parsedAnimation) {
  33441. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33442. var dataType = parsedAnimation.dataType;
  33443. var keys = [];
  33444. var data;
  33445. var index;
  33446. if (parsedAnimation.enableBlending) {
  33447. animation.enableBlending = parsedAnimation.enableBlending;
  33448. }
  33449. if (parsedAnimation.blendingSpeed) {
  33450. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33451. }
  33452. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33453. var key = parsedAnimation.keys[index];
  33454. switch (dataType) {
  33455. case Animation.ANIMATIONTYPE_FLOAT:
  33456. data = key.values[0];
  33457. break;
  33458. case Animation.ANIMATIONTYPE_QUATERNION:
  33459. data = BABYLON.Quaternion.FromArray(key.values);
  33460. break;
  33461. case Animation.ANIMATIONTYPE_MATRIX:
  33462. data = BABYLON.Matrix.FromArray(key.values);
  33463. break;
  33464. case Animation.ANIMATIONTYPE_COLOR3:
  33465. data = BABYLON.Color3.FromArray(key.values);
  33466. break;
  33467. case Animation.ANIMATIONTYPE_VECTOR3:
  33468. default:
  33469. data = BABYLON.Vector3.FromArray(key.values);
  33470. break;
  33471. }
  33472. keys.push({
  33473. frame: key.frame,
  33474. value: data
  33475. });
  33476. }
  33477. animation.setKeys(keys);
  33478. if (parsedAnimation.ranges) {
  33479. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33480. data = parsedAnimation.ranges[index];
  33481. animation.createRange(data.name, data.from, data.to);
  33482. }
  33483. }
  33484. return animation;
  33485. };
  33486. Animation.AppendSerializedAnimations = function (source, destination) {
  33487. if (source.animations) {
  33488. destination.animations = [];
  33489. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33490. var animation = source.animations[animationIndex];
  33491. destination.animations.push(animation.serialize());
  33492. }
  33493. }
  33494. };
  33495. return Animation;
  33496. }());
  33497. // Statics
  33498. Animation._ANIMATIONTYPE_FLOAT = 0;
  33499. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33500. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33501. Animation._ANIMATIONTYPE_MATRIX = 3;
  33502. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33503. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33504. Animation._ANIMATIONTYPE_SIZE = 6;
  33505. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33506. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33507. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33508. BABYLON.Animation = Animation;
  33509. })(BABYLON || (BABYLON = {}));
  33510. //# sourceMappingURL=babylon.animation.js.map
  33511. var BABYLON;
  33512. (function (BABYLON) {
  33513. var Animatable = (function () {
  33514. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33515. if (fromFrame === void 0) { fromFrame = 0; }
  33516. if (toFrame === void 0) { toFrame = 100; }
  33517. if (loopAnimation === void 0) { loopAnimation = false; }
  33518. if (speedRatio === void 0) { speedRatio = 1.0; }
  33519. this.target = target;
  33520. this.fromFrame = fromFrame;
  33521. this.toFrame = toFrame;
  33522. this.loopAnimation = loopAnimation;
  33523. this.speedRatio = speedRatio;
  33524. this.onAnimationEnd = onAnimationEnd;
  33525. this._animations = new Array();
  33526. this._paused = false;
  33527. this.animationStarted = false;
  33528. if (animations) {
  33529. this.appendAnimations(target, animations);
  33530. }
  33531. this._scene = scene;
  33532. scene._activeAnimatables.push(this);
  33533. }
  33534. // Methods
  33535. Animatable.prototype.getAnimations = function () {
  33536. return this._animations;
  33537. };
  33538. Animatable.prototype.appendAnimations = function (target, animations) {
  33539. for (var index = 0; index < animations.length; index++) {
  33540. var animation = animations[index];
  33541. animation._target = target;
  33542. this._animations.push(animation);
  33543. }
  33544. };
  33545. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33546. var animations = this._animations;
  33547. for (var index = 0; index < animations.length; index++) {
  33548. if (animations[index].targetProperty === property) {
  33549. return animations[index];
  33550. }
  33551. }
  33552. return null;
  33553. };
  33554. Animatable.prototype.reset = function () {
  33555. var animations = this._animations;
  33556. for (var index = 0; index < animations.length; index++) {
  33557. animations[index].reset();
  33558. }
  33559. this._localDelayOffset = null;
  33560. this._pausedDelay = null;
  33561. };
  33562. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33563. var animations = this._animations;
  33564. for (var index = 0; index < animations.length; index++) {
  33565. animations[index].enableBlending = true;
  33566. animations[index].blendingSpeed = blendingSpeed;
  33567. }
  33568. };
  33569. Animatable.prototype.disableBlending = function () {
  33570. var animations = this._animations;
  33571. for (var index = 0; index < animations.length; index++) {
  33572. animations[index].enableBlending = false;
  33573. }
  33574. };
  33575. Animatable.prototype.goToFrame = function (frame) {
  33576. var animations = this._animations;
  33577. if (animations[0]) {
  33578. var fps = animations[0].framePerSecond;
  33579. var currentFrame = animations[0].currentFrame;
  33580. var adjustTime = frame - currentFrame;
  33581. var delay = adjustTime * 1000 / fps;
  33582. this._localDelayOffset -= delay;
  33583. }
  33584. for (var index = 0; index < animations.length; index++) {
  33585. animations[index].goToFrame(frame);
  33586. }
  33587. };
  33588. Animatable.prototype.pause = function () {
  33589. if (this._paused) {
  33590. return;
  33591. }
  33592. this._paused = true;
  33593. };
  33594. Animatable.prototype.restart = function () {
  33595. this._paused = false;
  33596. };
  33597. Animatable.prototype.stop = function (animationName) {
  33598. if (animationName) {
  33599. var idx = this._scene._activeAnimatables.indexOf(this);
  33600. if (idx > -1) {
  33601. var animations = this._animations;
  33602. for (var index = animations.length - 1; index >= 0; index--) {
  33603. if (typeof animationName === "string" && animations[index].name != animationName) {
  33604. continue;
  33605. }
  33606. animations[index].reset();
  33607. animations.splice(index, 1);
  33608. }
  33609. if (animations.length == 0) {
  33610. this._scene._activeAnimatables.splice(idx, 1);
  33611. if (this.onAnimationEnd) {
  33612. this.onAnimationEnd();
  33613. }
  33614. }
  33615. }
  33616. }
  33617. else {
  33618. var index = this._scene._activeAnimatables.indexOf(this);
  33619. if (index > -1) {
  33620. this._scene._activeAnimatables.splice(index, 1);
  33621. var animations = this._animations;
  33622. for (var index = 0; index < animations.length; index++) {
  33623. animations[index].reset();
  33624. }
  33625. if (this.onAnimationEnd) {
  33626. this.onAnimationEnd();
  33627. }
  33628. }
  33629. }
  33630. };
  33631. Animatable.prototype._animate = function (delay) {
  33632. if (this._paused) {
  33633. this.animationStarted = false;
  33634. if (!this._pausedDelay) {
  33635. this._pausedDelay = delay;
  33636. }
  33637. return true;
  33638. }
  33639. if (!this._localDelayOffset) {
  33640. this._localDelayOffset = delay;
  33641. }
  33642. else if (this._pausedDelay) {
  33643. this._localDelayOffset += delay - this._pausedDelay;
  33644. this._pausedDelay = null;
  33645. }
  33646. // Animating
  33647. var running = false;
  33648. var animations = this._animations;
  33649. var index;
  33650. for (index = 0; index < animations.length; index++) {
  33651. var animation = animations[index];
  33652. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33653. running = running || isRunning;
  33654. }
  33655. this.animationStarted = running;
  33656. if (!running) {
  33657. // Remove from active animatables
  33658. index = this._scene._activeAnimatables.indexOf(this);
  33659. this._scene._activeAnimatables.splice(index, 1);
  33660. }
  33661. if (!running && this.onAnimationEnd) {
  33662. this.onAnimationEnd();
  33663. this.onAnimationEnd = null;
  33664. }
  33665. return running;
  33666. };
  33667. return Animatable;
  33668. }());
  33669. BABYLON.Animatable = Animatable;
  33670. })(BABYLON || (BABYLON = {}));
  33671. //# sourceMappingURL=babylon.animatable.js.map
  33672. var BABYLON;
  33673. (function (BABYLON) {
  33674. var EasingFunction = (function () {
  33675. function EasingFunction() {
  33676. // Properties
  33677. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33678. }
  33679. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33680. get: function () {
  33681. return EasingFunction._EASINGMODE_EASEIN;
  33682. },
  33683. enumerable: true,
  33684. configurable: true
  33685. });
  33686. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33687. get: function () {
  33688. return EasingFunction._EASINGMODE_EASEOUT;
  33689. },
  33690. enumerable: true,
  33691. configurable: true
  33692. });
  33693. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33694. get: function () {
  33695. return EasingFunction._EASINGMODE_EASEINOUT;
  33696. },
  33697. enumerable: true,
  33698. configurable: true
  33699. });
  33700. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33701. var n = Math.min(Math.max(easingMode, 0), 2);
  33702. this._easingMode = n;
  33703. };
  33704. EasingFunction.prototype.getEasingMode = function () {
  33705. return this._easingMode;
  33706. };
  33707. EasingFunction.prototype.easeInCore = function (gradient) {
  33708. throw new Error('You must implement this method');
  33709. };
  33710. EasingFunction.prototype.ease = function (gradient) {
  33711. switch (this._easingMode) {
  33712. case EasingFunction.EASINGMODE_EASEIN:
  33713. return this.easeInCore(gradient);
  33714. case EasingFunction.EASINGMODE_EASEOUT:
  33715. return (1 - this.easeInCore(1 - gradient));
  33716. }
  33717. if (gradient >= 0.5) {
  33718. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33719. }
  33720. return (this.easeInCore(gradient * 2) * 0.5);
  33721. };
  33722. return EasingFunction;
  33723. }());
  33724. //Statics
  33725. EasingFunction._EASINGMODE_EASEIN = 0;
  33726. EasingFunction._EASINGMODE_EASEOUT = 1;
  33727. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33728. BABYLON.EasingFunction = EasingFunction;
  33729. var CircleEase = (function (_super) {
  33730. __extends(CircleEase, _super);
  33731. function CircleEase() {
  33732. return _super !== null && _super.apply(this, arguments) || this;
  33733. }
  33734. CircleEase.prototype.easeInCore = function (gradient) {
  33735. gradient = Math.max(0, Math.min(1, gradient));
  33736. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33737. };
  33738. return CircleEase;
  33739. }(EasingFunction));
  33740. BABYLON.CircleEase = CircleEase;
  33741. var BackEase = (function (_super) {
  33742. __extends(BackEase, _super);
  33743. function BackEase(amplitude) {
  33744. if (amplitude === void 0) { amplitude = 1; }
  33745. var _this = _super.call(this) || this;
  33746. _this.amplitude = amplitude;
  33747. return _this;
  33748. }
  33749. BackEase.prototype.easeInCore = function (gradient) {
  33750. var num = Math.max(0, this.amplitude);
  33751. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33752. };
  33753. return BackEase;
  33754. }(EasingFunction));
  33755. BABYLON.BackEase = BackEase;
  33756. var BounceEase = (function (_super) {
  33757. __extends(BounceEase, _super);
  33758. function BounceEase(bounces, bounciness) {
  33759. if (bounces === void 0) { bounces = 3; }
  33760. if (bounciness === void 0) { bounciness = 2; }
  33761. var _this = _super.call(this) || this;
  33762. _this.bounces = bounces;
  33763. _this.bounciness = bounciness;
  33764. return _this;
  33765. }
  33766. BounceEase.prototype.easeInCore = function (gradient) {
  33767. var y = Math.max(0.0, this.bounces);
  33768. var bounciness = this.bounciness;
  33769. if (bounciness <= 1.0) {
  33770. bounciness = 1.001;
  33771. }
  33772. var num9 = Math.pow(bounciness, y);
  33773. var num5 = 1.0 - bounciness;
  33774. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33775. var num15 = gradient * num4;
  33776. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33777. var num3 = Math.floor(num65);
  33778. var num13 = num3 + 1.0;
  33779. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33780. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33781. var num7 = (num8 + num12) * 0.5;
  33782. var num6 = gradient - num7;
  33783. var num2 = num7 - num8;
  33784. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33785. };
  33786. return BounceEase;
  33787. }(EasingFunction));
  33788. BABYLON.BounceEase = BounceEase;
  33789. var CubicEase = (function (_super) {
  33790. __extends(CubicEase, _super);
  33791. function CubicEase() {
  33792. return _super !== null && _super.apply(this, arguments) || this;
  33793. }
  33794. CubicEase.prototype.easeInCore = function (gradient) {
  33795. return (gradient * gradient * gradient);
  33796. };
  33797. return CubicEase;
  33798. }(EasingFunction));
  33799. BABYLON.CubicEase = CubicEase;
  33800. var ElasticEase = (function (_super) {
  33801. __extends(ElasticEase, _super);
  33802. function ElasticEase(oscillations, springiness) {
  33803. if (oscillations === void 0) { oscillations = 3; }
  33804. if (springiness === void 0) { springiness = 3; }
  33805. var _this = _super.call(this) || this;
  33806. _this.oscillations = oscillations;
  33807. _this.springiness = springiness;
  33808. return _this;
  33809. }
  33810. ElasticEase.prototype.easeInCore = function (gradient) {
  33811. var num2;
  33812. var num3 = Math.max(0.0, this.oscillations);
  33813. var num = Math.max(0.0, this.springiness);
  33814. if (num == 0) {
  33815. num2 = gradient;
  33816. }
  33817. else {
  33818. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33819. }
  33820. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33821. };
  33822. return ElasticEase;
  33823. }(EasingFunction));
  33824. BABYLON.ElasticEase = ElasticEase;
  33825. var ExponentialEase = (function (_super) {
  33826. __extends(ExponentialEase, _super);
  33827. function ExponentialEase(exponent) {
  33828. if (exponent === void 0) { exponent = 2; }
  33829. var _this = _super.call(this) || this;
  33830. _this.exponent = exponent;
  33831. return _this;
  33832. }
  33833. ExponentialEase.prototype.easeInCore = function (gradient) {
  33834. if (this.exponent <= 0) {
  33835. return gradient;
  33836. }
  33837. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33838. };
  33839. return ExponentialEase;
  33840. }(EasingFunction));
  33841. BABYLON.ExponentialEase = ExponentialEase;
  33842. var PowerEase = (function (_super) {
  33843. __extends(PowerEase, _super);
  33844. function PowerEase(power) {
  33845. if (power === void 0) { power = 2; }
  33846. var _this = _super.call(this) || this;
  33847. _this.power = power;
  33848. return _this;
  33849. }
  33850. PowerEase.prototype.easeInCore = function (gradient) {
  33851. var y = Math.max(0.0, this.power);
  33852. return Math.pow(gradient, y);
  33853. };
  33854. return PowerEase;
  33855. }(EasingFunction));
  33856. BABYLON.PowerEase = PowerEase;
  33857. var QuadraticEase = (function (_super) {
  33858. __extends(QuadraticEase, _super);
  33859. function QuadraticEase() {
  33860. return _super !== null && _super.apply(this, arguments) || this;
  33861. }
  33862. QuadraticEase.prototype.easeInCore = function (gradient) {
  33863. return (gradient * gradient);
  33864. };
  33865. return QuadraticEase;
  33866. }(EasingFunction));
  33867. BABYLON.QuadraticEase = QuadraticEase;
  33868. var QuarticEase = (function (_super) {
  33869. __extends(QuarticEase, _super);
  33870. function QuarticEase() {
  33871. return _super !== null && _super.apply(this, arguments) || this;
  33872. }
  33873. QuarticEase.prototype.easeInCore = function (gradient) {
  33874. return (gradient * gradient * gradient * gradient);
  33875. };
  33876. return QuarticEase;
  33877. }(EasingFunction));
  33878. BABYLON.QuarticEase = QuarticEase;
  33879. var QuinticEase = (function (_super) {
  33880. __extends(QuinticEase, _super);
  33881. function QuinticEase() {
  33882. return _super !== null && _super.apply(this, arguments) || this;
  33883. }
  33884. QuinticEase.prototype.easeInCore = function (gradient) {
  33885. return (gradient * gradient * gradient * gradient * gradient);
  33886. };
  33887. return QuinticEase;
  33888. }(EasingFunction));
  33889. BABYLON.QuinticEase = QuinticEase;
  33890. var SineEase = (function (_super) {
  33891. __extends(SineEase, _super);
  33892. function SineEase() {
  33893. return _super !== null && _super.apply(this, arguments) || this;
  33894. }
  33895. SineEase.prototype.easeInCore = function (gradient) {
  33896. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33897. };
  33898. return SineEase;
  33899. }(EasingFunction));
  33900. BABYLON.SineEase = SineEase;
  33901. var BezierCurveEase = (function (_super) {
  33902. __extends(BezierCurveEase, _super);
  33903. function BezierCurveEase(x1, y1, x2, y2) {
  33904. if (x1 === void 0) { x1 = 0; }
  33905. if (y1 === void 0) { y1 = 0; }
  33906. if (x2 === void 0) { x2 = 1; }
  33907. if (y2 === void 0) { y2 = 1; }
  33908. var _this = _super.call(this) || this;
  33909. _this.x1 = x1;
  33910. _this.y1 = y1;
  33911. _this.x2 = x2;
  33912. _this.y2 = y2;
  33913. return _this;
  33914. }
  33915. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33916. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33917. };
  33918. return BezierCurveEase;
  33919. }(EasingFunction));
  33920. BABYLON.BezierCurveEase = BezierCurveEase;
  33921. })(BABYLON || (BABYLON = {}));
  33922. //# sourceMappingURL=babylon.easing.js.map
  33923. /// <reference path="..\babylon.node.ts" />
  33924. var BABYLON;
  33925. (function (BABYLON) {
  33926. var Bone = (function (_super) {
  33927. __extends(Bone, _super);
  33928. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33929. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33930. _this.name = name;
  33931. _this.children = new Array();
  33932. _this.animations = new Array();
  33933. _this._worldTransform = new BABYLON.Matrix();
  33934. _this._absoluteTransform = new BABYLON.Matrix();
  33935. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33936. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33937. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33938. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33939. _this._scalingDeterminant = 1;
  33940. _this._skeleton = skeleton;
  33941. _this._localMatrix = matrix;
  33942. _this._baseMatrix = matrix.clone();
  33943. _this._restPose = restPose ? restPose : matrix.clone();
  33944. skeleton.bones.push(_this);
  33945. if (parentBone) {
  33946. _this._parent = parentBone;
  33947. parentBone.children.push(_this);
  33948. }
  33949. else {
  33950. _this._parent = null;
  33951. }
  33952. _this._updateDifferenceMatrix();
  33953. if (_this.getAbsoluteTransform().determinant() < 0) {
  33954. _this._scalingDeterminant *= -1;
  33955. }
  33956. return _this;
  33957. }
  33958. Object.defineProperty(Bone.prototype, "_matrix", {
  33959. get: function () {
  33960. return this._localMatrix;
  33961. },
  33962. set: function (val) {
  33963. if (this._localMatrix) {
  33964. this._localMatrix.copyFrom(val);
  33965. }
  33966. else {
  33967. this._localMatrix = val;
  33968. }
  33969. },
  33970. enumerable: true,
  33971. configurable: true
  33972. });
  33973. // Members
  33974. Bone.prototype.getParent = function () {
  33975. return this._parent;
  33976. };
  33977. Bone.prototype.getLocalMatrix = function () {
  33978. return this._localMatrix;
  33979. };
  33980. Bone.prototype.getBaseMatrix = function () {
  33981. return this._baseMatrix;
  33982. };
  33983. Bone.prototype.getRestPose = function () {
  33984. return this._restPose;
  33985. };
  33986. Bone.prototype.returnToRest = function () {
  33987. this.updateMatrix(this._restPose.clone());
  33988. };
  33989. Bone.prototype.getWorldMatrix = function () {
  33990. return this._worldTransform;
  33991. };
  33992. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33993. return this._invertedAbsoluteTransform;
  33994. };
  33995. Bone.prototype.getAbsoluteTransform = function () {
  33996. return this._absoluteTransform;
  33997. };
  33998. // Methods
  33999. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  34000. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  34001. this._baseMatrix = matrix.clone();
  34002. this._localMatrix = matrix.clone();
  34003. this._skeleton._markAsDirty();
  34004. if (updateDifferenceMatrix) {
  34005. this._updateDifferenceMatrix();
  34006. }
  34007. };
  34008. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  34009. if (!rootMatrix) {
  34010. rootMatrix = this._baseMatrix;
  34011. }
  34012. if (this._parent) {
  34013. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34014. }
  34015. else {
  34016. this._absoluteTransform.copyFrom(rootMatrix);
  34017. }
  34018. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  34019. for (var index = 0; index < this.children.length; index++) {
  34020. this.children[index]._updateDifferenceMatrix();
  34021. }
  34022. };
  34023. Bone.prototype.markAsDirty = function () {
  34024. this._currentRenderId++;
  34025. this._skeleton._markAsDirty();
  34026. };
  34027. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  34028. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  34029. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  34030. // all animation may be coming from a library skeleton, so may need to create animation
  34031. if (this.animations.length === 0) {
  34032. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  34033. this.animations[0].setKeys([]);
  34034. }
  34035. // get animation info / verify there is such a range from the source bone
  34036. var sourceRange = source.animations[0].getRange(rangeName);
  34037. if (!sourceRange) {
  34038. return false;
  34039. }
  34040. var from = sourceRange.from;
  34041. var to = sourceRange.to;
  34042. var sourceKeys = source.animations[0].getKeys();
  34043. // rescaling prep
  34044. var sourceBoneLength = source.length;
  34045. var sourceParent = source.getParent();
  34046. var parent = this.getParent();
  34047. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  34048. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  34049. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  34050. var destKeys = this.animations[0].getKeys();
  34051. // loop vars declaration
  34052. var orig;
  34053. var origTranslation;
  34054. var mat;
  34055. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  34056. orig = sourceKeys[key];
  34057. if (orig.frame >= from && orig.frame <= to) {
  34058. if (rescaleAsRequired) {
  34059. mat = orig.value.clone();
  34060. // scale based on parent ratio, when bone has parent
  34061. if (parentScalingReqd) {
  34062. origTranslation = mat.getTranslation();
  34063. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  34064. // scale based on skeleton dimension ratio when root bone, and value is passed
  34065. }
  34066. else if (dimensionsScalingReqd) {
  34067. origTranslation = mat.getTranslation();
  34068. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  34069. // use original when root bone, and no data for skelDimensionsRatio
  34070. }
  34071. else {
  34072. mat = orig.value;
  34073. }
  34074. }
  34075. else {
  34076. mat = orig.value;
  34077. }
  34078. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  34079. }
  34080. }
  34081. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  34082. return true;
  34083. };
  34084. /**
  34085. * Translate the bone in local or world space.
  34086. * @param vec The amount to translate the bone.
  34087. * @param space The space that the translation is in.
  34088. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34089. */
  34090. Bone.prototype.translate = function (vec, space, mesh) {
  34091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34092. var lm = this.getLocalMatrix();
  34093. if (space == BABYLON.Space.LOCAL) {
  34094. lm.m[12] += vec.x;
  34095. lm.m[13] += vec.y;
  34096. lm.m[14] += vec.z;
  34097. }
  34098. else {
  34099. var wm;
  34100. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34101. if (mesh) {
  34102. wm = mesh.getWorldMatrix();
  34103. }
  34104. this._skeleton.computeAbsoluteTransforms();
  34105. var tmat = BABYLON.Tmp.Matrix[0];
  34106. var tvec = BABYLON.Tmp.Vector3[0];
  34107. if (mesh) {
  34108. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34109. tmat.multiplyToRef(wm, tmat);
  34110. }
  34111. else {
  34112. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34113. }
  34114. tmat.m[12] = 0;
  34115. tmat.m[13] = 0;
  34116. tmat.m[14] = 0;
  34117. tmat.invert();
  34118. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  34119. lm.m[12] += tvec.x;
  34120. lm.m[13] += tvec.y;
  34121. lm.m[14] += tvec.z;
  34122. }
  34123. this.markAsDirty();
  34124. };
  34125. /**
  34126. * Set the postion of the bone in local or world space.
  34127. * @param position The position to set the bone.
  34128. * @param space The space that the position is in.
  34129. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34130. */
  34131. Bone.prototype.setPosition = function (position, space, mesh) {
  34132. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34133. var lm = this.getLocalMatrix();
  34134. if (space == BABYLON.Space.LOCAL) {
  34135. lm.m[12] = position.x;
  34136. lm.m[13] = position.y;
  34137. lm.m[14] = position.z;
  34138. }
  34139. else {
  34140. var wm;
  34141. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34142. if (mesh) {
  34143. wm = mesh.getWorldMatrix();
  34144. }
  34145. this._skeleton.computeAbsoluteTransforms();
  34146. var tmat = BABYLON.Tmp.Matrix[0];
  34147. var vec = BABYLON.Tmp.Vector3[0];
  34148. if (mesh) {
  34149. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34150. tmat.multiplyToRef(wm, tmat);
  34151. }
  34152. else {
  34153. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34154. }
  34155. tmat.invert();
  34156. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  34157. lm.m[12] = vec.x;
  34158. lm.m[13] = vec.y;
  34159. lm.m[14] = vec.z;
  34160. }
  34161. this.markAsDirty();
  34162. };
  34163. /**
  34164. * Set the absolute postion of the bone (world space).
  34165. * @param position The position to set the bone.
  34166. * @param mesh The mesh that this bone is attached to.
  34167. */
  34168. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  34169. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  34170. };
  34171. /**
  34172. * Set the scale of the bone on the x, y and z axes.
  34173. * @param x The scale of the bone on the x axis.
  34174. * @param x The scale of the bone on the y axis.
  34175. * @param z The scale of the bone on the z axis.
  34176. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34177. */
  34178. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  34179. if (scaleChildren === void 0) { scaleChildren = false; }
  34180. if (this.animations[0] && !this.animations[0].isStopped()) {
  34181. if (!scaleChildren) {
  34182. this._negateScaleChildren.x = 1 / x;
  34183. this._negateScaleChildren.y = 1 / y;
  34184. this._negateScaleChildren.z = 1 / z;
  34185. }
  34186. this._syncScaleVector();
  34187. }
  34188. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  34189. };
  34190. /**
  34191. * Scale the bone on the x, y and z axes.
  34192. * @param x The amount to scale the bone on the x axis.
  34193. * @param x The amount to scale the bone on the y axis.
  34194. * @param z The amount to scale the bone on the z axis.
  34195. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34196. */
  34197. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  34198. if (scaleChildren === void 0) { scaleChildren = false; }
  34199. var locMat = this.getLocalMatrix();
  34200. var origLocMat = BABYLON.Tmp.Matrix[0];
  34201. origLocMat.copyFrom(locMat);
  34202. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  34203. origLocMatInv.copyFrom(origLocMat);
  34204. origLocMatInv.invert();
  34205. var scaleMat = BABYLON.Tmp.Matrix[2];
  34206. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  34207. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  34208. this._scaleVector.x *= x;
  34209. this._scaleVector.y *= y;
  34210. this._scaleVector.z *= z;
  34211. locMat.multiplyToRef(origLocMatInv, locMat);
  34212. locMat.multiplyToRef(scaleMat, locMat);
  34213. locMat.multiplyToRef(origLocMat, locMat);
  34214. var parent = this.getParent();
  34215. if (parent) {
  34216. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  34217. }
  34218. else {
  34219. this.getAbsoluteTransform().copyFrom(locMat);
  34220. }
  34221. var len = this.children.length;
  34222. scaleMat.invert();
  34223. for (var i = 0; i < len; i++) {
  34224. var child = this.children[i];
  34225. var cm = child.getLocalMatrix();
  34226. cm.multiplyToRef(scaleMat, cm);
  34227. var lm = child.getLocalMatrix();
  34228. lm.m[12] *= x;
  34229. lm.m[13] *= y;
  34230. lm.m[14] *= z;
  34231. }
  34232. this.computeAbsoluteTransforms();
  34233. if (scaleChildren) {
  34234. for (var i = 0; i < len; i++) {
  34235. this.children[i].scale(x, y, z, scaleChildren);
  34236. }
  34237. }
  34238. this.markAsDirty();
  34239. };
  34240. /**
  34241. * Set the yaw, pitch, and roll of the bone in local or world space.
  34242. * @param yaw The rotation of the bone on the y axis.
  34243. * @param pitch The rotation of the bone on the x axis.
  34244. * @param roll The rotation of the bone on the z axis.
  34245. * @param space The space that the axes of rotation are in.
  34246. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34247. */
  34248. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  34249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34250. var rotMat = BABYLON.Tmp.Matrix[0];
  34251. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  34252. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34253. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34254. rotMatInv.multiplyToRef(rotMat, rotMat);
  34255. this._rotateWithMatrix(rotMat, space, mesh);
  34256. };
  34257. /**
  34258. * Rotate the bone on an axis in local or world space.
  34259. * @param axis The axis to rotate the bone on.
  34260. * @param amount The amount to rotate the bone.
  34261. * @param space The space that the axis is in.
  34262. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34263. */
  34264. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  34265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34266. var rmat = BABYLON.Tmp.Matrix[0];
  34267. rmat.m[12] = 0;
  34268. rmat.m[13] = 0;
  34269. rmat.m[14] = 0;
  34270. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  34271. this._rotateWithMatrix(rmat, space, mesh);
  34272. };
  34273. /**
  34274. * Set the rotation of the bone to a particular axis angle in local or world space.
  34275. * @param axis The axis to rotate the bone on.
  34276. * @param angle The angle that the bone should be rotated to.
  34277. * @param space The space that the axis is in.
  34278. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34279. */
  34280. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  34281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34282. var rotMat = BABYLON.Tmp.Matrix[0];
  34283. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  34284. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34285. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34286. rotMatInv.multiplyToRef(rotMat, rotMat);
  34287. this._rotateWithMatrix(rotMat, space, mesh);
  34288. };
  34289. /**
  34290. * Set the euler rotation of the bone in local of world space.
  34291. * @param rotation The euler rotation that the bone should be set to.
  34292. * @param space The space that the rotation is in.
  34293. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34294. */
  34295. Bone.prototype.setRotation = function (rotation, space, mesh) {
  34296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34297. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  34298. };
  34299. /**
  34300. * Set the quaternion rotation of the bone in local of world space.
  34301. * @param quat The quaternion rotation that the bone should be set to.
  34302. * @param space The space that the rotation is in.
  34303. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34304. */
  34305. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  34306. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34307. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34308. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34309. var rotMat = BABYLON.Tmp.Matrix[1];
  34310. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  34311. rotMatInv.multiplyToRef(rotMat, rotMat);
  34312. this._rotateWithMatrix(rotMat, space, mesh);
  34313. };
  34314. /**
  34315. * Set the rotation matrix of the bone in local of world space.
  34316. * @param rotMat The rotation matrix that the bone should be set to.
  34317. * @param space The space that the rotation is in.
  34318. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34319. */
  34320. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  34321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34322. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34323. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34324. var rotMat2 = BABYLON.Tmp.Matrix[1];
  34325. rotMat2.copyFrom(rotMat);
  34326. rotMatInv.multiplyToRef(rotMat, rotMat2);
  34327. this._rotateWithMatrix(rotMat2, space, mesh);
  34328. };
  34329. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  34330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34331. var lmat = this.getLocalMatrix();
  34332. var lx = lmat.m[12];
  34333. var ly = lmat.m[13];
  34334. var lz = lmat.m[14];
  34335. var parent = this.getParent();
  34336. var parentScale = BABYLON.Tmp.Matrix[3];
  34337. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  34338. if (parent) {
  34339. if (space == BABYLON.Space.WORLD) {
  34340. if (mesh) {
  34341. parentScale.copyFrom(mesh.getWorldMatrix());
  34342. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  34343. }
  34344. else {
  34345. parentScale.copyFrom(parent.getAbsoluteTransform());
  34346. }
  34347. }
  34348. else {
  34349. parentScale = parent._scaleMatrix;
  34350. }
  34351. parentScaleInv.copyFrom(parentScale);
  34352. parentScaleInv.invert();
  34353. lmat.multiplyToRef(parentScale, lmat);
  34354. lmat.multiplyToRef(rmat, lmat);
  34355. lmat.multiplyToRef(parentScaleInv, lmat);
  34356. }
  34357. else {
  34358. if (space == BABYLON.Space.WORLD && mesh) {
  34359. parentScale.copyFrom(mesh.getWorldMatrix());
  34360. parentScaleInv.copyFrom(parentScale);
  34361. parentScaleInv.invert();
  34362. lmat.multiplyToRef(parentScale, lmat);
  34363. lmat.multiplyToRef(rmat, lmat);
  34364. lmat.multiplyToRef(parentScaleInv, lmat);
  34365. }
  34366. else {
  34367. lmat.multiplyToRef(rmat, lmat);
  34368. }
  34369. }
  34370. lmat.m[12] = lx;
  34371. lmat.m[13] = ly;
  34372. lmat.m[14] = lz;
  34373. this.computeAbsoluteTransforms();
  34374. this.markAsDirty();
  34375. };
  34376. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  34377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34378. if (space == BABYLON.Space.WORLD) {
  34379. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34380. scaleMatrix.copyFrom(this._scaleMatrix);
  34381. rotMatInv.copyFrom(this.getAbsoluteTransform());
  34382. if (mesh) {
  34383. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  34384. var meshScale = BABYLON.Tmp.Matrix[3];
  34385. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  34386. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  34387. }
  34388. rotMatInv.invert();
  34389. scaleMatrix.m[0] *= this._scalingDeterminant;
  34390. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34391. }
  34392. else {
  34393. rotMatInv.copyFrom(this.getLocalMatrix());
  34394. rotMatInv.invert();
  34395. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34396. scaleMatrix.copyFrom(this._scaleMatrix);
  34397. if (this._parent) {
  34398. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  34399. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  34400. pscaleMatrix.invert();
  34401. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  34402. }
  34403. else {
  34404. scaleMatrix.m[0] *= this._scalingDeterminant;
  34405. }
  34406. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34407. }
  34408. };
  34409. /**
  34410. * Get the scale of the bone
  34411. * @returns the scale of the bone
  34412. */
  34413. Bone.prototype.getScale = function () {
  34414. return this._scaleVector.clone();
  34415. };
  34416. /**
  34417. * Copy the scale of the bone to a vector3.
  34418. * @param result The vector3 to copy the scale to
  34419. */
  34420. Bone.prototype.getScaleToRef = function (result) {
  34421. result.copyFrom(this._scaleVector);
  34422. };
  34423. /**
  34424. * Get the position of the bone in local or world space.
  34425. * @param space The space that the returned position is in.
  34426. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34427. * @returns The position of the bone
  34428. */
  34429. Bone.prototype.getPosition = function (space, mesh) {
  34430. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34431. var pos = BABYLON.Vector3.Zero();
  34432. this.getPositionToRef(space, mesh, pos);
  34433. return pos;
  34434. };
  34435. /**
  34436. * Copy the position of the bone to a vector3 in local or world space.
  34437. * @param space The space that the returned position is in.
  34438. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34439. * @param result The vector3 to copy the position to.
  34440. */
  34441. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  34442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34443. if (space == BABYLON.Space.LOCAL) {
  34444. var lm = this.getLocalMatrix();
  34445. result.x = lm.m[12];
  34446. result.y = lm.m[13];
  34447. result.z = lm.m[14];
  34448. }
  34449. else {
  34450. var wm;
  34451. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34452. if (mesh) {
  34453. wm = mesh.getWorldMatrix();
  34454. }
  34455. this._skeleton.computeAbsoluteTransforms();
  34456. var tmat = BABYLON.Tmp.Matrix[0];
  34457. if (mesh) {
  34458. tmat.copyFrom(this.getAbsoluteTransform());
  34459. tmat.multiplyToRef(wm, tmat);
  34460. }
  34461. else {
  34462. tmat = this.getAbsoluteTransform();
  34463. }
  34464. result.x = tmat.m[12];
  34465. result.y = tmat.m[13];
  34466. result.z = tmat.m[14];
  34467. }
  34468. };
  34469. /**
  34470. * Get the absolute position of the bone (world space).
  34471. * @param mesh The mesh that this bone is attached to.
  34472. * @returns The absolute position of the bone
  34473. */
  34474. Bone.prototype.getAbsolutePosition = function (mesh) {
  34475. var pos = BABYLON.Vector3.Zero();
  34476. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  34477. return pos;
  34478. };
  34479. /**
  34480. * Copy the absolute position of the bone (world space) to the result param.
  34481. * @param mesh The mesh that this bone is attached to.
  34482. * @param result The vector3 to copy the absolute position to.
  34483. */
  34484. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  34485. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  34486. };
  34487. /**
  34488. * Compute the absolute transforms of this bone and its children.
  34489. */
  34490. Bone.prototype.computeAbsoluteTransforms = function () {
  34491. if (this._parent) {
  34492. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34493. }
  34494. else {
  34495. this._absoluteTransform.copyFrom(this._localMatrix);
  34496. var poseMatrix = this._skeleton.getPoseMatrix();
  34497. if (poseMatrix) {
  34498. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  34499. }
  34500. }
  34501. var children = this.children;
  34502. var len = children.length;
  34503. for (var i = 0; i < len; i++) {
  34504. children[i].computeAbsoluteTransforms();
  34505. }
  34506. };
  34507. Bone.prototype._syncScaleVector = function () {
  34508. var lm = this.getLocalMatrix();
  34509. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  34510. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  34511. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  34512. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  34513. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  34514. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  34515. this._scaleVector.x = xs * Math.sqrt(xsq);
  34516. this._scaleVector.y = ys * Math.sqrt(ysq);
  34517. this._scaleVector.z = zs * Math.sqrt(zsq);
  34518. if (this._parent) {
  34519. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  34520. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  34521. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  34522. }
  34523. 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);
  34524. };
  34525. /**
  34526. * Get the world direction from an axis that is in the local space of the bone.
  34527. * @param localAxis The local direction that is used to compute the world direction.
  34528. * @param mesh The mesh that this bone is attached to.
  34529. * @returns The world direction
  34530. */
  34531. Bone.prototype.getDirection = function (localAxis, mesh) {
  34532. var result = BABYLON.Vector3.Zero();
  34533. this.getDirectionToRef(localAxis, mesh, result);
  34534. return result;
  34535. };
  34536. /**
  34537. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  34538. * @param localAxis The local direction that is used to compute the world direction.
  34539. * @param mesh The mesh that this bone is attached to.
  34540. * @param result The vector3 that the world direction will be copied to.
  34541. */
  34542. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  34543. var wm;
  34544. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34545. if (mesh) {
  34546. wm = mesh.getWorldMatrix();
  34547. }
  34548. this._skeleton.computeAbsoluteTransforms();
  34549. var mat = BABYLON.Tmp.Matrix[0];
  34550. mat.copyFrom(this.getAbsoluteTransform());
  34551. if (mesh) {
  34552. mat.multiplyToRef(wm, mat);
  34553. }
  34554. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  34555. result.normalize();
  34556. };
  34557. /**
  34558. * Get the euler rotation of the bone in local or world space.
  34559. * @param space The space that the rotation should be in.
  34560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34561. * @returns The euler rotation
  34562. */
  34563. Bone.prototype.getRotation = function (space, mesh) {
  34564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34565. var result = BABYLON.Vector3.Zero();
  34566. this.getRotationToRef(space, mesh, result);
  34567. return result;
  34568. };
  34569. /**
  34570. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  34571. * @param space The space that the rotation should be in.
  34572. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34573. * @param result The vector3 that the rotation should be copied to.
  34574. */
  34575. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  34576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34577. var quat = BABYLON.Tmp.Quaternion[0];
  34578. this.getRotationQuaternionToRef(space, mesh, quat);
  34579. quat.toEulerAnglesToRef(result);
  34580. };
  34581. /**
  34582. * Get the quaternion rotation of the bone in either local or world space.
  34583. * @param space The space that the rotation should be in.
  34584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34585. * @returns The quaternion rotation
  34586. */
  34587. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  34588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34589. var result = BABYLON.Quaternion.Identity();
  34590. this.getRotationQuaternionToRef(space, mesh, result);
  34591. return result;
  34592. };
  34593. /**
  34594. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  34595. * @param space The space that the rotation should be in.
  34596. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34597. * @param result The quaternion that the rotation should be copied to.
  34598. */
  34599. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  34600. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34601. if (space == BABYLON.Space.LOCAL) {
  34602. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34603. }
  34604. else {
  34605. var mat = BABYLON.Tmp.Matrix[0];
  34606. var amat = this.getAbsoluteTransform();
  34607. if (mesh) {
  34608. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34609. }
  34610. else {
  34611. mat.copyFrom(amat);
  34612. }
  34613. mat.m[0] *= this._scalingDeterminant;
  34614. mat.m[1] *= this._scalingDeterminant;
  34615. mat.m[2] *= this._scalingDeterminant;
  34616. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34617. }
  34618. };
  34619. /**
  34620. * Get the rotation matrix of the bone in local or world space.
  34621. * @param space The space that the rotation should be in.
  34622. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34623. * @returns The rotation matrix
  34624. */
  34625. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34626. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34627. var result = BABYLON.Matrix.Identity();
  34628. this.getRotationMatrixToRef(space, mesh, result);
  34629. return result;
  34630. };
  34631. /**
  34632. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34633. * @param space The space that the rotation should be in.
  34634. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34635. * @param result The quaternion that the rotation should be copied to.
  34636. */
  34637. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34639. if (space == BABYLON.Space.LOCAL) {
  34640. this.getLocalMatrix().getRotationMatrixToRef(result);
  34641. }
  34642. else {
  34643. var mat = BABYLON.Tmp.Matrix[0];
  34644. var amat = this.getAbsoluteTransform();
  34645. if (mesh) {
  34646. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34647. }
  34648. else {
  34649. mat.copyFrom(amat);
  34650. }
  34651. mat.m[0] *= this._scalingDeterminant;
  34652. mat.m[1] *= this._scalingDeterminant;
  34653. mat.m[2] *= this._scalingDeterminant;
  34654. mat.getRotationMatrixToRef(result);
  34655. }
  34656. };
  34657. /**
  34658. * Get the world position of a point that is in the local space of the bone.
  34659. * @param position The local position
  34660. * @param mesh The mesh that this bone is attached to.
  34661. * @returns The world position
  34662. */
  34663. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34664. var result = BABYLON.Vector3.Zero();
  34665. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34666. return result;
  34667. };
  34668. /**
  34669. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34670. * @param position The local position
  34671. * @param mesh The mesh that this bone is attached to.
  34672. * @param result The vector3 that the world position should be copied to.
  34673. */
  34674. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34675. var wm;
  34676. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34677. if (mesh) {
  34678. wm = mesh.getWorldMatrix();
  34679. }
  34680. this._skeleton.computeAbsoluteTransforms();
  34681. var tmat = BABYLON.Tmp.Matrix[0];
  34682. if (mesh) {
  34683. tmat.copyFrom(this.getAbsoluteTransform());
  34684. tmat.multiplyToRef(wm, tmat);
  34685. }
  34686. else {
  34687. tmat = this.getAbsoluteTransform();
  34688. }
  34689. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34690. };
  34691. /**
  34692. * Get the local position of a point that is in world space.
  34693. * @param position The world position
  34694. * @param mesh The mesh that this bone is attached to.
  34695. * @returns The local position
  34696. */
  34697. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34698. var result = BABYLON.Vector3.Zero();
  34699. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34700. return result;
  34701. };
  34702. /**
  34703. * Get the local position of a point that is in world space and copy it to the result param.
  34704. * @param position The world position
  34705. * @param mesh The mesh that this bone is attached to.
  34706. * @param result The vector3 that the local position should be copied to.
  34707. */
  34708. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34709. var wm;
  34710. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34711. if (mesh) {
  34712. wm = mesh.getWorldMatrix();
  34713. }
  34714. this._skeleton.computeAbsoluteTransforms();
  34715. var tmat = BABYLON.Tmp.Matrix[0];
  34716. tmat.copyFrom(this.getAbsoluteTransform());
  34717. if (mesh) {
  34718. tmat.multiplyToRef(wm, tmat);
  34719. }
  34720. tmat.invert();
  34721. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34722. };
  34723. return Bone;
  34724. }(BABYLON.Node));
  34725. BABYLON.Bone = Bone;
  34726. })(BABYLON || (BABYLON = {}));
  34727. //# sourceMappingURL=babylon.bone.js.map
  34728. var BABYLON;
  34729. (function (BABYLON) {
  34730. var BoneIKController = (function () {
  34731. function BoneIKController(mesh, bone, options) {
  34732. this.targetPosition = BABYLON.Vector3.Zero();
  34733. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34734. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34735. this.poleAngle = 0;
  34736. this.slerpAmount = 1;
  34737. this._bone1Quat = BABYLON.Quaternion.Identity();
  34738. this._bone1Mat = BABYLON.Matrix.Identity();
  34739. this._bone2Ang = Math.PI;
  34740. this._maxAngle = Math.PI;
  34741. this._rightHandedSystem = false;
  34742. this._bendAxis = BABYLON.Vector3.Right();
  34743. this._slerping = false;
  34744. this._adjustRoll = 0;
  34745. this._bone2 = bone;
  34746. this._bone1 = bone.getParent();
  34747. this.mesh = mesh;
  34748. var bonePos = bone.getPosition();
  34749. if (bone.getAbsoluteTransform().determinant() > 0) {
  34750. this._rightHandedSystem = true;
  34751. this._bendAxis.x = 0;
  34752. this._bendAxis.y = 0;
  34753. this._bendAxis.z = -1;
  34754. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34755. this._adjustRoll = Math.PI * .5;
  34756. this._bendAxis.z = 1;
  34757. }
  34758. }
  34759. if (this._bone1.length) {
  34760. var boneScale1 = this._bone1.getScale();
  34761. var boneScale2 = this._bone2.getScale();
  34762. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34763. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34764. }
  34765. else if (this._bone1.children[0]) {
  34766. mesh.computeWorldMatrix(true);
  34767. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34768. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34769. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34770. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34771. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34772. }
  34773. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34774. this.maxAngle = Math.PI;
  34775. if (options) {
  34776. if (options.targetMesh) {
  34777. this.targetMesh = options.targetMesh;
  34778. this.targetMesh.computeWorldMatrix(true);
  34779. }
  34780. if (options.poleTargetMesh) {
  34781. this.poleTargetMesh = options.poleTargetMesh;
  34782. this.poleTargetMesh.computeWorldMatrix(true);
  34783. }
  34784. else if (options.poleTargetBone) {
  34785. this.poleTargetBone = options.poleTargetBone;
  34786. }
  34787. else if (this._bone1.getParent()) {
  34788. this.poleTargetBone = this._bone1.getParent();
  34789. }
  34790. if (options.poleTargetLocalOffset) {
  34791. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34792. }
  34793. if (options.poleAngle) {
  34794. this.poleAngle = options.poleAngle;
  34795. }
  34796. if (options.bendAxis) {
  34797. this._bendAxis.copyFrom(options.bendAxis);
  34798. }
  34799. if (options.maxAngle) {
  34800. this.maxAngle = options.maxAngle;
  34801. }
  34802. if (options.slerpAmount) {
  34803. this.slerpAmount = options.slerpAmount;
  34804. }
  34805. }
  34806. }
  34807. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34808. get: function () {
  34809. return this._maxAngle;
  34810. },
  34811. set: function (value) {
  34812. this._setMaxAngle(value);
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. BoneIKController.prototype._setMaxAngle = function (ang) {
  34818. if (ang < 0) {
  34819. ang = 0;
  34820. }
  34821. if (ang > Math.PI || ang == undefined) {
  34822. ang = Math.PI;
  34823. }
  34824. this._maxAngle = ang;
  34825. var a = this._bone1Length;
  34826. var b = this._bone2Length;
  34827. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34828. };
  34829. BoneIKController.prototype.update = function () {
  34830. var bone1 = this._bone1;
  34831. var target = this.targetPosition;
  34832. var poleTarget = this.poleTargetPosition;
  34833. var mat1 = BoneIKController._tmpMats[0];
  34834. var mat2 = BoneIKController._tmpMats[1];
  34835. if (this.targetMesh) {
  34836. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34837. }
  34838. if (this.poleTargetBone) {
  34839. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34840. }
  34841. else if (this.poleTargetMesh) {
  34842. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34843. }
  34844. var bonePos = BoneIKController._tmpVecs[0];
  34845. var zaxis = BoneIKController._tmpVecs[1];
  34846. var xaxis = BoneIKController._tmpVecs[2];
  34847. var yaxis = BoneIKController._tmpVecs[3];
  34848. var upAxis = BoneIKController._tmpVecs[4];
  34849. var _tmpQuat = BoneIKController._tmpQuat;
  34850. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34851. poleTarget.subtractToRef(bonePos, upAxis);
  34852. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34853. upAxis.y = 1;
  34854. }
  34855. else {
  34856. upAxis.normalize();
  34857. }
  34858. target.subtractToRef(bonePos, yaxis);
  34859. yaxis.normalize();
  34860. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34861. zaxis.normalize();
  34862. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34863. xaxis.normalize();
  34864. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34865. var a = this._bone1Length;
  34866. var b = this._bone2Length;
  34867. var c = BABYLON.Vector3.Distance(bonePos, target);
  34868. if (this._maxReach > 0) {
  34869. c = Math.min(this._maxReach, c);
  34870. }
  34871. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34872. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34873. if (acosa > 1) {
  34874. acosa = 1;
  34875. }
  34876. if (acosb > 1) {
  34877. acosb = 1;
  34878. }
  34879. if (acosa < -1) {
  34880. acosa = -1;
  34881. }
  34882. if (acosb < -1) {
  34883. acosb = -1;
  34884. }
  34885. var angA = Math.acos(acosa);
  34886. var angB = Math.acos(acosb);
  34887. var angC = -angA - angB;
  34888. if (this._rightHandedSystem) {
  34889. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34890. mat2.multiplyToRef(mat1, mat1);
  34891. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34892. mat2.multiplyToRef(mat1, mat1);
  34893. }
  34894. else {
  34895. var _tmpVec = BoneIKController._tmpVecs[5];
  34896. _tmpVec.copyFrom(this._bendAxis);
  34897. _tmpVec.x *= -1;
  34898. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  34899. mat2.multiplyToRef(mat1, mat1);
  34900. }
  34901. if (this.poleAngle) {
  34902. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34903. mat1.multiplyToRef(mat2, mat1);
  34904. }
  34905. if (this.slerpAmount < 1) {
  34906. if (!this._slerping) {
  34907. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34908. }
  34909. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  34910. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  34911. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34912. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34913. this._slerping = true;
  34914. }
  34915. else {
  34916. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34917. this._bone1Mat.copyFrom(mat1);
  34918. this._slerping = false;
  34919. }
  34920. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34921. this._bone2Ang = angC;
  34922. };
  34923. return BoneIKController;
  34924. }());
  34925. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34926. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  34927. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34928. BABYLON.BoneIKController = BoneIKController;
  34929. })(BABYLON || (BABYLON = {}));
  34930. //# sourceMappingURL=babylon.boneIKController.js.map
  34931. var BABYLON;
  34932. (function (BABYLON) {
  34933. var BoneLookController = (function () {
  34934. /**
  34935. * Create a BoneLookController
  34936. * @param mesh the mesh that the bone belongs to
  34937. * @param bone the bone that will be looking to the target
  34938. * @param target the target Vector3 to look at
  34939. * @param settings optional settings:
  34940. * - maxYaw: the maximum angle the bone will yaw to
  34941. * - minYaw: the minimum angle the bone will yaw to
  34942. * - maxPitch: the maximum angle the bone will pitch to
  34943. * - minPitch: the minimum angle the bone will yaw to
  34944. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34945. * - upAxis: the up axis of the coordinate system
  34946. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34947. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34948. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34949. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34950. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34951. * - adjustRoll: used to make an adjustment to the roll of the bone
  34952. **/
  34953. function BoneLookController(mesh, bone, target, options) {
  34954. /**
  34955. * The up axis of the coordinate system that is used when the bone is rotated.
  34956. */
  34957. this.upAxis = BABYLON.Vector3.Up();
  34958. /**
  34959. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34960. */
  34961. this.upAxisSpace = BABYLON.Space.LOCAL;
  34962. /**
  34963. * Used to make an adjustment to the yaw of the bone.
  34964. */
  34965. this.adjustYaw = 0;
  34966. /**
  34967. * Used to make an adjustment to the pitch of the bone.
  34968. */
  34969. this.adjustPitch = 0;
  34970. /**
  34971. * Used to make an adjustment to the roll of the bone.
  34972. */
  34973. this.adjustRoll = 0;
  34974. /**
  34975. * 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).
  34976. */
  34977. this.slerpAmount = 1;
  34978. this._boneQuat = BABYLON.Quaternion.Identity();
  34979. this._slerping = false;
  34980. this._firstFrameSkipped = false;
  34981. this._fowardAxis = BABYLON.Vector3.Forward();
  34982. this.mesh = mesh;
  34983. this.bone = bone;
  34984. this.target = target;
  34985. if (options) {
  34986. if (options.adjustYaw) {
  34987. this.adjustYaw = options.adjustYaw;
  34988. }
  34989. if (options.adjustPitch) {
  34990. this.adjustPitch = options.adjustPitch;
  34991. }
  34992. if (options.adjustRoll) {
  34993. this.adjustRoll = options.adjustRoll;
  34994. }
  34995. if (options.maxYaw != null) {
  34996. this.maxYaw = options.maxYaw;
  34997. }
  34998. else {
  34999. this.maxYaw = Math.PI;
  35000. }
  35001. if (options.minYaw != null) {
  35002. this.minYaw = options.minYaw;
  35003. }
  35004. else {
  35005. this.minYaw = -Math.PI;
  35006. }
  35007. if (options.maxPitch != null) {
  35008. this.maxPitch = options.maxPitch;
  35009. }
  35010. else {
  35011. this.maxPitch = Math.PI;
  35012. }
  35013. if (options.minPitch != null) {
  35014. this.minPitch = options.minPitch;
  35015. }
  35016. else {
  35017. this.minPitch = -Math.PI;
  35018. }
  35019. if (options.slerpAmount != null) {
  35020. this.slerpAmount = options.slerpAmount;
  35021. }
  35022. if (options.upAxis != null) {
  35023. this.upAxis = options.upAxis;
  35024. }
  35025. if (options.upAxisSpace != null) {
  35026. this.upAxisSpace = options.upAxisSpace;
  35027. }
  35028. if (options.yawAxis != null || options.pitchAxis != null) {
  35029. var newYawAxis = BABYLON.Axis.Y;
  35030. var newPitchAxis = BABYLON.Axis.X;
  35031. if (options.yawAxis != null) {
  35032. newYawAxis = options.yawAxis.clone();
  35033. newYawAxis.normalize();
  35034. }
  35035. if (options.pitchAxis != null) {
  35036. newPitchAxis = options.pitchAxis.clone();
  35037. newPitchAxis.normalize();
  35038. }
  35039. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  35040. this._transformYawPitch = BABYLON.Matrix.Identity();
  35041. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  35042. this._transformYawPitchInv = this._transformYawPitch.clone();
  35043. this._transformYawPitch.invert();
  35044. }
  35045. }
  35046. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  35047. this.upAxisSpace = BABYLON.Space.LOCAL;
  35048. }
  35049. }
  35050. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  35051. /**
  35052. * Get/set the minimum yaw angle that the bone can look to.
  35053. */
  35054. get: function () {
  35055. return this._minYaw;
  35056. },
  35057. set: function (value) {
  35058. this._minYaw = value;
  35059. this._minYawSin = Math.sin(value);
  35060. this._minYawCos = Math.cos(value);
  35061. if (this._maxYaw != null) {
  35062. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  35063. this._yawRange = this._maxYaw - this._minYaw;
  35064. }
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  35070. /**
  35071. * Get/set the maximum yaw angle that the bone can look to.
  35072. */
  35073. get: function () {
  35074. return this._maxYaw;
  35075. },
  35076. set: function (value) {
  35077. this._maxYaw = value;
  35078. this._maxYawSin = Math.sin(value);
  35079. this._maxYawCos = Math.cos(value);
  35080. if (this._minYaw != null) {
  35081. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  35082. this._yawRange = this._maxYaw - this._minYaw;
  35083. }
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  35089. /**
  35090. * Get/set the minimum pitch angle that the bone can look to.
  35091. */
  35092. get: function () {
  35093. return this._minPitch;
  35094. },
  35095. set: function (value) {
  35096. this._minPitch = value;
  35097. this._minPitchTan = Math.tan(value);
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  35103. /**
  35104. * Get/set the maximum pitch angle that the bone can look to.
  35105. */
  35106. get: function () {
  35107. return this._maxPitch;
  35108. },
  35109. set: function (value) {
  35110. this._maxPitch = value;
  35111. this._maxPitchTan = Math.tan(value);
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. /**
  35117. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  35118. */
  35119. BoneLookController.prototype.update = function () {
  35120. //skip the first frame when slerping so that the mesh rotation is correct
  35121. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  35122. this._firstFrameSkipped = true;
  35123. return;
  35124. }
  35125. var bone = this.bone;
  35126. var bonePos = BoneLookController._tmpVecs[0];
  35127. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  35128. var target = this.target;
  35129. var _tmpMat1 = BoneLookController._tmpMats[0];
  35130. var _tmpMat2 = BoneLookController._tmpMats[1];
  35131. var mesh = this.mesh;
  35132. var parentBone = bone.getParent();
  35133. var upAxis = BoneLookController._tmpVecs[1];
  35134. upAxis.copyFrom(this.upAxis);
  35135. if (this.upAxisSpace == BABYLON.Space.BONE) {
  35136. if (this._transformYawPitch) {
  35137. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  35138. }
  35139. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  35140. }
  35141. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  35142. mesh.getDirectionToRef(upAxis, upAxis);
  35143. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  35144. upAxis.normalize();
  35145. }
  35146. }
  35147. var checkYaw = false;
  35148. var checkPitch = false;
  35149. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  35150. checkYaw = true;
  35151. }
  35152. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  35153. checkPitch = true;
  35154. }
  35155. if (checkYaw || checkPitch) {
  35156. var spaceMat = BoneLookController._tmpMats[2];
  35157. var spaceMatInv = BoneLookController._tmpMats[3];
  35158. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  35159. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  35160. }
  35161. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  35162. spaceMat.copyFrom(mesh.getWorldMatrix());
  35163. }
  35164. else {
  35165. var forwardAxis = BoneLookController._tmpVecs[2];
  35166. forwardAxis.copyFrom(this._fowardAxis);
  35167. if (this._transformYawPitch) {
  35168. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  35169. }
  35170. if (parentBone) {
  35171. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  35172. }
  35173. else {
  35174. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  35175. }
  35176. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  35177. rightAxis.normalize();
  35178. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  35179. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  35180. }
  35181. spaceMat.invertToRef(spaceMatInv);
  35182. var xzlen;
  35183. if (checkPitch) {
  35184. var localTarget = BoneLookController._tmpVecs[3];
  35185. target.subtractToRef(bonePos, localTarget);
  35186. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35187. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35188. var pitch = Math.atan2(localTarget.y, xzlen);
  35189. var newPitch = pitch;
  35190. if (pitch > this._maxPitch) {
  35191. localTarget.y = this._maxPitchTan * xzlen;
  35192. newPitch = this._maxPitch;
  35193. }
  35194. else if (pitch < this._minPitch) {
  35195. localTarget.y = this._minPitchTan * xzlen;
  35196. newPitch = this._minPitch;
  35197. }
  35198. if (pitch != newPitch) {
  35199. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35200. localTarget.addInPlace(bonePos);
  35201. target = localTarget;
  35202. }
  35203. }
  35204. if (checkYaw) {
  35205. var localTarget = BoneLookController._tmpVecs[4];
  35206. target.subtractToRef(bonePos, localTarget);
  35207. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35208. var yaw = Math.atan2(localTarget.x, localTarget.z);
  35209. var newYaw = yaw;
  35210. if (yaw > this._maxYaw || yaw < this._minYaw) {
  35211. if (xzlen == null) {
  35212. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35213. }
  35214. if (this._yawRange > Math.PI) {
  35215. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  35216. localTarget.z = this._maxYawCos * xzlen;
  35217. localTarget.x = this._maxYawSin * xzlen;
  35218. newYaw = this._maxYaw;
  35219. }
  35220. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  35221. localTarget.z = this._minYawCos * xzlen;
  35222. localTarget.x = this._minYawSin * xzlen;
  35223. newYaw = this._minYaw;
  35224. }
  35225. }
  35226. else {
  35227. if (yaw > this._maxYaw) {
  35228. localTarget.z = this._maxYawCos * xzlen;
  35229. localTarget.x = this._maxYawSin * xzlen;
  35230. newYaw = this._maxYaw;
  35231. }
  35232. else if (yaw < this._minYaw) {
  35233. localTarget.z = this._minYawCos * xzlen;
  35234. localTarget.x = this._minYawSin * xzlen;
  35235. newYaw = this._minYaw;
  35236. }
  35237. }
  35238. }
  35239. if (this._slerping && this._yawRange > Math.PI) {
  35240. //are we going to be crossing into the min/max region?
  35241. var boneFwd = BoneLookController._tmpVecs[8];
  35242. boneFwd.copyFrom(BABYLON.Axis.Z);
  35243. if (this._transformYawPitch) {
  35244. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  35245. }
  35246. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  35247. this._boneQuat.toRotationMatrix(boneRotMat);
  35248. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  35249. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  35250. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  35251. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  35252. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  35253. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  35254. if (angBtwTar > angBtwMidYaw) {
  35255. if (xzlen == null) {
  35256. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35257. }
  35258. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  35259. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  35260. if (angBtwMin < angBtwMax) {
  35261. newYaw = boneYaw + Math.PI * .75;
  35262. localTarget.z = Math.cos(newYaw) * xzlen;
  35263. localTarget.x = Math.sin(newYaw) * xzlen;
  35264. }
  35265. else {
  35266. newYaw = boneYaw - Math.PI * .75;
  35267. localTarget.z = Math.cos(newYaw) * xzlen;
  35268. localTarget.x = Math.sin(newYaw) * xzlen;
  35269. }
  35270. }
  35271. }
  35272. if (yaw != newYaw) {
  35273. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35274. localTarget.addInPlace(bonePos);
  35275. target = localTarget;
  35276. }
  35277. }
  35278. }
  35279. var zaxis = BoneLookController._tmpVecs[5];
  35280. var xaxis = BoneLookController._tmpVecs[6];
  35281. var yaxis = BoneLookController._tmpVecs[7];
  35282. var _tmpQuat = BoneLookController._tmpQuat;
  35283. target.subtractToRef(bonePos, zaxis);
  35284. zaxis.normalize();
  35285. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  35286. xaxis.normalize();
  35287. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  35288. yaxis.normalize();
  35289. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  35290. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  35291. return;
  35292. }
  35293. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  35294. return;
  35295. }
  35296. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  35297. return;
  35298. }
  35299. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  35300. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  35301. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  35302. }
  35303. if (this.slerpAmount < 1) {
  35304. if (!this._slerping) {
  35305. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  35306. }
  35307. if (this._transformYawPitch) {
  35308. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35309. }
  35310. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  35311. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  35312. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  35313. this._slerping = true;
  35314. }
  35315. else {
  35316. if (this._transformYawPitch) {
  35317. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35318. }
  35319. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  35320. this._slerping = false;
  35321. }
  35322. };
  35323. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  35324. var angDiff = ang2 - ang1;
  35325. angDiff %= Math.PI * 2;
  35326. if (angDiff > Math.PI) {
  35327. angDiff -= Math.PI * 2;
  35328. }
  35329. else if (angDiff < -Math.PI) {
  35330. angDiff += Math.PI * 2;
  35331. }
  35332. return angDiff;
  35333. };
  35334. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  35335. ang1 %= (2 * Math.PI);
  35336. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35337. ang2 %= (2 * Math.PI);
  35338. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35339. var ab = 0;
  35340. if (ang1 < ang2) {
  35341. ab = ang2 - ang1;
  35342. }
  35343. else {
  35344. ab = ang1 - ang2;
  35345. }
  35346. if (ab > Math.PI) {
  35347. ab = Math.PI * 2 - ab;
  35348. }
  35349. return ab;
  35350. };
  35351. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  35352. ang %= (2 * Math.PI);
  35353. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  35354. ang1 %= (2 * Math.PI);
  35355. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35356. ang2 %= (2 * Math.PI);
  35357. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35358. if (ang1 < ang2) {
  35359. if (ang > ang1 && ang < ang2) {
  35360. return true;
  35361. }
  35362. }
  35363. else {
  35364. if (ang > ang2 && ang < ang1) {
  35365. return true;
  35366. }
  35367. }
  35368. return false;
  35369. };
  35370. return BoneLookController;
  35371. }());
  35372. 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()];
  35373. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  35374. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35375. BABYLON.BoneLookController = BoneLookController;
  35376. })(BABYLON || (BABYLON = {}));
  35377. //# sourceMappingURL=babylon.boneLookController.js.map
  35378. var BABYLON;
  35379. (function (BABYLON) {
  35380. var Skeleton = (function () {
  35381. function Skeleton(name, id, scene) {
  35382. this.name = name;
  35383. this.id = id;
  35384. this.bones = new Array();
  35385. this.needInitialSkinMatrix = false;
  35386. this._isDirty = true;
  35387. this._meshesWithPoseMatrix = new Array();
  35388. this._identity = BABYLON.Matrix.Identity();
  35389. this._ranges = {};
  35390. this._lastAbsoluteTransformsUpdateId = -1;
  35391. // Events
  35392. /**
  35393. * An event triggered before computing the skeleton's matrices
  35394. * @type {BABYLON.Observable}
  35395. */
  35396. this.onBeforeComputeObservable = new BABYLON.Observable();
  35397. this.bones = [];
  35398. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35399. scene.skeletons.push(this);
  35400. //make sure it will recalculate the matrix next time prepare is called.
  35401. this._isDirty = true;
  35402. }
  35403. // Members
  35404. Skeleton.prototype.getTransformMatrices = function (mesh) {
  35405. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  35406. return mesh._bonesTransformMatrices;
  35407. }
  35408. if (!this._transformMatrices) {
  35409. this.prepare();
  35410. }
  35411. return this._transformMatrices;
  35412. };
  35413. Skeleton.prototype.getScene = function () {
  35414. return this._scene;
  35415. };
  35416. // Methods
  35417. /**
  35418. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35419. */
  35420. Skeleton.prototype.toString = function (fullDetails) {
  35421. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  35422. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35423. if (fullDetails) {
  35424. ret += ", Ranges: {";
  35425. var first = true;
  35426. for (var name_1 in this._ranges) {
  35427. if (first) {
  35428. ret += ", ";
  35429. first = false;
  35430. }
  35431. ret += name_1;
  35432. }
  35433. ret += "}";
  35434. }
  35435. return ret;
  35436. };
  35437. /**
  35438. * Get bone's index searching by name
  35439. * @param {string} name is bone's name to search for
  35440. * @return {number} Indice of the bone. Returns -1 if not found
  35441. */
  35442. Skeleton.prototype.getBoneIndexByName = function (name) {
  35443. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  35444. if (this.bones[boneIndex].name === name) {
  35445. return boneIndex;
  35446. }
  35447. }
  35448. return -1;
  35449. };
  35450. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  35451. // check name not already in use
  35452. if (!this._ranges[name]) {
  35453. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  35454. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35455. if (this.bones[i].animations[0]) {
  35456. this.bones[i].animations[0].createRange(name, from, to);
  35457. }
  35458. }
  35459. }
  35460. };
  35461. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  35462. if (deleteFrames === void 0) { deleteFrames = true; }
  35463. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35464. if (this.bones[i].animations[0]) {
  35465. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  35466. }
  35467. }
  35468. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35469. };
  35470. Skeleton.prototype.getAnimationRange = function (name) {
  35471. return this._ranges[name];
  35472. };
  35473. /**
  35474. * Returns as an Array, all AnimationRanges defined on this skeleton
  35475. */
  35476. Skeleton.prototype.getAnimationRanges = function () {
  35477. var animationRanges = [];
  35478. var name;
  35479. var i = 0;
  35480. for (name in this._ranges) {
  35481. animationRanges[i] = this._ranges[name];
  35482. i++;
  35483. }
  35484. return animationRanges;
  35485. };
  35486. /**
  35487. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  35488. */
  35489. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  35490. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35491. if (this._ranges[name] || !source.getAnimationRange(name)) {
  35492. return false;
  35493. }
  35494. var ret = true;
  35495. var frameOffset = this._getHighestAnimationFrame() + 1;
  35496. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  35497. var boneDict = {};
  35498. var sourceBones = source.bones;
  35499. var nBones;
  35500. var i;
  35501. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  35502. boneDict[sourceBones[i].name] = sourceBones[i];
  35503. }
  35504. if (this.bones.length !== sourceBones.length) {
  35505. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  35506. ret = false;
  35507. }
  35508. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  35509. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  35510. var boneName = this.bones[i].name;
  35511. var sourceBone = boneDict[boneName];
  35512. if (sourceBone) {
  35513. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  35514. }
  35515. else {
  35516. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  35517. ret = false;
  35518. }
  35519. }
  35520. // do not call createAnimationRange(), since it also is done to bones, which was already done
  35521. var range = source.getAnimationRange(name);
  35522. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  35523. return ret;
  35524. };
  35525. Skeleton.prototype.returnToRest = function () {
  35526. for (var index = 0; index < this.bones.length; index++) {
  35527. this.bones[index].returnToRest();
  35528. }
  35529. };
  35530. Skeleton.prototype._getHighestAnimationFrame = function () {
  35531. var ret = 0;
  35532. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35533. if (this.bones[i].animations[0]) {
  35534. var highest = this.bones[i].animations[0].getHighestFrame();
  35535. if (ret < highest) {
  35536. ret = highest;
  35537. }
  35538. }
  35539. }
  35540. return ret;
  35541. };
  35542. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  35543. var range = this.getAnimationRange(name);
  35544. if (!range) {
  35545. return null;
  35546. }
  35547. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  35548. };
  35549. Skeleton.prototype._markAsDirty = function () {
  35550. this._isDirty = true;
  35551. };
  35552. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  35553. this._meshesWithPoseMatrix.push(mesh);
  35554. };
  35555. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  35556. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  35557. if (index > -1) {
  35558. this._meshesWithPoseMatrix.splice(index, 1);
  35559. }
  35560. };
  35561. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  35562. this.onBeforeComputeObservable.notifyObservers(this);
  35563. for (var index = 0; index < this.bones.length; index++) {
  35564. var bone = this.bones[index];
  35565. var parentBone = bone.getParent();
  35566. if (parentBone) {
  35567. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  35568. }
  35569. else {
  35570. if (initialSkinMatrix) {
  35571. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  35572. }
  35573. else {
  35574. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  35575. }
  35576. }
  35577. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  35578. }
  35579. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  35580. };
  35581. Skeleton.prototype.prepare = function () {
  35582. if (!this._isDirty) {
  35583. return;
  35584. }
  35585. if (this.needInitialSkinMatrix) {
  35586. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  35587. var mesh = this._meshesWithPoseMatrix[index];
  35588. var poseMatrix = mesh.getPoseMatrix();
  35589. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  35590. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35591. }
  35592. if (this._synchronizedWithMesh !== mesh) {
  35593. this._synchronizedWithMesh = mesh;
  35594. // Prepare bones
  35595. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  35596. var bone = this.bones[boneIndex];
  35597. if (!bone.getParent()) {
  35598. var matrix = bone.getBaseMatrix();
  35599. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  35600. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  35601. }
  35602. }
  35603. }
  35604. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  35605. }
  35606. }
  35607. else {
  35608. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  35609. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35610. }
  35611. this._computeTransformMatrices(this._transformMatrices, null);
  35612. }
  35613. this._isDirty = false;
  35614. this._scene._activeBones.addCount(this.bones.length, false);
  35615. };
  35616. Skeleton.prototype.getAnimatables = function () {
  35617. if (!this._animatables || this._animatables.length !== this.bones.length) {
  35618. this._animatables = [];
  35619. for (var index = 0; index < this.bones.length; index++) {
  35620. this._animatables.push(this.bones[index]);
  35621. }
  35622. }
  35623. return this._animatables;
  35624. };
  35625. Skeleton.prototype.clone = function (name, id) {
  35626. var result = new Skeleton(name, id || name, this._scene);
  35627. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35628. for (var index = 0; index < this.bones.length; index++) {
  35629. var source = this.bones[index];
  35630. var parentBone = null;
  35631. if (source.getParent()) {
  35632. var parentIndex = this.bones.indexOf(source.getParent());
  35633. parentBone = result.bones[parentIndex];
  35634. }
  35635. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35636. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35637. }
  35638. if (this._ranges) {
  35639. result._ranges = {};
  35640. for (var rangeName in this._ranges) {
  35641. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35642. }
  35643. }
  35644. this._isDirty = true;
  35645. return result;
  35646. };
  35647. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35648. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35649. this.bones.forEach(function (bone) {
  35650. bone.animations.forEach(function (animation) {
  35651. animation.enableBlending = true;
  35652. animation.blendingSpeed = blendingSpeed;
  35653. });
  35654. });
  35655. };
  35656. Skeleton.prototype.dispose = function () {
  35657. this._meshesWithPoseMatrix = [];
  35658. // Animations
  35659. this.getScene().stopAnimation(this);
  35660. // Remove from scene
  35661. this.getScene().removeSkeleton(this);
  35662. };
  35663. Skeleton.prototype.serialize = function () {
  35664. var serializationObject = {};
  35665. serializationObject.name = this.name;
  35666. serializationObject.id = this.id;
  35667. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35668. serializationObject.bones = [];
  35669. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35670. for (var index = 0; index < this.bones.length; index++) {
  35671. var bone = this.bones[index];
  35672. var serializedBone = {
  35673. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35674. name: bone.name,
  35675. matrix: bone.getBaseMatrix().toArray(),
  35676. rest: bone.getRestPose().toArray()
  35677. };
  35678. serializationObject.bones.push(serializedBone);
  35679. if (bone.length) {
  35680. serializedBone.length = bone.length;
  35681. }
  35682. if (bone.animations && bone.animations.length > 0) {
  35683. serializedBone.animation = bone.animations[0].serialize();
  35684. }
  35685. serializationObject.ranges = [];
  35686. for (var name in this._ranges) {
  35687. var range = {};
  35688. range.name = name;
  35689. range.from = this._ranges[name].from;
  35690. range.to = this._ranges[name].to;
  35691. serializationObject.ranges.push(range);
  35692. }
  35693. }
  35694. return serializationObject;
  35695. };
  35696. Skeleton.Parse = function (parsedSkeleton, scene) {
  35697. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35698. if (parsedSkeleton.dimensionsAtRest) {
  35699. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35700. }
  35701. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35702. var index;
  35703. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35704. var parsedBone = parsedSkeleton.bones[index];
  35705. var parentBone = null;
  35706. if (parsedBone.parentBoneIndex > -1) {
  35707. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35708. }
  35709. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35710. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35711. if (parsedBone.length) {
  35712. bone.length = parsedBone.length;
  35713. }
  35714. if (parsedBone.animation) {
  35715. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35716. }
  35717. }
  35718. // placed after bones, so createAnimationRange can cascade down
  35719. if (parsedSkeleton.ranges) {
  35720. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35721. var data = parsedSkeleton.ranges[index];
  35722. skeleton.createAnimationRange(data.name, data.from, data.to);
  35723. }
  35724. }
  35725. return skeleton;
  35726. };
  35727. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35728. if (forceUpdate === void 0) { forceUpdate = false; }
  35729. var renderId = this._scene.getRenderId();
  35730. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35731. this.bones[0].computeAbsoluteTransforms();
  35732. this._lastAbsoluteTransformsUpdateId = renderId;
  35733. }
  35734. };
  35735. Skeleton.prototype.getPoseMatrix = function () {
  35736. var poseMatrix;
  35737. if (this._meshesWithPoseMatrix.length > 0) {
  35738. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35739. }
  35740. return poseMatrix;
  35741. };
  35742. return Skeleton;
  35743. }());
  35744. BABYLON.Skeleton = Skeleton;
  35745. })(BABYLON || (BABYLON = {}));
  35746. //# sourceMappingURL=babylon.skeleton.js.map
  35747. var BABYLON;
  35748. (function (BABYLON) {
  35749. var PostProcess = (function () {
  35750. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35752. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35753. this.name = name;
  35754. this.width = -1;
  35755. this.height = -1;
  35756. /*
  35757. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35758. Can only be used on a single postprocess or on the last one of a chain.
  35759. */
  35760. this.enablePixelPerfectMode = false;
  35761. this.samples = 1;
  35762. this._reusable = false;
  35763. this._textures = new BABYLON.SmartArray(2);
  35764. this._currentRenderTextureInd = 0;
  35765. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35766. // Events
  35767. /**
  35768. * An event triggered when the postprocess is activated.
  35769. * @type {BABYLON.Observable}
  35770. */
  35771. this.onActivateObservable = new BABYLON.Observable();
  35772. /**
  35773. * An event triggered when the postprocess changes its size.
  35774. * @type {BABYLON.Observable}
  35775. */
  35776. this.onSizeChangedObservable = new BABYLON.Observable();
  35777. /**
  35778. * An event triggered when the postprocess applies its effect.
  35779. * @type {BABYLON.Observable}
  35780. */
  35781. this.onApplyObservable = new BABYLON.Observable();
  35782. /**
  35783. * An event triggered before rendering the postprocess
  35784. * @type {BABYLON.Observable}
  35785. */
  35786. this.onBeforeRenderObservable = new BABYLON.Observable();
  35787. /**
  35788. * An event triggered after rendering the postprocess
  35789. * @type {BABYLON.Observable}
  35790. */
  35791. this.onAfterRenderObservable = new BABYLON.Observable();
  35792. if (camera != null) {
  35793. this._camera = camera;
  35794. this._scene = camera.getScene();
  35795. camera.attachPostProcess(this);
  35796. this._engine = this._scene.getEngine();
  35797. }
  35798. else {
  35799. this._engine = engine;
  35800. }
  35801. this._options = options;
  35802. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35803. this._reusable = reusable || false;
  35804. this._textureType = textureType;
  35805. this._samplers = samplers || [];
  35806. this._samplers.push("textureSampler");
  35807. this._fragmentUrl = fragmentUrl;
  35808. this._parameters = parameters || [];
  35809. this._parameters.push("scale");
  35810. this.updateEffect(defines);
  35811. }
  35812. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35813. set: function (callback) {
  35814. if (this._onActivateObserver) {
  35815. this.onActivateObservable.remove(this._onActivateObserver);
  35816. }
  35817. this._onActivateObserver = this.onActivateObservable.add(callback);
  35818. },
  35819. enumerable: true,
  35820. configurable: true
  35821. });
  35822. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35823. set: function (callback) {
  35824. if (this._onSizeChangedObserver) {
  35825. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35826. }
  35827. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35828. },
  35829. enumerable: true,
  35830. configurable: true
  35831. });
  35832. Object.defineProperty(PostProcess.prototype, "onApply", {
  35833. set: function (callback) {
  35834. if (this._onApplyObserver) {
  35835. this.onApplyObservable.remove(this._onApplyObserver);
  35836. }
  35837. this._onApplyObserver = this.onApplyObservable.add(callback);
  35838. },
  35839. enumerable: true,
  35840. configurable: true
  35841. });
  35842. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35843. set: function (callback) {
  35844. if (this._onBeforeRenderObserver) {
  35845. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35846. }
  35847. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35848. },
  35849. enumerable: true,
  35850. configurable: true
  35851. });
  35852. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35853. set: function (callback) {
  35854. if (this._onAfterRenderObserver) {
  35855. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35856. }
  35857. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35858. },
  35859. enumerable: true,
  35860. configurable: true
  35861. });
  35862. PostProcess.prototype.updateEffect = function (defines) {
  35863. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35864. };
  35865. PostProcess.prototype.isReusable = function () {
  35866. return this._reusable;
  35867. };
  35868. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35869. PostProcess.prototype.markTextureDirty = function () {
  35870. this.width = -1;
  35871. };
  35872. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35873. var _this = this;
  35874. camera = camera || this._camera;
  35875. var scene = camera.getScene();
  35876. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35877. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35878. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35879. var desiredWidth = this._options.width || requiredWidth;
  35880. var desiredHeight = this._options.height || requiredHeight;
  35881. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35882. if (!this._options.width) {
  35883. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35884. }
  35885. if (!this._options.height) {
  35886. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35887. }
  35888. }
  35889. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35890. if (this._textures.length > 0) {
  35891. for (var i = 0; i < this._textures.length; i++) {
  35892. this._engine._releaseTexture(this._textures.data[i]);
  35893. }
  35894. this._textures.reset();
  35895. }
  35896. this.width = desiredWidth;
  35897. this.height = desiredHeight;
  35898. var textureSize = { width: this.width, height: this.height };
  35899. var textureOptions = {
  35900. generateMipMaps: false,
  35901. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35902. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35903. samplingMode: this.renderTargetSamplingMode,
  35904. type: this._textureType
  35905. };
  35906. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35907. if (this._reusable) {
  35908. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35909. }
  35910. this.onSizeChangedObservable.notifyObservers(this);
  35911. }
  35912. this._textures.forEach(function (texture) {
  35913. if (texture.samples !== _this.samples) {
  35914. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35915. }
  35916. });
  35917. if (this.enablePixelPerfectMode) {
  35918. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35919. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35920. }
  35921. else {
  35922. this._scaleRatio.copyFromFloats(1, 1);
  35923. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35924. }
  35925. this.onActivateObservable.notifyObservers(camera);
  35926. // Clear
  35927. if (this.clearColor) {
  35928. this._engine.clear(this.clearColor, true, true, true);
  35929. }
  35930. else {
  35931. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35932. }
  35933. if (this._reusable) {
  35934. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35935. }
  35936. };
  35937. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35938. get: function () {
  35939. return this._effect.isSupported;
  35940. },
  35941. enumerable: true,
  35942. configurable: true
  35943. });
  35944. PostProcess.prototype.apply = function () {
  35945. // Check
  35946. if (!this._effect.isReady())
  35947. return null;
  35948. // States
  35949. this._engine.enableEffect(this._effect);
  35950. this._engine.setState(false);
  35951. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35952. this._engine.setDepthBuffer(false);
  35953. this._engine.setDepthWrite(false);
  35954. // Texture
  35955. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35956. // Parameters
  35957. this._effect.setVector2("scale", this._scaleRatio);
  35958. this.onApplyObservable.notifyObservers(this._effect);
  35959. return this._effect;
  35960. };
  35961. PostProcess.prototype.dispose = function (camera) {
  35962. camera = camera || this._camera;
  35963. if (this._textures.length > 0) {
  35964. for (var i = 0; i < this._textures.length; i++) {
  35965. this._engine._releaseTexture(this._textures.data[i]);
  35966. }
  35967. }
  35968. this._textures.dispose();
  35969. if (!camera) {
  35970. return;
  35971. }
  35972. camera.detachPostProcess(this);
  35973. var index = camera._postProcesses.indexOf(this);
  35974. if (index === 0 && camera._postProcesses.length > 0) {
  35975. this._camera._postProcesses[0].markTextureDirty();
  35976. }
  35977. this.onActivateObservable.clear();
  35978. this.onAfterRenderObservable.clear();
  35979. this.onApplyObservable.clear();
  35980. this.onBeforeRenderObservable.clear();
  35981. this.onSizeChangedObservable.clear();
  35982. };
  35983. return PostProcess;
  35984. }());
  35985. BABYLON.PostProcess = PostProcess;
  35986. })(BABYLON || (BABYLON = {}));
  35987. //# sourceMappingURL=babylon.postProcess.js.map
  35988. var BABYLON;
  35989. (function (BABYLON) {
  35990. var PostProcessManager = (function () {
  35991. function PostProcessManager(scene) {
  35992. this._vertexBuffers = {};
  35993. this._scene = scene;
  35994. }
  35995. PostProcessManager.prototype._prepareBuffers = function () {
  35996. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35997. return;
  35998. }
  35999. // VBO
  36000. var vertices = [];
  36001. vertices.push(1, 1);
  36002. vertices.push(-1, 1);
  36003. vertices.push(-1, -1);
  36004. vertices.push(1, -1);
  36005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36006. // Indices
  36007. var indices = [];
  36008. indices.push(0);
  36009. indices.push(1);
  36010. indices.push(2);
  36011. indices.push(0);
  36012. indices.push(2);
  36013. indices.push(3);
  36014. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36015. };
  36016. // Methods
  36017. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  36018. var postProcesses = this._scene.activeCamera._postProcesses;
  36019. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36020. return false;
  36021. }
  36022. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  36023. return true;
  36024. };
  36025. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  36026. var engine = this._scene.getEngine();
  36027. for (var index = 0; index < postProcesses.length; index++) {
  36028. if (index < postProcesses.length - 1) {
  36029. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36030. }
  36031. else {
  36032. if (targetTexture) {
  36033. engine.bindFramebuffer(targetTexture);
  36034. }
  36035. else {
  36036. engine.restoreDefaultFramebuffer();
  36037. }
  36038. }
  36039. var pp = postProcesses[index];
  36040. var effect = pp.apply();
  36041. if (effect) {
  36042. pp.onBeforeRenderObservable.notifyObservers(effect);
  36043. // VBOs
  36044. this._prepareBuffers();
  36045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36046. // Draw order
  36047. engine.draw(true, 0, 6);
  36048. pp.onAfterRenderObservable.notifyObservers(effect);
  36049. }
  36050. }
  36051. // Restore depth buffer
  36052. engine.setDepthBuffer(true);
  36053. engine.setDepthWrite(true);
  36054. };
  36055. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  36056. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  36057. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36058. return;
  36059. }
  36060. var engine = this._scene.getEngine();
  36061. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36062. if (index < len - 1) {
  36063. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36064. }
  36065. else {
  36066. if (targetTexture) {
  36067. engine.bindFramebuffer(targetTexture, faceIndex);
  36068. }
  36069. else {
  36070. engine.restoreDefaultFramebuffer();
  36071. }
  36072. }
  36073. if (doNotPresent) {
  36074. break;
  36075. }
  36076. var pp = postProcesses[index];
  36077. var effect = pp.apply();
  36078. if (effect) {
  36079. pp.onBeforeRenderObservable.notifyObservers(effect);
  36080. // VBOs
  36081. this._prepareBuffers();
  36082. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36083. // Draw order
  36084. engine.draw(true, 0, 6);
  36085. pp.onAfterRenderObservable.notifyObservers(effect);
  36086. }
  36087. }
  36088. // Restore depth buffer
  36089. engine.setDepthBuffer(true);
  36090. engine.setDepthWrite(true);
  36091. };
  36092. PostProcessManager.prototype.dispose = function () {
  36093. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36094. if (buffer) {
  36095. buffer.dispose();
  36096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36097. }
  36098. if (this._indexBuffer) {
  36099. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36100. this._indexBuffer = null;
  36101. }
  36102. };
  36103. return PostProcessManager;
  36104. }());
  36105. BABYLON.PostProcessManager = PostProcessManager;
  36106. })(BABYLON || (BABYLON = {}));
  36107. //# sourceMappingURL=babylon.postProcessManager.js.map
  36108. var BABYLON;
  36109. (function (BABYLON) {
  36110. var PassPostProcess = (function (_super) {
  36111. __extends(PassPostProcess, _super);
  36112. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  36113. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36114. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  36115. }
  36116. return PassPostProcess;
  36117. }(BABYLON.PostProcess));
  36118. BABYLON.PassPostProcess = PassPostProcess;
  36119. })(BABYLON || (BABYLON = {}));
  36120. //# sourceMappingURL=babylon.passPostProcess.js.map
  36121. var BABYLON;
  36122. (function (BABYLON) {
  36123. /**
  36124. * This is a holder class for the physics joint created by the physics plugin.
  36125. * It holds a set of functions to control the underlying joint.
  36126. */
  36127. var PhysicsJoint = (function () {
  36128. function PhysicsJoint(type, jointData) {
  36129. this.type = type;
  36130. this.jointData = jointData;
  36131. jointData.nativeParams = jointData.nativeParams || {};
  36132. }
  36133. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  36134. get: function () {
  36135. return this._physicsJoint;
  36136. },
  36137. set: function (newJoint) {
  36138. if (this._physicsJoint) {
  36139. //remove from the wolrd
  36140. }
  36141. this._physicsJoint = newJoint;
  36142. },
  36143. enumerable: true,
  36144. configurable: true
  36145. });
  36146. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  36147. set: function (physicsPlugin) {
  36148. this._physicsPlugin = physicsPlugin;
  36149. },
  36150. enumerable: true,
  36151. configurable: true
  36152. });
  36153. /**
  36154. * Execute a function that is physics-plugin specific.
  36155. * @param {Function} func the function that will be executed.
  36156. * It accepts two parameters: the physics world and the physics joint.
  36157. */
  36158. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  36159. func(this._physicsPlugin.world, this._physicsJoint);
  36160. };
  36161. return PhysicsJoint;
  36162. }());
  36163. //TODO check if the native joints are the same
  36164. //Joint Types
  36165. PhysicsJoint.DistanceJoint = 0;
  36166. PhysicsJoint.HingeJoint = 1;
  36167. PhysicsJoint.BallAndSocketJoint = 2;
  36168. PhysicsJoint.WheelJoint = 3;
  36169. PhysicsJoint.SliderJoint = 4;
  36170. //OIMO
  36171. PhysicsJoint.PrismaticJoint = 5;
  36172. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  36173. PhysicsJoint.UniversalJoint = 6;
  36174. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  36175. //Cannon
  36176. //Similar to a Ball-Joint. Different in params
  36177. PhysicsJoint.PointToPointJoint = 8;
  36178. //Cannon only at the moment
  36179. PhysicsJoint.SpringJoint = 9;
  36180. PhysicsJoint.LockJoint = 10;
  36181. BABYLON.PhysicsJoint = PhysicsJoint;
  36182. /**
  36183. * A class representing a physics distance joint.
  36184. */
  36185. var DistanceJoint = (function (_super) {
  36186. __extends(DistanceJoint, _super);
  36187. function DistanceJoint(jointData) {
  36188. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  36189. }
  36190. /**
  36191. * Update the predefined distance.
  36192. */
  36193. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  36194. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  36195. };
  36196. return DistanceJoint;
  36197. }(PhysicsJoint));
  36198. BABYLON.DistanceJoint = DistanceJoint;
  36199. var MotorEnabledJoint = (function (_super) {
  36200. __extends(MotorEnabledJoint, _super);
  36201. function MotorEnabledJoint(type, jointData) {
  36202. return _super.call(this, type, jointData) || this;
  36203. }
  36204. /**
  36205. * Set the motor values.
  36206. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36207. * @param {number} force the force to apply
  36208. * @param {number} maxForce max force for this motor.
  36209. */
  36210. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  36211. this._physicsPlugin.setMotor(this, force, maxForce);
  36212. };
  36213. /**
  36214. * Set the motor's limits.
  36215. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36216. */
  36217. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36218. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36219. };
  36220. return MotorEnabledJoint;
  36221. }(PhysicsJoint));
  36222. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  36223. /**
  36224. * This class represents a single hinge physics joint
  36225. */
  36226. var HingeJoint = (function (_super) {
  36227. __extends(HingeJoint, _super);
  36228. function HingeJoint(jointData) {
  36229. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  36230. }
  36231. /**
  36232. * Set the motor values.
  36233. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36234. * @param {number} force the force to apply
  36235. * @param {number} maxForce max force for this motor.
  36236. */
  36237. HingeJoint.prototype.setMotor = function (force, maxForce) {
  36238. this._physicsPlugin.setMotor(this, force, maxForce);
  36239. };
  36240. /**
  36241. * Set the motor's limits.
  36242. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36243. */
  36244. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36245. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36246. };
  36247. return HingeJoint;
  36248. }(MotorEnabledJoint));
  36249. BABYLON.HingeJoint = HingeJoint;
  36250. /**
  36251. * This class represents a dual hinge physics joint (same as wheel joint)
  36252. */
  36253. var Hinge2Joint = (function (_super) {
  36254. __extends(Hinge2Joint, _super);
  36255. function Hinge2Joint(jointData) {
  36256. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  36257. }
  36258. /**
  36259. * Set the motor values.
  36260. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36261. * @param {number} force the force to apply
  36262. * @param {number} maxForce max force for this motor.
  36263. * @param {motorIndex} the motor's index, 0 or 1.
  36264. */
  36265. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  36266. if (motorIndex === void 0) { motorIndex = 0; }
  36267. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  36268. };
  36269. /**
  36270. * Set the motor limits.
  36271. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36272. * @param {number} upperLimit the upper limit
  36273. * @param {number} lowerLimit lower limit
  36274. * @param {motorIndex} the motor's index, 0 or 1.
  36275. */
  36276. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  36277. if (motorIndex === void 0) { motorIndex = 0; }
  36278. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  36279. };
  36280. return Hinge2Joint;
  36281. }(MotorEnabledJoint));
  36282. BABYLON.Hinge2Joint = Hinge2Joint;
  36283. })(BABYLON || (BABYLON = {}));
  36284. //# sourceMappingURL=babylon.physicsJoint.js.map
  36285. var BABYLON;
  36286. (function (BABYLON) {
  36287. var PhysicsImpostor = (function () {
  36288. function PhysicsImpostor(object, type, _options, _scene) {
  36289. if (_options === void 0) { _options = { mass: 0 }; }
  36290. var _this = this;
  36291. this.object = object;
  36292. this.type = type;
  36293. this._options = _options;
  36294. this._scene = _scene;
  36295. this._bodyUpdateRequired = false;
  36296. this._onBeforePhysicsStepCallbacks = new Array();
  36297. this._onAfterPhysicsStepCallbacks = new Array();
  36298. this._onPhysicsCollideCallbacks = [];
  36299. this._deltaPosition = BABYLON.Vector3.Zero();
  36300. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  36301. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  36302. /**
  36303. * this function is executed by the physics engine.
  36304. */
  36305. this.beforeStep = function () {
  36306. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  36307. //conjugate deltaRotation
  36308. if (_this._deltaRotationConjugated) {
  36309. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  36310. }
  36311. else {
  36312. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  36313. }
  36314. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  36315. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  36316. func(_this);
  36317. });
  36318. };
  36319. /**
  36320. * this function is executed by the physics engine.
  36321. */
  36322. this.afterStep = function () {
  36323. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  36324. func(_this);
  36325. });
  36326. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  36327. _this.object.position.addInPlace(_this._deltaPosition);
  36328. if (_this._deltaRotation) {
  36329. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  36330. }
  36331. };
  36332. /**
  36333. * Legacy collision detection event support
  36334. */
  36335. this.onCollideEvent = null;
  36336. //event and body object due to cannon's event-based architecture.
  36337. this.onCollide = function (e) {
  36338. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  36339. return;
  36340. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  36341. if (otherImpostor) {
  36342. // Legacy collision detection event support
  36343. if (_this.onCollideEvent) {
  36344. _this.onCollideEvent(_this, otherImpostor);
  36345. }
  36346. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  36347. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  36348. }).forEach(function (obj) {
  36349. obj.callback(_this, otherImpostor);
  36350. });
  36351. }
  36352. };
  36353. //sanity check!
  36354. if (!this.object) {
  36355. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  36356. return;
  36357. }
  36358. //legacy support for old syntax.
  36359. if (!this._scene && object.getScene) {
  36360. this._scene = object.getScene();
  36361. }
  36362. this._physicsEngine = this._scene.getPhysicsEngine();
  36363. if (!this._physicsEngine) {
  36364. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  36365. }
  36366. else {
  36367. //set the object's quaternion, if not set
  36368. if (!this.object.rotationQuaternion) {
  36369. if (this.object.rotation) {
  36370. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  36371. }
  36372. else {
  36373. this.object.rotationQuaternion = new BABYLON.Quaternion();
  36374. }
  36375. }
  36376. //default options params
  36377. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  36378. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  36379. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  36380. this._joints = [];
  36381. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  36382. if (!this.object.parent) {
  36383. this._init();
  36384. }
  36385. }
  36386. }
  36387. /**
  36388. * This function will completly initialize this impostor.
  36389. * It will create a new body - but only if this mesh has no parent.
  36390. * If it has, this impostor will not be used other than to define the impostor
  36391. * of the child mesh.
  36392. */
  36393. PhysicsImpostor.prototype._init = function () {
  36394. this._physicsEngine.removeImpostor(this);
  36395. this.physicsBody = null;
  36396. this._parent = this._parent || this._getPhysicsParent();
  36397. if (!this.parent) {
  36398. this._physicsEngine.addImpostor(this);
  36399. }
  36400. };
  36401. PhysicsImpostor.prototype._getPhysicsParent = function () {
  36402. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  36403. var parentMesh = this.object.parent;
  36404. return parentMesh.physicsImpostor;
  36405. }
  36406. return;
  36407. };
  36408. /**
  36409. * Should a new body be generated.
  36410. */
  36411. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  36412. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  36413. };
  36414. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  36415. this.forceUpdate();
  36416. };
  36417. /**
  36418. * Force a regeneration of this or the parent's impostor's body.
  36419. * Use under cautious - This will remove all joints already implemented.
  36420. */
  36421. PhysicsImpostor.prototype.forceUpdate = function () {
  36422. this._init();
  36423. if (this.parent) {
  36424. this.parent.forceUpdate();
  36425. }
  36426. };
  36427. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  36428. /*public get mesh(): AbstractMesh {
  36429. return this._mesh;
  36430. }*/
  36431. /**
  36432. * Gets the body that holds this impostor. Either its own, or its parent.
  36433. */
  36434. get: function () {
  36435. return this._parent ? this._parent.physicsBody : this._physicsBody;
  36436. },
  36437. /**
  36438. * Set the physics body. Used mainly by the physics engine/plugin
  36439. */
  36440. set: function (physicsBody) {
  36441. if (this._physicsBody) {
  36442. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  36443. }
  36444. this._physicsBody = physicsBody;
  36445. this.resetUpdateFlags();
  36446. },
  36447. enumerable: true,
  36448. configurable: true
  36449. });
  36450. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  36451. get: function () {
  36452. return this._parent;
  36453. },
  36454. set: function (value) {
  36455. this._parent = value;
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  36461. this._bodyUpdateRequired = false;
  36462. };
  36463. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  36464. if (this.object.getBoundingInfo) {
  36465. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  36466. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  36467. }
  36468. else {
  36469. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  36470. }
  36471. };
  36472. PhysicsImpostor.prototype.getObjectCenter = function () {
  36473. if (this.object.getBoundingInfo) {
  36474. return this.object.getBoundingInfo().boundingBox.centerWorld;
  36475. }
  36476. else {
  36477. return this.object.position;
  36478. }
  36479. };
  36480. /**
  36481. * Get a specific parametes from the options parameter.
  36482. */
  36483. PhysicsImpostor.prototype.getParam = function (paramName) {
  36484. return this._options[paramName];
  36485. };
  36486. /**
  36487. * Sets a specific parameter in the options given to the physics plugin
  36488. */
  36489. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  36490. this._options[paramName] = value;
  36491. this._bodyUpdateRequired = true;
  36492. };
  36493. /**
  36494. * Specifically change the body's mass option. Won't recreate the physics body object
  36495. */
  36496. PhysicsImpostor.prototype.setMass = function (mass) {
  36497. if (this.getParam("mass") !== mass) {
  36498. this.setParam("mass", mass);
  36499. }
  36500. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  36501. };
  36502. PhysicsImpostor.prototype.getLinearVelocity = function () {
  36503. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  36504. };
  36505. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  36506. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  36507. };
  36508. PhysicsImpostor.prototype.getAngularVelocity = function () {
  36509. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  36510. };
  36511. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  36512. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  36513. };
  36514. /**
  36515. * Execute a function with the physics plugin native code.
  36516. * Provide a function the will have two variables - the world object and the physics body object.
  36517. */
  36518. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  36519. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  36520. };
  36521. /**
  36522. * Register a function that will be executed before the physics world is stepping forward.
  36523. */
  36524. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  36525. this._onBeforePhysicsStepCallbacks.push(func);
  36526. };
  36527. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  36528. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  36529. if (index > -1) {
  36530. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  36531. }
  36532. else {
  36533. BABYLON.Tools.Warn("Function to remove was not found");
  36534. }
  36535. };
  36536. /**
  36537. * Register a function that will be executed after the physics step
  36538. */
  36539. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  36540. this._onAfterPhysicsStepCallbacks.push(func);
  36541. };
  36542. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  36543. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  36544. if (index > -1) {
  36545. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  36546. }
  36547. else {
  36548. BABYLON.Tools.Warn("Function to remove was not found");
  36549. }
  36550. };
  36551. /**
  36552. * register a function that will be executed when this impostor collides against a different body.
  36553. */
  36554. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  36555. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36556. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  36557. };
  36558. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  36559. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36560. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  36561. if (index > -1) {
  36562. this._onPhysicsCollideCallbacks.splice(index, 1);
  36563. }
  36564. else {
  36565. BABYLON.Tools.Warn("Function to remove was not found");
  36566. }
  36567. };
  36568. /**
  36569. * Apply a force
  36570. */
  36571. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  36572. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  36573. };
  36574. /**
  36575. * Apply an impulse
  36576. */
  36577. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  36578. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  36579. };
  36580. /**
  36581. * A help function to create a joint.
  36582. */
  36583. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  36584. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  36585. this.addJoint(otherImpostor, joint);
  36586. };
  36587. /**
  36588. * Add a joint to this impostor with a different impostor.
  36589. */
  36590. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  36591. this._joints.push({
  36592. otherImpostor: otherImpostor,
  36593. joint: joint
  36594. });
  36595. this._physicsEngine.addJoint(this, otherImpostor, joint);
  36596. };
  36597. /**
  36598. * Will keep this body still, in a sleep mode.
  36599. */
  36600. PhysicsImpostor.prototype.sleep = function () {
  36601. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  36602. };
  36603. /**
  36604. * Wake the body up.
  36605. */
  36606. PhysicsImpostor.prototype.wakeUp = function () {
  36607. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  36608. };
  36609. PhysicsImpostor.prototype.clone = function (newObject) {
  36610. if (!newObject)
  36611. return null;
  36612. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  36613. };
  36614. PhysicsImpostor.prototype.dispose = function () {
  36615. var _this = this;
  36616. //no dispose if no physics engine is available.
  36617. if (!this._physicsEngine) {
  36618. return;
  36619. }
  36620. this._joints.forEach(function (j) {
  36621. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  36622. });
  36623. //dispose the physics body
  36624. this._physicsEngine.removeImpostor(this);
  36625. if (this.parent) {
  36626. this.parent.forceUpdate();
  36627. }
  36628. else {
  36629. /*this._object.getChildMeshes().forEach(function(mesh) {
  36630. if (mesh.physicsImpostor) {
  36631. if (disposeChildren) {
  36632. mesh.physicsImpostor.dispose();
  36633. mesh.physicsImpostor = null;
  36634. }
  36635. }
  36636. })*/
  36637. }
  36638. };
  36639. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36640. this._deltaPosition.copyFrom(position);
  36641. };
  36642. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36643. if (!this._deltaRotation) {
  36644. this._deltaRotation = new BABYLON.Quaternion();
  36645. }
  36646. this._deltaRotation.copyFrom(rotation);
  36647. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36648. };
  36649. return PhysicsImpostor;
  36650. }());
  36651. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36652. //Impostor types
  36653. PhysicsImpostor.NoImpostor = 0;
  36654. PhysicsImpostor.SphereImpostor = 1;
  36655. PhysicsImpostor.BoxImpostor = 2;
  36656. PhysicsImpostor.PlaneImpostor = 3;
  36657. PhysicsImpostor.MeshImpostor = 4;
  36658. PhysicsImpostor.CylinderImpostor = 7;
  36659. PhysicsImpostor.ParticleImpostor = 8;
  36660. PhysicsImpostor.HeightmapImpostor = 9;
  36661. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36662. })(BABYLON || (BABYLON = {}));
  36663. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36664. var BABYLON;
  36665. (function (BABYLON) {
  36666. var PhysicsEngine = (function () {
  36667. function PhysicsEngine(gravity, _physicsPlugin) {
  36668. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36669. this._physicsPlugin = _physicsPlugin;
  36670. //new methods and parameters
  36671. this._impostors = [];
  36672. this._joints = [];
  36673. if (!this._physicsPlugin.isSupported()) {
  36674. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36675. + "Please make sure it is included.");
  36676. }
  36677. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36678. this.setGravity(gravity);
  36679. this.setTimeStep();
  36680. }
  36681. PhysicsEngine.prototype.setGravity = function (gravity) {
  36682. this.gravity = gravity;
  36683. this._physicsPlugin.setGravity(this.gravity);
  36684. };
  36685. /**
  36686. * Set the time step of the physics engine.
  36687. * default is 1/60.
  36688. * To slow it down, enter 1/600 for example.
  36689. * To speed it up, 1/30
  36690. * @param {number} newTimeStep the new timestep to apply to this world.
  36691. */
  36692. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36693. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36694. this._physicsPlugin.setTimeStep(newTimeStep);
  36695. };
  36696. PhysicsEngine.prototype.dispose = function () {
  36697. this._impostors.forEach(function (impostor) {
  36698. impostor.dispose();
  36699. });
  36700. this._physicsPlugin.dispose();
  36701. };
  36702. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36703. return this._physicsPlugin.name;
  36704. };
  36705. /**
  36706. * Adding a new impostor for the impostor tracking.
  36707. * This will be done by the impostor itself.
  36708. * @param {PhysicsImpostor} impostor the impostor to add
  36709. */
  36710. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36711. impostor.uniqueId = this._impostors.push(impostor);
  36712. //if no parent, generate the body
  36713. if (!impostor.parent) {
  36714. this._physicsPlugin.generatePhysicsBody(impostor);
  36715. }
  36716. };
  36717. /**
  36718. * Remove an impostor from the engine.
  36719. * This impostor and its mesh will not longer be updated by the physics engine.
  36720. * @param {PhysicsImpostor} impostor the impostor to remove
  36721. */
  36722. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36723. var index = this._impostors.indexOf(impostor);
  36724. if (index > -1) {
  36725. var removed = this._impostors.splice(index, 1);
  36726. //Is it needed?
  36727. if (removed.length) {
  36728. //this will also remove it from the world.
  36729. removed[0].physicsBody = null;
  36730. }
  36731. }
  36732. };
  36733. /**
  36734. * Add a joint to the physics engine
  36735. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36736. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36737. * @param {PhysicsJoint} the joint that will connect both impostors.
  36738. */
  36739. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36740. var impostorJoint = {
  36741. mainImpostor: mainImpostor,
  36742. connectedImpostor: connectedImpostor,
  36743. joint: joint
  36744. };
  36745. joint.physicsPlugin = this._physicsPlugin;
  36746. this._joints.push(impostorJoint);
  36747. this._physicsPlugin.generateJoint(impostorJoint);
  36748. };
  36749. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36750. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36751. return (impostorJoint.connectedImpostor === connectedImpostor
  36752. && impostorJoint.joint === joint
  36753. && impostorJoint.mainImpostor === mainImpostor);
  36754. });
  36755. if (matchingJoints.length) {
  36756. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36757. //TODO remove it from the list as well
  36758. }
  36759. };
  36760. /**
  36761. * Called by the scene. no need to call it.
  36762. */
  36763. PhysicsEngine.prototype._step = function (delta) {
  36764. var _this = this;
  36765. //check if any mesh has no body / requires an update
  36766. this._impostors.forEach(function (impostor) {
  36767. if (impostor.isBodyInitRequired()) {
  36768. _this._physicsPlugin.generatePhysicsBody(impostor);
  36769. }
  36770. });
  36771. if (delta > 0.1) {
  36772. delta = 0.1;
  36773. }
  36774. else if (delta <= 0) {
  36775. delta = 1.0 / 60.0;
  36776. }
  36777. this._physicsPlugin.executeStep(delta, this._impostors);
  36778. };
  36779. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36780. return this._physicsPlugin;
  36781. };
  36782. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36783. for (var i = 0; i < this._impostors.length; ++i) {
  36784. if (this._impostors[i].object === object) {
  36785. return this._impostors[i];
  36786. }
  36787. }
  36788. };
  36789. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36790. for (var i = 0; i < this._impostors.length; ++i) {
  36791. if (this._impostors[i].physicsBody === body) {
  36792. return this._impostors[i];
  36793. }
  36794. }
  36795. };
  36796. return PhysicsEngine;
  36797. }());
  36798. // Statics
  36799. PhysicsEngine.Epsilon = 0.001;
  36800. BABYLON.PhysicsEngine = PhysicsEngine;
  36801. })(BABYLON || (BABYLON = {}));
  36802. //# sourceMappingURL=babylon.physicsEngine.js.map
  36803. var BABYLON;
  36804. (function (BABYLON) {
  36805. var VertexData = (function () {
  36806. function VertexData() {
  36807. }
  36808. VertexData.prototype.set = function (data, kind) {
  36809. switch (kind) {
  36810. case BABYLON.VertexBuffer.PositionKind:
  36811. this.positions = data;
  36812. break;
  36813. case BABYLON.VertexBuffer.NormalKind:
  36814. this.normals = data;
  36815. break;
  36816. case BABYLON.VertexBuffer.TangentKind:
  36817. this.tangents = data;
  36818. break;
  36819. case BABYLON.VertexBuffer.UVKind:
  36820. this.uvs = data;
  36821. break;
  36822. case BABYLON.VertexBuffer.UV2Kind:
  36823. this.uvs2 = data;
  36824. break;
  36825. case BABYLON.VertexBuffer.UV3Kind:
  36826. this.uvs3 = data;
  36827. break;
  36828. case BABYLON.VertexBuffer.UV4Kind:
  36829. this.uvs4 = data;
  36830. break;
  36831. case BABYLON.VertexBuffer.UV5Kind:
  36832. this.uvs5 = data;
  36833. break;
  36834. case BABYLON.VertexBuffer.UV6Kind:
  36835. this.uvs6 = data;
  36836. break;
  36837. case BABYLON.VertexBuffer.ColorKind:
  36838. this.colors = data;
  36839. break;
  36840. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36841. this.matricesIndices = data;
  36842. break;
  36843. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36844. this.matricesWeights = data;
  36845. break;
  36846. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36847. this.matricesIndicesExtra = data;
  36848. break;
  36849. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36850. this.matricesWeightsExtra = data;
  36851. break;
  36852. }
  36853. };
  36854. /**
  36855. * Associates the vertexData to the passed Mesh.
  36856. * Sets it as updatable or not (default `false`).
  36857. * Returns the VertexData.
  36858. */
  36859. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36860. this._applyTo(mesh, updatable);
  36861. return this;
  36862. };
  36863. /**
  36864. * Associates the vertexData to the passed Geometry.
  36865. * Sets it as updatable or not (default `false`).
  36866. * Returns the VertexData.
  36867. */
  36868. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36869. this._applyTo(geometry, updatable);
  36870. return this;
  36871. };
  36872. /**
  36873. * Updates the associated mesh.
  36874. * Returns the VertexData.
  36875. */
  36876. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36877. this._update(mesh);
  36878. return this;
  36879. };
  36880. /**
  36881. * Updates the associated geometry.
  36882. * Returns the VertexData.
  36883. */
  36884. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36885. this._update(geometry);
  36886. return this;
  36887. };
  36888. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36889. if (this.positions) {
  36890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36891. }
  36892. if (this.normals) {
  36893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36894. }
  36895. if (this.tangents) {
  36896. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36897. }
  36898. if (this.uvs) {
  36899. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36900. }
  36901. if (this.uvs2) {
  36902. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36903. }
  36904. if (this.uvs3) {
  36905. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36906. }
  36907. if (this.uvs4) {
  36908. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36909. }
  36910. if (this.uvs5) {
  36911. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36912. }
  36913. if (this.uvs6) {
  36914. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36915. }
  36916. if (this.colors) {
  36917. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36918. }
  36919. if (this.matricesIndices) {
  36920. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36921. }
  36922. if (this.matricesWeights) {
  36923. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36924. }
  36925. if (this.matricesIndicesExtra) {
  36926. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36927. }
  36928. if (this.matricesWeightsExtra) {
  36929. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36930. }
  36931. if (this.indices) {
  36932. meshOrGeometry.setIndices(this.indices);
  36933. }
  36934. return this;
  36935. };
  36936. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36937. if (this.positions) {
  36938. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36939. }
  36940. if (this.normals) {
  36941. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36942. }
  36943. if (this.tangents) {
  36944. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36945. }
  36946. if (this.uvs) {
  36947. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36948. }
  36949. if (this.uvs2) {
  36950. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36951. }
  36952. if (this.uvs3) {
  36953. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36954. }
  36955. if (this.uvs4) {
  36956. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36957. }
  36958. if (this.uvs5) {
  36959. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36960. }
  36961. if (this.uvs6) {
  36962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36963. }
  36964. if (this.colors) {
  36965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36966. }
  36967. if (this.matricesIndices) {
  36968. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36969. }
  36970. if (this.matricesWeights) {
  36971. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36972. }
  36973. if (this.matricesIndicesExtra) {
  36974. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36975. }
  36976. if (this.matricesWeightsExtra) {
  36977. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36978. }
  36979. if (this.indices) {
  36980. meshOrGeometry.setIndices(this.indices);
  36981. }
  36982. return this;
  36983. };
  36984. /**
  36985. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36986. * Returns the VertexData.
  36987. */
  36988. VertexData.prototype.transform = function (matrix) {
  36989. var transformed = BABYLON.Vector3.Zero();
  36990. var index;
  36991. if (this.positions) {
  36992. var position = BABYLON.Vector3.Zero();
  36993. for (index = 0; index < this.positions.length; index += 3) {
  36994. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36995. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36996. this.positions[index] = transformed.x;
  36997. this.positions[index + 1] = transformed.y;
  36998. this.positions[index + 2] = transformed.z;
  36999. }
  37000. }
  37001. if (this.normals) {
  37002. var normal = BABYLON.Vector3.Zero();
  37003. for (index = 0; index < this.normals.length; index += 3) {
  37004. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37005. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37006. this.normals[index] = transformed.x;
  37007. this.normals[index + 1] = transformed.y;
  37008. this.normals[index + 2] = transformed.z;
  37009. }
  37010. }
  37011. if (this.tangents) {
  37012. var tangent = BABYLON.Vector4.Zero();
  37013. var tangentTransformed = BABYLON.Vector4.Zero();
  37014. for (index = 0; index < this.tangents.length; index += 4) {
  37015. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37016. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37017. this.tangents[index] = tangentTransformed.x;
  37018. this.tangents[index + 1] = tangentTransformed.y;
  37019. this.tangents[index + 2] = tangentTransformed.z;
  37020. this.tangents[index + 3] = tangentTransformed.w;
  37021. }
  37022. }
  37023. return this;
  37024. };
  37025. /**
  37026. * Merges the passed VertexData into the current one.
  37027. * Returns the modified VertexData.
  37028. */
  37029. VertexData.prototype.merge = function (other) {
  37030. if (other.indices) {
  37031. if (!this.indices) {
  37032. this.indices = [];
  37033. }
  37034. var offset = this.positions ? this.positions.length / 3 : 0;
  37035. for (var index = 0; index < other.indices.length; index++) {
  37036. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  37037. this.indices.push(other.indices[index] + offset);
  37038. }
  37039. }
  37040. this.positions = this._mergeElement(this.positions, other.positions);
  37041. this.normals = this._mergeElement(this.normals, other.normals);
  37042. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37043. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37044. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37045. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37046. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37047. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37048. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37049. this.colors = this._mergeElement(this.colors, other.colors);
  37050. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37051. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37052. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37053. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37054. return this;
  37055. };
  37056. VertexData.prototype._mergeElement = function (source, other) {
  37057. if (!other)
  37058. return source;
  37059. if (!source)
  37060. return other;
  37061. var len = other.length + source.length;
  37062. var isSrcTypedArray = source instanceof Float32Array;
  37063. var isOthTypedArray = other instanceof Float32Array;
  37064. // use non-loop method when the source is Float32Array
  37065. if (isSrcTypedArray) {
  37066. var ret32 = new Float32Array(len);
  37067. ret32.set(source);
  37068. ret32.set(other, source.length);
  37069. return ret32;
  37070. // source is number[], when other is also use concat
  37071. }
  37072. else if (!isOthTypedArray) {
  37073. return source.concat(other);
  37074. // source is a number[], but other is a Float32Array, loop required
  37075. }
  37076. else {
  37077. var ret = source.slice(0); // copy source to a separate array
  37078. for (var i = 0, len = other.length; i < len; i++) {
  37079. ret.push(other[i]);
  37080. }
  37081. return ret;
  37082. }
  37083. };
  37084. /**
  37085. * Serializes the VertexData.
  37086. * Returns a serialized object.
  37087. */
  37088. VertexData.prototype.serialize = function () {
  37089. var serializationObject = this.serialize();
  37090. if (this.positions) {
  37091. serializationObject.positions = this.positions;
  37092. }
  37093. if (this.normals) {
  37094. serializationObject.normals = this.normals;
  37095. }
  37096. if (this.tangents) {
  37097. serializationObject.tangents = this.tangents;
  37098. }
  37099. if (this.uvs) {
  37100. serializationObject.uvs = this.uvs;
  37101. }
  37102. if (this.uvs2) {
  37103. serializationObject.uvs2 = this.uvs2;
  37104. }
  37105. if (this.uvs3) {
  37106. serializationObject.uvs3 = this.uvs3;
  37107. }
  37108. if (this.uvs4) {
  37109. serializationObject.uvs4 = this.uvs4;
  37110. }
  37111. if (this.uvs5) {
  37112. serializationObject.uvs5 = this.uvs5;
  37113. }
  37114. if (this.uvs6) {
  37115. serializationObject.uvs6 = this.uvs6;
  37116. }
  37117. if (this.colors) {
  37118. serializationObject.colors = this.colors;
  37119. }
  37120. if (this.matricesIndices) {
  37121. serializationObject.matricesIndices = this.matricesIndices;
  37122. serializationObject.matricesIndices._isExpanded = true;
  37123. }
  37124. if (this.matricesWeights) {
  37125. serializationObject.matricesWeights = this.matricesWeights;
  37126. }
  37127. if (this.matricesIndicesExtra) {
  37128. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37129. serializationObject.matricesIndicesExtra._isExpanded = true;
  37130. }
  37131. if (this.matricesWeightsExtra) {
  37132. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37133. }
  37134. serializationObject.indices = this.indices;
  37135. return serializationObject;
  37136. };
  37137. // Statics
  37138. /**
  37139. * Returns the object VertexData associated to the passed mesh.
  37140. */
  37141. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  37142. return VertexData._ExtractFrom(mesh, copyWhenShared);
  37143. };
  37144. /**
  37145. * Returns the object VertexData associated to the passed geometry.
  37146. */
  37147. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  37148. return VertexData._ExtractFrom(geometry, copyWhenShared);
  37149. };
  37150. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  37151. var result = new VertexData();
  37152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37153. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  37154. }
  37155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37156. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  37157. }
  37158. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37159. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  37160. }
  37161. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37162. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  37163. }
  37164. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37165. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  37166. }
  37167. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37168. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  37169. }
  37170. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37171. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  37172. }
  37173. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37174. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  37175. }
  37176. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37177. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  37178. }
  37179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37180. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  37181. }
  37182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37183. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  37184. }
  37185. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37186. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  37187. }
  37188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37189. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  37190. }
  37191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37192. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  37193. }
  37194. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37195. return result;
  37196. };
  37197. /**
  37198. * Creates the vertexData of the Ribbon.
  37199. */
  37200. VertexData.CreateRibbon = function (options) {
  37201. var pathArray = options.pathArray;
  37202. var closeArray = options.closeArray || false;
  37203. var closePath = options.closePath || false;
  37204. var invertUV = options.invertUV || false;
  37205. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37206. var offset = options.offset || defaultOffset;
  37207. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37209. var customUV = options.uvs;
  37210. var customColors = options.colors;
  37211. var positions = [];
  37212. var indices = [];
  37213. var normals = [];
  37214. var uvs = [];
  37215. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37216. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37217. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37218. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37219. var minlg; // minimal length among all paths from pathArray
  37220. var lg = []; // array of path lengths : nb of vertex per path
  37221. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37222. var p; // path iterator
  37223. var i; // point iterator
  37224. var j; // point iterator
  37225. // if single path in pathArray
  37226. if (pathArray.length < 2) {
  37227. var ar1 = [];
  37228. var ar2 = [];
  37229. for (i = 0; i < pathArray[0].length - offset; i++) {
  37230. ar1.push(pathArray[0][i]);
  37231. ar2.push(pathArray[0][i + offset]);
  37232. }
  37233. pathArray = [ar1, ar2];
  37234. }
  37235. // positions and horizontal distances (u)
  37236. var idc = 0;
  37237. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37238. var path;
  37239. var l;
  37240. minlg = pathArray[0].length;
  37241. var vectlg;
  37242. var dist;
  37243. for (p = 0; p < pathArray.length; p++) {
  37244. uTotalDistance[p] = 0;
  37245. us[p] = [0];
  37246. path = pathArray[p];
  37247. l = path.length;
  37248. minlg = (minlg < l) ? minlg : l;
  37249. j = 0;
  37250. while (j < l) {
  37251. positions.push(path[j].x, path[j].y, path[j].z);
  37252. if (j > 0) {
  37253. vectlg = path[j].subtract(path[j - 1]).length();
  37254. dist = vectlg + uTotalDistance[p];
  37255. us[p].push(dist);
  37256. uTotalDistance[p] = dist;
  37257. }
  37258. j++;
  37259. }
  37260. if (closePath) {
  37261. j--;
  37262. positions.push(path[0].x, path[0].y, path[0].z);
  37263. vectlg = path[j].subtract(path[0]).length();
  37264. dist = vectlg + uTotalDistance[p];
  37265. us[p].push(dist);
  37266. uTotalDistance[p] = dist;
  37267. }
  37268. lg[p] = l + closePathCorr;
  37269. idx[p] = idc;
  37270. idc += (l + closePathCorr);
  37271. }
  37272. // vertical distances (v)
  37273. var path1;
  37274. var path2;
  37275. var vertex1;
  37276. var vertex2;
  37277. for (i = 0; i < minlg + closePathCorr; i++) {
  37278. vTotalDistance[i] = 0;
  37279. vs[i] = [0];
  37280. for (p = 0; p < pathArray.length - 1; p++) {
  37281. path1 = pathArray[p];
  37282. path2 = pathArray[p + 1];
  37283. if (i === minlg) {
  37284. vertex1 = path1[0];
  37285. vertex2 = path2[0];
  37286. }
  37287. else {
  37288. vertex1 = path1[i];
  37289. vertex2 = path2[i];
  37290. }
  37291. vectlg = vertex2.subtract(vertex1).length();
  37292. dist = vectlg + vTotalDistance[i];
  37293. vs[i].push(dist);
  37294. vTotalDistance[i] = dist;
  37295. }
  37296. if (closeArray) {
  37297. path1 = pathArray[p];
  37298. path2 = pathArray[0];
  37299. if (i === minlg) {
  37300. vertex2 = path2[0];
  37301. }
  37302. vectlg = vertex2.subtract(vertex1).length();
  37303. dist = vectlg + vTotalDistance[i];
  37304. vTotalDistance[i] = dist;
  37305. }
  37306. }
  37307. // uvs
  37308. var u;
  37309. var v;
  37310. if (customUV) {
  37311. for (p = 0; p < customUV.length; p++) {
  37312. uvs.push(customUV[p].x, customUV[p].y);
  37313. }
  37314. }
  37315. else {
  37316. for (p = 0; p < pathArray.length; p++) {
  37317. for (i = 0; i < minlg + closePathCorr; i++) {
  37318. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37319. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37320. if (invertUV) {
  37321. uvs.push(v, u);
  37322. }
  37323. else {
  37324. uvs.push(u, v);
  37325. }
  37326. }
  37327. }
  37328. }
  37329. // indices
  37330. p = 0; // path index
  37331. var pi = 0; // positions array index
  37332. var l1 = lg[p] - 1; // path1 length
  37333. var l2 = lg[p + 1] - 1; // path2 length
  37334. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37335. var shft = idx[1] - idx[0]; // shift
  37336. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37337. while (pi <= min && p < path1nb) {
  37338. // 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
  37339. indices.push(pi, pi + shft, pi + 1);
  37340. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37341. pi += 1;
  37342. if (pi === min) {
  37343. p++;
  37344. if (p === lg.length - 1) {
  37345. shft = idx[0] - idx[p];
  37346. l1 = lg[p] - 1;
  37347. l2 = lg[0] - 1;
  37348. }
  37349. else {
  37350. shft = idx[p + 1] - idx[p];
  37351. l1 = lg[p] - 1;
  37352. l2 = lg[p + 1] - 1;
  37353. }
  37354. pi = idx[p];
  37355. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37356. }
  37357. }
  37358. // normals
  37359. VertexData.ComputeNormals(positions, indices, normals);
  37360. if (closePath) {
  37361. var indexFirst = 0;
  37362. var indexLast = 0;
  37363. for (p = 0; p < pathArray.length; p++) {
  37364. indexFirst = idx[p] * 3;
  37365. if (p + 1 < pathArray.length) {
  37366. indexLast = (idx[p + 1] - 1) * 3;
  37367. }
  37368. else {
  37369. indexLast = normals.length - 3;
  37370. }
  37371. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37372. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37373. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37374. normals[indexLast] = normals[indexFirst];
  37375. normals[indexLast + 1] = normals[indexFirst + 1];
  37376. normals[indexLast + 2] = normals[indexFirst + 2];
  37377. }
  37378. }
  37379. // sides
  37380. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37381. // Colors
  37382. if (customColors) {
  37383. var colors = new Float32Array(customColors.length * 4);
  37384. for (var c = 0; c < customColors.length; c++) {
  37385. colors[c * 4] = customColors[c].r;
  37386. colors[c * 4 + 1] = customColors[c].g;
  37387. colors[c * 4 + 2] = customColors[c].b;
  37388. colors[c * 4 + 3] = customColors[c].a;
  37389. }
  37390. }
  37391. // Result
  37392. var vertexData = new VertexData();
  37393. var positions32 = new Float32Array(positions);
  37394. var normals32 = new Float32Array(normals);
  37395. var uvs32 = new Float32Array(uvs);
  37396. vertexData.indices = indices;
  37397. vertexData.positions = positions32;
  37398. vertexData.normals = normals32;
  37399. vertexData.uvs = uvs32;
  37400. if (customColors) {
  37401. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37402. }
  37403. if (closePath) {
  37404. vertexData._idx = idx;
  37405. }
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData of the Box.
  37410. */
  37411. VertexData.CreateBox = function (options) {
  37412. var normalsSource = [
  37413. new BABYLON.Vector3(0, 0, 1),
  37414. new BABYLON.Vector3(0, 0, -1),
  37415. new BABYLON.Vector3(1, 0, 0),
  37416. new BABYLON.Vector3(-1, 0, 0),
  37417. new BABYLON.Vector3(0, 1, 0),
  37418. new BABYLON.Vector3(0, -1, 0)
  37419. ];
  37420. var indices = [];
  37421. var positions = [];
  37422. var normals = [];
  37423. var uvs = [];
  37424. var width = options.width || options.size || 1;
  37425. var height = options.height || options.size || 1;
  37426. var depth = options.depth || options.size || 1;
  37427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37428. var faceUV = options.faceUV || new Array(6);
  37429. var faceColors = options.faceColors;
  37430. var colors = [];
  37431. // default face colors and UV if undefined
  37432. for (var f = 0; f < 6; f++) {
  37433. if (faceUV[f] === undefined) {
  37434. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37435. }
  37436. if (faceColors && faceColors[f] === undefined) {
  37437. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37438. }
  37439. }
  37440. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37441. // Create each face in turn.
  37442. for (var index = 0; index < normalsSource.length; index++) {
  37443. var normal = normalsSource[index];
  37444. // Get two vectors perpendicular to the face normal and to each other.
  37445. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37446. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37447. // Six indices (two triangles) per face.
  37448. var verticesLength = positions.length / 3;
  37449. indices.push(verticesLength);
  37450. indices.push(verticesLength + 1);
  37451. indices.push(verticesLength + 2);
  37452. indices.push(verticesLength);
  37453. indices.push(verticesLength + 2);
  37454. indices.push(verticesLength + 3);
  37455. // Four vertices per face.
  37456. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37457. positions.push(vertex.x, vertex.y, vertex.z);
  37458. normals.push(normal.x, normal.y, normal.z);
  37459. uvs.push(faceUV[index].z, faceUV[index].w);
  37460. if (faceColors) {
  37461. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37462. }
  37463. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37464. positions.push(vertex.x, vertex.y, vertex.z);
  37465. normals.push(normal.x, normal.y, normal.z);
  37466. uvs.push(faceUV[index].x, faceUV[index].w);
  37467. if (faceColors) {
  37468. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37469. }
  37470. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37471. positions.push(vertex.x, vertex.y, vertex.z);
  37472. normals.push(normal.x, normal.y, normal.z);
  37473. uvs.push(faceUV[index].x, faceUV[index].y);
  37474. if (faceColors) {
  37475. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37476. }
  37477. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37478. positions.push(vertex.x, vertex.y, vertex.z);
  37479. normals.push(normal.x, normal.y, normal.z);
  37480. uvs.push(faceUV[index].z, faceUV[index].y);
  37481. if (faceColors) {
  37482. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37483. }
  37484. }
  37485. // sides
  37486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37487. // Result
  37488. var vertexData = new VertexData();
  37489. vertexData.indices = indices;
  37490. vertexData.positions = positions;
  37491. vertexData.normals = normals;
  37492. vertexData.uvs = uvs;
  37493. if (faceColors) {
  37494. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37495. vertexData.colors = totalColors;
  37496. }
  37497. return vertexData;
  37498. };
  37499. /**
  37500. * Creates the VertexData of the Sphere.
  37501. */
  37502. VertexData.CreateSphere = function (options) {
  37503. var segments = options.segments || 32;
  37504. var diameterX = options.diameterX || options.diameter || 1;
  37505. var diameterY = options.diameterY || options.diameter || 1;
  37506. var diameterZ = options.diameterZ || options.diameter || 1;
  37507. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37508. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37510. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37511. var totalZRotationSteps = 2 + segments;
  37512. var totalYRotationSteps = 2 * totalZRotationSteps;
  37513. var indices = [];
  37514. var positions = [];
  37515. var normals = [];
  37516. var uvs = [];
  37517. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37518. var normalizedZ = zRotationStep / totalZRotationSteps;
  37519. var angleZ = normalizedZ * Math.PI * slice;
  37520. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37521. var normalizedY = yRotationStep / totalYRotationSteps;
  37522. var angleY = normalizedY * Math.PI * 2 * arc;
  37523. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37524. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37525. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37526. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37527. var vertex = complete.multiply(radius);
  37528. var normal = complete.divide(radius).normalize();
  37529. positions.push(vertex.x, vertex.y, vertex.z);
  37530. normals.push(normal.x, normal.y, normal.z);
  37531. uvs.push(normalizedY, normalizedZ);
  37532. }
  37533. if (zRotationStep > 0) {
  37534. var verticesCount = positions.length / 3;
  37535. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37536. indices.push((firstIndex));
  37537. indices.push((firstIndex + 1));
  37538. indices.push(firstIndex + totalYRotationSteps + 1);
  37539. indices.push((firstIndex + totalYRotationSteps + 1));
  37540. indices.push((firstIndex + 1));
  37541. indices.push((firstIndex + totalYRotationSteps + 2));
  37542. }
  37543. }
  37544. }
  37545. // Sides
  37546. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37547. // Result
  37548. var vertexData = new VertexData();
  37549. vertexData.indices = indices;
  37550. vertexData.positions = positions;
  37551. vertexData.normals = normals;
  37552. vertexData.uvs = uvs;
  37553. return vertexData;
  37554. };
  37555. /**
  37556. * Creates the VertexData of the Cylinder or Cone.
  37557. */
  37558. VertexData.CreateCylinder = function (options) {
  37559. var height = options.height || 2;
  37560. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37561. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37562. var tessellation = options.tessellation || 24;
  37563. var subdivisions = options.subdivisions || 1;
  37564. var hasRings = options.hasRings;
  37565. var enclose = options.enclose;
  37566. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37567. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37568. var faceUV = options.faceUV || new Array(3);
  37569. var faceColors = options.faceColors;
  37570. // default face colors and UV if undefined
  37571. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37572. var ringNb = (hasRings) ? subdivisions : 1;
  37573. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37574. var f;
  37575. for (f = 0; f < surfaceNb; f++) {
  37576. if (faceColors && faceColors[f] === undefined) {
  37577. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37578. }
  37579. }
  37580. for (f = 0; f < surfaceNb; f++) {
  37581. if (faceUV && faceUV[f] === undefined) {
  37582. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37583. }
  37584. }
  37585. var indices = [];
  37586. var positions = [];
  37587. var normals = [];
  37588. var uvs = [];
  37589. var colors = [];
  37590. var angle_step = Math.PI * 2 * arc / tessellation;
  37591. var angle;
  37592. var h;
  37593. var radius;
  37594. var tan = (diameterBottom - diameterTop) / 2 / height;
  37595. var ringVertex = BABYLON.Vector3.Zero();
  37596. var ringNormal = BABYLON.Vector3.Zero();
  37597. var ringFirstVertex = BABYLON.Vector3.Zero();
  37598. var ringFirstNormal = BABYLON.Vector3.Zero();
  37599. var quadNormal = BABYLON.Vector3.Zero();
  37600. var Y = BABYLON.Axis.Y;
  37601. // positions, normals, uvs
  37602. var i;
  37603. var j;
  37604. var r;
  37605. var ringIdx = 1;
  37606. var s = 1; // surface index
  37607. var cs = 0;
  37608. var v = 0;
  37609. for (i = 0; i <= subdivisions; i++) {
  37610. h = i / subdivisions;
  37611. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37612. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37613. for (r = 0; r < ringIdx; r++) {
  37614. if (hasRings) {
  37615. s += r;
  37616. }
  37617. if (enclose) {
  37618. s += 2 * r;
  37619. }
  37620. for (j = 0; j <= tessellation; j++) {
  37621. angle = j * angle_step;
  37622. // position
  37623. ringVertex.x = Math.cos(-angle) * radius;
  37624. ringVertex.y = -height / 2 + h * height;
  37625. ringVertex.z = Math.sin(-angle) * radius;
  37626. // normal
  37627. if (diameterTop === 0 && i === subdivisions) {
  37628. // if no top cap, reuse former normals
  37629. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37630. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37631. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37632. }
  37633. else {
  37634. ringNormal.x = ringVertex.x;
  37635. ringNormal.z = ringVertex.z;
  37636. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37637. ringNormal.normalize();
  37638. }
  37639. // keep first ring vertex values for enclose
  37640. if (j === 0) {
  37641. ringFirstVertex.copyFrom(ringVertex);
  37642. ringFirstNormal.copyFrom(ringNormal);
  37643. }
  37644. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37645. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37646. if (hasRings) {
  37647. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37648. }
  37649. else {
  37650. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37651. }
  37652. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37653. if (faceColors) {
  37654. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37655. }
  37656. }
  37657. // if enclose, add four vertices and their dedicated normals
  37658. if (arc !== 1 && enclose) {
  37659. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37660. positions.push(0, ringVertex.y, 0);
  37661. positions.push(0, ringVertex.y, 0);
  37662. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37663. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37664. quadNormal.normalize();
  37665. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37666. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37667. quadNormal.normalize();
  37668. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37669. if (hasRings) {
  37670. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37671. }
  37672. else {
  37673. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37674. }
  37675. uvs.push(faceUV[s + 1].x, v);
  37676. uvs.push(faceUV[s + 1].z, v);
  37677. if (hasRings) {
  37678. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37679. }
  37680. else {
  37681. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37682. }
  37683. uvs.push(faceUV[s + 2].x, v);
  37684. uvs.push(faceUV[s + 2].z, v);
  37685. if (faceColors) {
  37686. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37687. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37688. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37689. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37690. }
  37691. }
  37692. if (cs !== s) {
  37693. cs = s;
  37694. }
  37695. }
  37696. }
  37697. // indices
  37698. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37699. var s;
  37700. i = 0;
  37701. for (s = 0; s < subdivisions; s++) {
  37702. for (j = 0; j < tessellation; j++) {
  37703. var i0 = i * (e + 1) + j;
  37704. var i1 = (i + 1) * (e + 1) + j;
  37705. var i2 = i * (e + 1) + (j + 1);
  37706. var i3 = (i + 1) * (e + 1) + (j + 1);
  37707. indices.push(i0, i1, i2);
  37708. indices.push(i3, i2, i1);
  37709. }
  37710. if (arc !== 1 && enclose) {
  37711. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37712. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37713. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37714. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37715. }
  37716. i = (hasRings) ? (i + 2) : (i + 1);
  37717. }
  37718. // Caps
  37719. var createCylinderCap = function (isTop) {
  37720. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37721. if (radius === 0) {
  37722. return;
  37723. }
  37724. // Cap positions, normals & uvs
  37725. var angle;
  37726. var circleVector;
  37727. var i;
  37728. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37729. var c;
  37730. if (faceColors) {
  37731. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37732. }
  37733. // cap center
  37734. var vbase = positions.length / 3;
  37735. var offset = isTop ? height / 2 : -height / 2;
  37736. var center = new BABYLON.Vector3(0, offset, 0);
  37737. positions.push(center.x, center.y, center.z);
  37738. normals.push(0, isTop ? 1 : -1, 0);
  37739. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37740. if (faceColors) {
  37741. colors.push(c.r, c.g, c.b, c.a);
  37742. }
  37743. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37744. for (i = 0; i <= tessellation; i++) {
  37745. angle = Math.PI * 2 * i * arc / tessellation;
  37746. var cos = Math.cos(-angle);
  37747. var sin = Math.sin(-angle);
  37748. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37749. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37750. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37751. normals.push(0, isTop ? 1 : -1, 0);
  37752. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37753. if (faceColors) {
  37754. colors.push(c.r, c.g, c.b, c.a);
  37755. }
  37756. }
  37757. // Cap indices
  37758. for (i = 0; i < tessellation; i++) {
  37759. if (!isTop) {
  37760. indices.push(vbase);
  37761. indices.push(vbase + (i + 1));
  37762. indices.push(vbase + (i + 2));
  37763. }
  37764. else {
  37765. indices.push(vbase);
  37766. indices.push(vbase + (i + 2));
  37767. indices.push(vbase + (i + 1));
  37768. }
  37769. }
  37770. };
  37771. // add caps to geometry
  37772. createCylinderCap(false);
  37773. createCylinderCap(true);
  37774. // Sides
  37775. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37776. var vertexData = new VertexData();
  37777. vertexData.indices = indices;
  37778. vertexData.positions = positions;
  37779. vertexData.normals = normals;
  37780. vertexData.uvs = uvs;
  37781. if (faceColors) {
  37782. vertexData.colors = colors;
  37783. }
  37784. return vertexData;
  37785. };
  37786. /**
  37787. * Creates the VertexData of the Torus.
  37788. */
  37789. VertexData.CreateTorus = function (options) {
  37790. var indices = [];
  37791. var positions = [];
  37792. var normals = [];
  37793. var uvs = [];
  37794. var diameter = options.diameter || 1;
  37795. var thickness = options.thickness || 0.5;
  37796. var tessellation = options.tessellation || 16;
  37797. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37798. var stride = tessellation + 1;
  37799. for (var i = 0; i <= tessellation; i++) {
  37800. var u = i / tessellation;
  37801. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37802. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37803. for (var j = 0; j <= tessellation; j++) {
  37804. var v = 1 - j / tessellation;
  37805. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37806. var dx = Math.cos(innerAngle);
  37807. var dy = Math.sin(innerAngle);
  37808. // Create a vertex.
  37809. var normal = new BABYLON.Vector3(dx, dy, 0);
  37810. var position = normal.scale(thickness / 2);
  37811. var textureCoordinate = new BABYLON.Vector2(u, v);
  37812. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37813. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37814. positions.push(position.x, position.y, position.z);
  37815. normals.push(normal.x, normal.y, normal.z);
  37816. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37817. // And create indices for two triangles.
  37818. var nextI = (i + 1) % stride;
  37819. var nextJ = (j + 1) % stride;
  37820. indices.push(i * stride + j);
  37821. indices.push(i * stride + nextJ);
  37822. indices.push(nextI * stride + j);
  37823. indices.push(i * stride + nextJ);
  37824. indices.push(nextI * stride + nextJ);
  37825. indices.push(nextI * stride + j);
  37826. }
  37827. }
  37828. // Sides
  37829. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37830. // Result
  37831. var vertexData = new VertexData();
  37832. vertexData.indices = indices;
  37833. vertexData.positions = positions;
  37834. vertexData.normals = normals;
  37835. vertexData.uvs = uvs;
  37836. return vertexData;
  37837. };
  37838. /**
  37839. * Creates the VertexData of the LineSystem.
  37840. */
  37841. VertexData.CreateLineSystem = function (options) {
  37842. var indices = [];
  37843. var positions = [];
  37844. var lines = options.lines;
  37845. var idx = 0;
  37846. for (var l = 0; l < lines.length; l++) {
  37847. var points = lines[l];
  37848. for (var index = 0; index < points.length; index++) {
  37849. positions.push(points[index].x, points[index].y, points[index].z);
  37850. if (index > 0) {
  37851. indices.push(idx - 1);
  37852. indices.push(idx);
  37853. }
  37854. idx++;
  37855. }
  37856. }
  37857. var vertexData = new VertexData();
  37858. vertexData.indices = indices;
  37859. vertexData.positions = positions;
  37860. return vertexData;
  37861. };
  37862. /**
  37863. * Create the VertexData of the DashedLines.
  37864. */
  37865. VertexData.CreateDashedLines = function (options) {
  37866. var dashSize = options.dashSize || 3;
  37867. var gapSize = options.gapSize || 1;
  37868. var dashNb = options.dashNb || 200;
  37869. var points = options.points;
  37870. var positions = new Array();
  37871. var indices = new Array();
  37872. var curvect = BABYLON.Vector3.Zero();
  37873. var lg = 0;
  37874. var nb = 0;
  37875. var shft = 0;
  37876. var dashshft = 0;
  37877. var curshft = 0;
  37878. var idx = 0;
  37879. var i = 0;
  37880. for (i = 0; i < points.length - 1; i++) {
  37881. points[i + 1].subtractToRef(points[i], curvect);
  37882. lg += curvect.length();
  37883. }
  37884. shft = lg / dashNb;
  37885. dashshft = dashSize * shft / (dashSize + gapSize);
  37886. for (i = 0; i < points.length - 1; i++) {
  37887. points[i + 1].subtractToRef(points[i], curvect);
  37888. nb = Math.floor(curvect.length() / shft);
  37889. curvect.normalize();
  37890. for (var j = 0; j < nb; j++) {
  37891. curshft = shft * j;
  37892. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37893. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37894. indices.push(idx, idx + 1);
  37895. idx += 2;
  37896. }
  37897. }
  37898. // Result
  37899. var vertexData = new VertexData();
  37900. vertexData.positions = positions;
  37901. vertexData.indices = indices;
  37902. return vertexData;
  37903. };
  37904. /**
  37905. * Creates the VertexData of the Ground.
  37906. */
  37907. VertexData.CreateGround = function (options) {
  37908. var indices = [];
  37909. var positions = [];
  37910. var normals = [];
  37911. var uvs = [];
  37912. var row, col;
  37913. var width = options.width || 1;
  37914. var height = options.height || 1;
  37915. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37916. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37917. for (row = 0; row <= subdivisionsY; row++) {
  37918. for (col = 0; col <= subdivisionsX; col++) {
  37919. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37920. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37921. positions.push(position.x, position.y, position.z);
  37922. normals.push(normal.x, normal.y, normal.z);
  37923. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37924. }
  37925. }
  37926. for (row = 0; row < subdivisionsY; row++) {
  37927. for (col = 0; col < subdivisionsX; col++) {
  37928. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37929. indices.push(col + 1 + row * (subdivisionsX + 1));
  37930. indices.push(col + row * (subdivisionsX + 1));
  37931. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37932. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37933. indices.push(col + row * (subdivisionsX + 1));
  37934. }
  37935. }
  37936. // Result
  37937. var vertexData = new VertexData();
  37938. vertexData.indices = indices;
  37939. vertexData.positions = positions;
  37940. vertexData.normals = normals;
  37941. vertexData.uvs = uvs;
  37942. return vertexData;
  37943. };
  37944. /**
  37945. * Creates the VertexData of the TiledGround.
  37946. */
  37947. VertexData.CreateTiledGround = function (options) {
  37948. var xmin = options.xmin || -1.0;
  37949. var zmin = options.zmin || -1.0;
  37950. var xmax = options.xmax || 1.0;
  37951. var zmax = options.zmax || 1.0;
  37952. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37953. var precision = options.precision || { w: 1, h: 1 };
  37954. var indices = [];
  37955. var positions = [];
  37956. var normals = [];
  37957. var uvs = [];
  37958. var row, col, tileRow, tileCol;
  37959. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37960. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37961. precision.w = (precision.w < 1) ? 1 : precision.w;
  37962. precision.h = (precision.h < 1) ? 1 : precision.h;
  37963. var tileSize = {
  37964. 'w': (xmax - xmin) / subdivisions.w,
  37965. 'h': (zmax - zmin) / subdivisions.h
  37966. };
  37967. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37968. // Indices
  37969. var base = positions.length / 3;
  37970. var rowLength = precision.w + 1;
  37971. for (row = 0; row < precision.h; row++) {
  37972. for (col = 0; col < precision.w; col++) {
  37973. var square = [
  37974. base + col + row * rowLength,
  37975. base + (col + 1) + row * rowLength,
  37976. base + (col + 1) + (row + 1) * rowLength,
  37977. base + col + (row + 1) * rowLength
  37978. ];
  37979. indices.push(square[1]);
  37980. indices.push(square[2]);
  37981. indices.push(square[3]);
  37982. indices.push(square[0]);
  37983. indices.push(square[1]);
  37984. indices.push(square[3]);
  37985. }
  37986. }
  37987. // Position, normals and uvs
  37988. var position = BABYLON.Vector3.Zero();
  37989. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37990. for (row = 0; row <= precision.h; row++) {
  37991. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37992. for (col = 0; col <= precision.w; col++) {
  37993. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37994. position.y = 0;
  37995. positions.push(position.x, position.y, position.z);
  37996. normals.push(normal.x, normal.y, normal.z);
  37997. uvs.push(col / precision.w, row / precision.h);
  37998. }
  37999. }
  38000. }
  38001. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38002. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38003. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38004. }
  38005. }
  38006. // Result
  38007. var vertexData = new VertexData();
  38008. vertexData.indices = indices;
  38009. vertexData.positions = positions;
  38010. vertexData.normals = normals;
  38011. vertexData.uvs = uvs;
  38012. return vertexData;
  38013. };
  38014. /**
  38015. * Creates the VertexData of the Ground designed from a heightmap.
  38016. */
  38017. VertexData.CreateGroundFromHeightMap = function (options) {
  38018. var indices = [];
  38019. var positions = [];
  38020. var normals = [];
  38021. var uvs = [];
  38022. var row, col;
  38023. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38024. // Vertices
  38025. for (row = 0; row <= options.subdivisions; row++) {
  38026. for (col = 0; col <= options.subdivisions; col++) {
  38027. 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));
  38028. // Compute height
  38029. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38030. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38031. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38032. var r = options.buffer[pos] / 255.0;
  38033. var g = options.buffer[pos + 1] / 255.0;
  38034. var b = options.buffer[pos + 2] / 255.0;
  38035. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38036. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38037. // Add vertex
  38038. positions.push(position.x, position.y, position.z);
  38039. normals.push(0, 0, 0);
  38040. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38041. }
  38042. }
  38043. // Indices
  38044. for (row = 0; row < options.subdivisions; row++) {
  38045. for (col = 0; col < options.subdivisions; col++) {
  38046. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38047. indices.push(col + 1 + row * (options.subdivisions + 1));
  38048. indices.push(col + row * (options.subdivisions + 1));
  38049. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38050. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38051. indices.push(col + row * (options.subdivisions + 1));
  38052. }
  38053. }
  38054. // Normals
  38055. VertexData.ComputeNormals(positions, indices, normals);
  38056. // Result
  38057. var vertexData = new VertexData();
  38058. vertexData.indices = indices;
  38059. vertexData.positions = positions;
  38060. vertexData.normals = normals;
  38061. vertexData.uvs = uvs;
  38062. return vertexData;
  38063. };
  38064. /**
  38065. * Creates the VertexData of the Plane.
  38066. */
  38067. VertexData.CreatePlane = function (options) {
  38068. var indices = [];
  38069. var positions = [];
  38070. var normals = [];
  38071. var uvs = [];
  38072. var width = options.width || options.size || 1;
  38073. var height = options.height || options.size || 1;
  38074. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38075. // Vertices
  38076. var halfWidth = width / 2.0;
  38077. var halfHeight = height / 2.0;
  38078. positions.push(-halfWidth, -halfHeight, 0);
  38079. normals.push(0, 0, -1.0);
  38080. uvs.push(0.0, 0.0);
  38081. positions.push(halfWidth, -halfHeight, 0);
  38082. normals.push(0, 0, -1.0);
  38083. uvs.push(1.0, 0.0);
  38084. positions.push(halfWidth, halfHeight, 0);
  38085. normals.push(0, 0, -1.0);
  38086. uvs.push(1.0, 1.0);
  38087. positions.push(-halfWidth, halfHeight, 0);
  38088. normals.push(0, 0, -1.0);
  38089. uvs.push(0.0, 1.0);
  38090. // Indices
  38091. indices.push(0);
  38092. indices.push(1);
  38093. indices.push(2);
  38094. indices.push(0);
  38095. indices.push(2);
  38096. indices.push(3);
  38097. // Sides
  38098. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38099. // Result
  38100. var vertexData = new VertexData();
  38101. vertexData.indices = indices;
  38102. vertexData.positions = positions;
  38103. vertexData.normals = normals;
  38104. vertexData.uvs = uvs;
  38105. return vertexData;
  38106. };
  38107. /**
  38108. * Creates the VertexData of the Disc or regular Polygon.
  38109. */
  38110. VertexData.CreateDisc = function (options) {
  38111. var positions = [];
  38112. var indices = [];
  38113. var normals = [];
  38114. var uvs = [];
  38115. var radius = options.radius || 0.5;
  38116. var tessellation = options.tessellation || 64;
  38117. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38118. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38119. // positions and uvs
  38120. positions.push(0, 0, 0); // disc center first
  38121. uvs.push(0.5, 0.5);
  38122. var theta = Math.PI * 2 * arc;
  38123. var step = theta / tessellation;
  38124. for (var a = 0; a < theta; a += step) {
  38125. var x = Math.cos(a);
  38126. var y = Math.sin(a);
  38127. var u = (x + 1) / 2;
  38128. var v = (1 - y) / 2;
  38129. positions.push(radius * x, radius * y, 0);
  38130. uvs.push(u, v);
  38131. }
  38132. if (arc === 1) {
  38133. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38134. uvs.push(uvs[2], uvs[3]);
  38135. }
  38136. //indices
  38137. var vertexNb = positions.length / 3;
  38138. for (var i = 1; i < vertexNb - 1; i++) {
  38139. indices.push(i + 1, 0, i);
  38140. }
  38141. // result
  38142. VertexData.ComputeNormals(positions, indices, normals);
  38143. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38144. var vertexData = new VertexData();
  38145. vertexData.indices = indices;
  38146. vertexData.positions = positions;
  38147. vertexData.normals = normals;
  38148. vertexData.uvs = uvs;
  38149. return vertexData;
  38150. };
  38151. /**
  38152. * Creates the VertexData of the IcoSphere.
  38153. */
  38154. VertexData.CreateIcoSphere = function (options) {
  38155. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38156. var radius = options.radius || 1;
  38157. var flat = (options.flat === undefined) ? true : options.flat;
  38158. var subdivisions = options.subdivisions || 4;
  38159. var radiusX = options.radiusX || radius;
  38160. var radiusY = options.radiusY || radius;
  38161. var radiusZ = options.radiusZ || radius;
  38162. var t = (1 + Math.sqrt(5)) / 2;
  38163. // 12 vertex x,y,z
  38164. var ico_vertices = [
  38165. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38166. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38167. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38168. ];
  38169. // index of 3 vertex makes a face of icopshere
  38170. var ico_indices = [
  38171. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38172. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38173. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38174. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38175. ];
  38176. // vertex for uv have aliased position, not for UV
  38177. var vertices_unalias_id = [
  38178. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38179. // vertex alias
  38180. 0,
  38181. 2,
  38182. 3,
  38183. 3,
  38184. 3,
  38185. 4,
  38186. 7,
  38187. 8,
  38188. 9,
  38189. 9,
  38190. 10,
  38191. 11 // 23: B + 12
  38192. ];
  38193. // uv as integer step (not pixels !)
  38194. var ico_vertexuv = [
  38195. 5, 1, 3, 1, 6, 4, 0, 0,
  38196. 5, 3, 4, 2, 2, 2, 4, 0,
  38197. 2, 0, 1, 1, 6, 0, 6, 2,
  38198. // vertex alias (for same vertex on different faces)
  38199. 0, 4,
  38200. 3, 3,
  38201. 4, 4,
  38202. 3, 1,
  38203. 4, 2,
  38204. 4, 4,
  38205. 0, 2,
  38206. 1, 1,
  38207. 2, 2,
  38208. 3, 3,
  38209. 1, 3,
  38210. 2, 4 // 23: B + 12
  38211. ];
  38212. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38213. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38214. // First island of uv mapping
  38215. // v = 4h 3+ 2
  38216. // v = 3h 9+ 4
  38217. // v = 2h 9+ 5 B
  38218. // v = 1h 9 1 0
  38219. // v = 0h 3 8 7 A
  38220. // u = 0 1 2 3 4 5 6 *a
  38221. // Second island of uv mapping
  38222. // v = 4h 0+ B+ 4+
  38223. // v = 3h A+ 2+
  38224. // v = 2h 7+ 6 3+
  38225. // v = 1h 8+ 3+
  38226. // v = 0h
  38227. // u = 0 1 2 3 4 5 6 *a
  38228. // Face layout on texture UV mapping
  38229. // ============
  38230. // \ 4 /\ 16 / ======
  38231. // \ / \ / /\ 11 /
  38232. // \/ 7 \/ / \ /
  38233. // ======= / 10 \/
  38234. // /\ 17 /\ =======
  38235. // / \ / \ \ 15 /\
  38236. // / 8 \/ 12 \ \ / \
  38237. // ============ \/ 6 \
  38238. // \ 18 /\ ============
  38239. // \ / \ \ 5 /\ 0 /
  38240. // \/ 13 \ \ / \ /
  38241. // ======= \/ 1 \/
  38242. // =============
  38243. // /\ 19 /\ 2 /\
  38244. // / \ / \ / \
  38245. // / 14 \/ 9 \/ 3 \
  38246. // ===================
  38247. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38248. var ustep = 138 / 1024;
  38249. var vstep = 239 / 1024;
  38250. var uoffset = 60 / 1024;
  38251. var voffset = 26 / 1024;
  38252. // Second island should have margin, not to touch the first island
  38253. // avoid any borderline artefact in pixel rounding
  38254. var island_u_offset = -40 / 1024;
  38255. var island_v_offset = +20 / 1024;
  38256. // face is either island 0 or 1 :
  38257. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38258. var island = [
  38259. 0, 0, 0, 0, 1,
  38260. 0, 0, 1, 1, 0,
  38261. 0, 0, 1, 1, 0,
  38262. 0, 1, 1, 1, 0 // 15 - 19
  38263. ];
  38264. var indices = [];
  38265. var positions = [];
  38266. var normals = [];
  38267. var uvs = [];
  38268. var current_indice = 0;
  38269. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38270. var face_vertex_pos = new Array(3);
  38271. var face_vertex_uv = new Array(3);
  38272. var v012;
  38273. for (v012 = 0; v012 < 3; v012++) {
  38274. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38275. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38276. }
  38277. // create all with normals
  38278. for (var face = 0; face < 20; face++) {
  38279. // 3 vertex per face
  38280. for (v012 = 0; v012 < 3; v012++) {
  38281. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38282. var v_id = ico_indices[3 * face + v012];
  38283. // vertex have 3D position (x,y,z)
  38284. 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]);
  38285. // Normalize to get normal, then scale to radius
  38286. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38287. // uv Coordinates from vertex ID
  38288. 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);
  38289. }
  38290. // Subdivide the face (interpolate pos, norm, uv)
  38291. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38292. // - norm is linear interpolation of vertex corner normal
  38293. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38294. // - uv is linear interpolation
  38295. //
  38296. // Topology is as below for sub-divide by 2
  38297. // vertex shown as v0,v1,v2
  38298. // interp index is i1 to progress in range [v0,v1[
  38299. // interp index is i2 to progress in range [v0,v2[
  38300. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38301. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38302. //
  38303. //
  38304. // i2 v2
  38305. // ^ ^
  38306. // / / \
  38307. // / / \
  38308. // / / \
  38309. // / / (0,1) \
  38310. // / #---------\
  38311. // / / \ (0,0)'/ \
  38312. // / / \ / \
  38313. // / / \ / \
  38314. // / / (0,0) \ / (1,0) \
  38315. // / #---------#---------\
  38316. // v0 v1
  38317. //
  38318. // --------------------> i1
  38319. //
  38320. // interp of (i1,i2):
  38321. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38322. // along i1 : lerp(x0,x1, i1/(S-i2))
  38323. //
  38324. // centroid of triangle is needed to get help normal computation
  38325. // (c1,c2) are used for centroid location
  38326. var interp_vertex = function (i1, i2, c1, c2) {
  38327. // vertex is interpolated from
  38328. // - face_vertex_pos[0..2]
  38329. // - face_vertex_uv[0..2]
  38330. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38331. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38332. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38333. pos_interp.normalize();
  38334. var vertex_normal;
  38335. if (flat) {
  38336. // in flat mode, recalculate normal as face centroid normal
  38337. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38338. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38339. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38340. }
  38341. else {
  38342. // in smooth mode, recalculate normal from each single vertex position
  38343. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38344. }
  38345. // Vertex normal need correction due to X,Y,Z radius scaling
  38346. vertex_normal.x /= radiusX;
  38347. vertex_normal.y /= radiusY;
  38348. vertex_normal.z /= radiusZ;
  38349. vertex_normal.normalize();
  38350. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38351. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38352. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38353. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38354. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38355. uvs.push(uv_interp.x, uv_interp.y);
  38356. // push each vertex has member of a face
  38357. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38358. indices.push(current_indice);
  38359. current_indice++;
  38360. };
  38361. for (var i2 = 0; i2 < subdivisions; i2++) {
  38362. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38363. // face : (i1,i2) for /\ :
  38364. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38365. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38366. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38367. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38368. if (i1 + i2 + 1 < subdivisions) {
  38369. // face : (i1,i2)' for \/ :
  38370. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38371. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38372. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38373. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38374. }
  38375. }
  38376. }
  38377. }
  38378. // Sides
  38379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38380. // Result
  38381. var vertexData = new VertexData();
  38382. vertexData.indices = indices;
  38383. vertexData.positions = positions;
  38384. vertexData.normals = normals;
  38385. vertexData.uvs = uvs;
  38386. return vertexData;
  38387. };
  38388. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38389. /**
  38390. * Creates the VertexData of the Polyhedron.
  38391. */
  38392. VertexData.CreatePolyhedron = function (options) {
  38393. // provided polyhedron types :
  38394. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38395. // 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)
  38396. var polyhedra = [];
  38397. 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]] };
  38398. 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]] };
  38399. polyhedra[2] = {
  38400. 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]],
  38401. 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]]
  38402. };
  38403. polyhedra[3] = {
  38404. 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]],
  38405. 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]]
  38406. };
  38407. polyhedra[4] = {
  38408. 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]],
  38409. 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]]
  38410. };
  38411. 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]] };
  38412. 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]] };
  38413. 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]] };
  38414. 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]] };
  38415. 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]] };
  38416. 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]] };
  38417. 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]] };
  38418. 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]] };
  38419. 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]] };
  38420. polyhedra[14] = {
  38421. 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]],
  38422. 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]]
  38423. };
  38424. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38425. var size = options.size;
  38426. var sizeX = options.sizeX || size || 1;
  38427. var sizeY = options.sizeY || size || 1;
  38428. var sizeZ = options.sizeZ || size || 1;
  38429. var data = options.custom || polyhedra[type];
  38430. var nbfaces = data.face.length;
  38431. var faceUV = options.faceUV || new Array(nbfaces);
  38432. var faceColors = options.faceColors;
  38433. var flat = (options.flat === undefined) ? true : options.flat;
  38434. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38435. var positions = [];
  38436. var indices = [];
  38437. var normals = [];
  38438. var uvs = [];
  38439. var colors = [];
  38440. var index = 0;
  38441. var faceIdx = 0; // face cursor in the array "indexes"
  38442. var indexes = [];
  38443. var i = 0;
  38444. var f = 0;
  38445. var u, v, ang, x, y, tmp;
  38446. // default face colors and UV if undefined
  38447. if (flat) {
  38448. for (f = 0; f < nbfaces; f++) {
  38449. if (faceColors && faceColors[f] === undefined) {
  38450. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38451. }
  38452. if (faceUV && faceUV[f] === undefined) {
  38453. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38454. }
  38455. }
  38456. }
  38457. if (!flat) {
  38458. for (i = 0; i < data.vertex.length; i++) {
  38459. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38460. uvs.push(0, 0);
  38461. }
  38462. for (f = 0; f < nbfaces; f++) {
  38463. for (i = 0; i < data.face[f].length - 2; i++) {
  38464. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38465. }
  38466. }
  38467. }
  38468. else {
  38469. for (f = 0; f < nbfaces; f++) {
  38470. var fl = data.face[f].length; // number of vertices of the current face
  38471. ang = 2 * Math.PI / fl;
  38472. x = 0.5 * Math.tan(ang / 2);
  38473. y = 0.5;
  38474. // positions, uvs, colors
  38475. for (i = 0; i < fl; i++) {
  38476. // positions
  38477. 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);
  38478. indexes.push(index);
  38479. index++;
  38480. // uvs
  38481. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38482. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38483. uvs.push(u, v);
  38484. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38485. y = x * Math.sin(ang) + y * Math.cos(ang);
  38486. x = tmp;
  38487. // colors
  38488. if (faceColors) {
  38489. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38490. }
  38491. }
  38492. // indices from indexes
  38493. for (i = 0; i < fl - 2; i++) {
  38494. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38495. }
  38496. faceIdx += fl;
  38497. }
  38498. }
  38499. VertexData.ComputeNormals(positions, indices, normals);
  38500. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38501. var vertexData = new VertexData();
  38502. vertexData.positions = positions;
  38503. vertexData.indices = indices;
  38504. vertexData.normals = normals;
  38505. vertexData.uvs = uvs;
  38506. if (faceColors && flat) {
  38507. vertexData.colors = colors;
  38508. }
  38509. return vertexData;
  38510. };
  38511. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38512. /**
  38513. * Creates the VertexData of the Torus Knot.
  38514. */
  38515. VertexData.CreateTorusKnot = function (options) {
  38516. var indices = [];
  38517. var positions = [];
  38518. var normals = [];
  38519. var uvs = [];
  38520. var radius = options.radius || 2;
  38521. var tube = options.tube || 0.5;
  38522. var radialSegments = options.radialSegments || 32;
  38523. var tubularSegments = options.tubularSegments || 32;
  38524. var p = options.p || 2;
  38525. var q = options.q || 3;
  38526. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38527. // Helper
  38528. var getPos = function (angle) {
  38529. var cu = Math.cos(angle);
  38530. var su = Math.sin(angle);
  38531. var quOverP = q / p * angle;
  38532. var cs = Math.cos(quOverP);
  38533. var tx = radius * (2 + cs) * 0.5 * cu;
  38534. var ty = radius * (2 + cs) * su * 0.5;
  38535. var tz = radius * Math.sin(quOverP) * 0.5;
  38536. return new BABYLON.Vector3(tx, ty, tz);
  38537. };
  38538. // Vertices
  38539. var i;
  38540. var j;
  38541. for (i = 0; i <= radialSegments; i++) {
  38542. var modI = i % radialSegments;
  38543. var u = modI / radialSegments * 2 * p * Math.PI;
  38544. var p1 = getPos(u);
  38545. var p2 = getPos(u + 0.01);
  38546. var tang = p2.subtract(p1);
  38547. var n = p2.add(p1);
  38548. var bitan = BABYLON.Vector3.Cross(tang, n);
  38549. n = BABYLON.Vector3.Cross(bitan, tang);
  38550. bitan.normalize();
  38551. n.normalize();
  38552. for (j = 0; j < tubularSegments; j++) {
  38553. var modJ = j % tubularSegments;
  38554. var v = modJ / tubularSegments * 2 * Math.PI;
  38555. var cx = -tube * Math.cos(v);
  38556. var cy = tube * Math.sin(v);
  38557. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38558. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38559. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38560. uvs.push(i / radialSegments);
  38561. uvs.push(j / tubularSegments);
  38562. }
  38563. }
  38564. for (i = 0; i < radialSegments; i++) {
  38565. for (j = 0; j < tubularSegments; j++) {
  38566. var jNext = (j + 1) % tubularSegments;
  38567. var a = i * tubularSegments + j;
  38568. var b = (i + 1) * tubularSegments + j;
  38569. var c = (i + 1) * tubularSegments + jNext;
  38570. var d = i * tubularSegments + jNext;
  38571. indices.push(d);
  38572. indices.push(b);
  38573. indices.push(a);
  38574. indices.push(d);
  38575. indices.push(c);
  38576. indices.push(b);
  38577. }
  38578. }
  38579. // Normals
  38580. VertexData.ComputeNormals(positions, indices, normals);
  38581. // Sides
  38582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38583. // Result
  38584. var vertexData = new VertexData();
  38585. vertexData.indices = indices;
  38586. vertexData.positions = positions;
  38587. vertexData.normals = normals;
  38588. vertexData.uvs = uvs;
  38589. return vertexData;
  38590. };
  38591. // Tools
  38592. /**
  38593. * @param {any} - positions (number[] or Float32Array)
  38594. * @param {any} - indices (number[] or Uint16Array)
  38595. * @param {any} - normals (number[] or Float32Array)
  38596. * options (optional) :
  38597. * facetPositions : optional array of facet positions (vector3)
  38598. * facetNormals : optional array of facet normals (vector3)
  38599. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38600. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38601. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38602. * bbSize : optional bounding box size data, required for facetPartitioning computation
  38603. * bInfo : optional bounding info, required for facetPartitioning computation
  38604. */
  38605. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38606. // temporary scalar variables
  38607. var index = 0; // facet index
  38608. var p1p2x = 0.0; // p1p2 vector x coordinate
  38609. var p1p2y = 0.0; // p1p2 vector y coordinate
  38610. var p1p2z = 0.0; // p1p2 vector z coordinate
  38611. var p3p2x = 0.0; // p3p2 vector x coordinate
  38612. var p3p2y = 0.0; // p3p2 vector y coordinate
  38613. var p3p2z = 0.0; // p3p2 vector z coordinate
  38614. var faceNormalx = 0.0; // facet normal x coordinate
  38615. var faceNormaly = 0.0; // facet normal y coordinate
  38616. var faceNormalz = 0.0; // facet normal z coordinate
  38617. var length = 0.0; // facet normal length before normalization
  38618. var v1x = 0; // vector1 x index in the positions array
  38619. var v1y = 0; // vector1 y index in the positions array
  38620. var v1z = 0; // vector1 z index in the positions array
  38621. var v2x = 0; // vector2 x index in the positions array
  38622. var v2y = 0; // vector2 y index in the positions array
  38623. var v2z = 0; // vector2 z index in the positions array
  38624. var v3x = 0; // vector3 x index in the positions array
  38625. var v3y = 0; // vector3 y index in the positions array
  38626. var v3z = 0; // vector3 z index in the positions array
  38627. var computeFacetNormals = false;
  38628. var computeFacetPositions = false;
  38629. var computeFacetPartitioning = false;
  38630. if (options) {
  38631. computeFacetNormals = (options.facetNormals) ? true : false;
  38632. computeFacetPositions = (options.facetPositions) ? true : false;
  38633. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38634. }
  38635. // facetPartitioning reinit if needed
  38636. if (computeFacetPartitioning) {
  38637. var ox = 0; // X partitioning index for facet position
  38638. var oy = 0; // Y partinioning index for facet position
  38639. var oz = 0; // Z partinioning index for facet position
  38640. var b1x = 0; // X partitioning index for facet v1 vertex
  38641. var b1y = 0; // Y partitioning index for facet v1 vertex
  38642. var b1z = 0; // z partitioning index for facet v1 vertex
  38643. var b2x = 0; // X partitioning index for facet v2 vertex
  38644. var b2y = 0; // Y partitioning index for facet v2 vertex
  38645. var b2z = 0; // Z partitioning index for facet v2 vertex
  38646. var b3x = 0; // X partitioning index for facet v3 vertex
  38647. var b3y = 0; // Y partitioning index for facet v3 vertex
  38648. var b3z = 0; // Z partitioning index for facet v3 vertex
  38649. var block_idx_o = 0; // facet barycenter block index
  38650. var block_idx_v1 = 0; // v1 vertex block index
  38651. var block_idx_v2 = 0; // v2 vertex block index
  38652. var block_idx_v3 = 0; // v3 vertex block index
  38653. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38654. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38655. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  38656. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  38657. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  38658. var subSq = options.subDiv.max * options.subDiv.max;
  38659. options.facetPartitioning.length = 0;
  38660. }
  38661. // reset the normals
  38662. for (index = 0; index < positions.length; index++) {
  38663. normals[index] = 0.0;
  38664. }
  38665. // Loop : 1 indice triplet = 1 facet
  38666. var nbFaces = indices.length / 3;
  38667. for (index = 0; index < nbFaces; index++) {
  38668. // get the indexes of the coordinates of each vertex of the facet
  38669. v1x = indices[index * 3] * 3;
  38670. v1y = v1x + 1;
  38671. v1z = v1x + 2;
  38672. v2x = indices[index * 3 + 1] * 3;
  38673. v2y = v2x + 1;
  38674. v2z = v2x + 2;
  38675. v3x = indices[index * 3 + 2] * 3;
  38676. v3y = v3x + 1;
  38677. v3z = v3x + 2;
  38678. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38679. p1p2y = positions[v1y] - positions[v2y];
  38680. p1p2z = positions[v1z] - positions[v2z];
  38681. p3p2x = positions[v3x] - positions[v2x];
  38682. p3p2y = positions[v3y] - positions[v2y];
  38683. p3p2z = positions[v3z] - positions[v2z];
  38684. // compute the face normal with the cross product
  38685. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  38686. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  38687. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  38688. // normalize this normal and store it in the array facetData
  38689. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38690. length = (length === 0) ? 1.0 : length;
  38691. faceNormalx /= length;
  38692. faceNormaly /= length;
  38693. faceNormalz /= length;
  38694. if (computeFacetNormals) {
  38695. options.facetNormals[index].x = faceNormalx;
  38696. options.facetNormals[index].y = faceNormaly;
  38697. options.facetNormals[index].z = faceNormalz;
  38698. }
  38699. if (computeFacetPositions) {
  38700. // compute and the facet barycenter coordinates in the array facetPositions
  38701. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38702. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38703. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38704. }
  38705. if (computeFacetPartitioning) {
  38706. // store the facet indexes in arrays in the main facetPartitioning array :
  38707. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38708. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38709. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38710. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38711. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38712. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38713. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38714. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38715. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38716. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38717. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38718. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38719. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38720. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38721. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38722. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38723. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38724. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38725. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38726. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38727. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38728. // push each facet index in each block containing the vertex
  38729. options.facetPartitioning[block_idx_v1].push(index);
  38730. if (block_idx_v2 != block_idx_v1) {
  38731. options.facetPartitioning[block_idx_v2].push(index);
  38732. }
  38733. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38734. options.facetPartitioning[block_idx_v3].push(index);
  38735. }
  38736. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38737. options.facetPartitioning[block_idx_o].push(index);
  38738. }
  38739. }
  38740. // compute the normals anyway
  38741. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38742. normals[v1y] += faceNormaly;
  38743. normals[v1z] += faceNormalz;
  38744. normals[v2x] += faceNormalx;
  38745. normals[v2y] += faceNormaly;
  38746. normals[v2z] += faceNormalz;
  38747. normals[v3x] += faceNormalx;
  38748. normals[v3y] += faceNormaly;
  38749. normals[v3z] += faceNormalz;
  38750. }
  38751. // last normalization of each normal
  38752. for (index = 0; index < normals.length / 3; index++) {
  38753. faceNormalx = normals[index * 3];
  38754. faceNormaly = normals[index * 3 + 1];
  38755. faceNormalz = normals[index * 3 + 2];
  38756. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38757. length = (length === 0) ? 1.0 : length;
  38758. faceNormalx /= length;
  38759. faceNormaly /= length;
  38760. faceNormalz /= length;
  38761. normals[index * 3] = faceNormalx;
  38762. normals[index * 3 + 1] = faceNormaly;
  38763. normals[index * 3 + 2] = faceNormalz;
  38764. }
  38765. };
  38766. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38767. var li = indices.length;
  38768. var ln = normals.length;
  38769. var i;
  38770. var n;
  38771. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38772. switch (sideOrientation) {
  38773. case BABYLON.Mesh.FRONTSIDE:
  38774. // nothing changed
  38775. break;
  38776. case BABYLON.Mesh.BACKSIDE:
  38777. var tmp;
  38778. // indices
  38779. for (i = 0; i < li; i += 3) {
  38780. tmp = indices[i];
  38781. indices[i] = indices[i + 2];
  38782. indices[i + 2] = tmp;
  38783. }
  38784. // normals
  38785. for (n = 0; n < ln; n++) {
  38786. normals[n] = -normals[n];
  38787. }
  38788. break;
  38789. case BABYLON.Mesh.DOUBLESIDE:
  38790. // positions
  38791. var lp = positions.length;
  38792. var l = lp / 3;
  38793. for (var p = 0; p < lp; p++) {
  38794. positions[lp + p] = positions[p];
  38795. }
  38796. // indices
  38797. for (i = 0; i < li; i += 3) {
  38798. indices[i + li] = indices[i + 2] + l;
  38799. indices[i + 1 + li] = indices[i + 1] + l;
  38800. indices[i + 2 + li] = indices[i] + l;
  38801. }
  38802. // normals
  38803. for (n = 0; n < ln; n++) {
  38804. normals[ln + n] = -normals[n];
  38805. }
  38806. // uvs
  38807. var lu = uvs.length;
  38808. for (var u = 0; u < lu; u++) {
  38809. uvs[u + lu] = uvs[u];
  38810. }
  38811. break;
  38812. }
  38813. };
  38814. /**
  38815. * Creates a new VertexData from the imported parameters.
  38816. */
  38817. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38818. var vertexData = new VertexData();
  38819. // positions
  38820. var positions = parsedVertexData.positions;
  38821. if (positions) {
  38822. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38823. }
  38824. // normals
  38825. var normals = parsedVertexData.normals;
  38826. if (normals) {
  38827. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38828. }
  38829. // tangents
  38830. var tangents = parsedVertexData.tangents;
  38831. if (tangents) {
  38832. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38833. }
  38834. // uvs
  38835. var uvs = parsedVertexData.uvs;
  38836. if (uvs) {
  38837. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38838. }
  38839. // uv2s
  38840. var uv2s = parsedVertexData.uv2s;
  38841. if (uv2s) {
  38842. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38843. }
  38844. // uv3s
  38845. var uv3s = parsedVertexData.uv3s;
  38846. if (uv3s) {
  38847. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38848. }
  38849. // uv4s
  38850. var uv4s = parsedVertexData.uv4s;
  38851. if (uv4s) {
  38852. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38853. }
  38854. // uv5s
  38855. var uv5s = parsedVertexData.uv5s;
  38856. if (uv5s) {
  38857. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38858. }
  38859. // uv6s
  38860. var uv6s = parsedVertexData.uv6s;
  38861. if (uv6s) {
  38862. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38863. }
  38864. // colors
  38865. var colors = parsedVertexData.colors;
  38866. if (colors) {
  38867. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38868. }
  38869. // matricesIndices
  38870. var matricesIndices = parsedVertexData.matricesIndices;
  38871. if (matricesIndices) {
  38872. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38873. }
  38874. // matricesWeights
  38875. var matricesWeights = parsedVertexData.matricesWeights;
  38876. if (matricesWeights) {
  38877. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38878. }
  38879. // indices
  38880. var indices = parsedVertexData.indices;
  38881. if (indices) {
  38882. vertexData.indices = indices;
  38883. }
  38884. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38885. };
  38886. return VertexData;
  38887. }());
  38888. BABYLON.VertexData = VertexData;
  38889. })(BABYLON || (BABYLON = {}));
  38890. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38891. var BABYLON;
  38892. (function (BABYLON) {
  38893. var Tags = (function () {
  38894. function Tags() {
  38895. }
  38896. Tags.EnableFor = function (obj) {
  38897. obj._tags = obj._tags || {};
  38898. obj.hasTags = function () {
  38899. return Tags.HasTags(obj);
  38900. };
  38901. obj.addTags = function (tagsString) {
  38902. return Tags.AddTagsTo(obj, tagsString);
  38903. };
  38904. obj.removeTags = function (tagsString) {
  38905. return Tags.RemoveTagsFrom(obj, tagsString);
  38906. };
  38907. obj.matchesTagsQuery = function (tagsQuery) {
  38908. return Tags.MatchesQuery(obj, tagsQuery);
  38909. };
  38910. };
  38911. Tags.DisableFor = function (obj) {
  38912. delete obj._tags;
  38913. delete obj.hasTags;
  38914. delete obj.addTags;
  38915. delete obj.removeTags;
  38916. delete obj.matchesTagsQuery;
  38917. };
  38918. Tags.HasTags = function (obj) {
  38919. if (!obj._tags) {
  38920. return false;
  38921. }
  38922. return !BABYLON.Tools.IsEmpty(obj._tags);
  38923. };
  38924. Tags.GetTags = function (obj, asString) {
  38925. if (asString === void 0) { asString = true; }
  38926. if (!obj._tags) {
  38927. return null;
  38928. }
  38929. if (asString) {
  38930. var tagsArray = [];
  38931. for (var tag in obj._tags) {
  38932. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38933. tagsArray.push(tag);
  38934. }
  38935. }
  38936. return tagsArray.join(" ");
  38937. }
  38938. else {
  38939. return obj._tags;
  38940. }
  38941. };
  38942. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38943. // a tag cannot start with '||', '&&', and '!'
  38944. // it cannot contain whitespaces
  38945. Tags.AddTagsTo = function (obj, tagsString) {
  38946. if (!tagsString) {
  38947. return;
  38948. }
  38949. if (typeof tagsString !== "string") {
  38950. return;
  38951. }
  38952. var tags = tagsString.split(" ");
  38953. tags.forEach(function (tag, index, array) {
  38954. Tags._AddTagTo(obj, tag);
  38955. });
  38956. };
  38957. Tags._AddTagTo = function (obj, tag) {
  38958. tag = tag.trim();
  38959. if (tag === "" || tag === "true" || tag === "false") {
  38960. return;
  38961. }
  38962. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38963. return;
  38964. }
  38965. Tags.EnableFor(obj);
  38966. obj._tags[tag] = true;
  38967. };
  38968. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38969. if (!Tags.HasTags(obj)) {
  38970. return;
  38971. }
  38972. var tags = tagsString.split(" ");
  38973. for (var t in tags) {
  38974. Tags._RemoveTagFrom(obj, tags[t]);
  38975. }
  38976. };
  38977. Tags._RemoveTagFrom = function (obj, tag) {
  38978. delete obj._tags[tag];
  38979. };
  38980. Tags.MatchesQuery = function (obj, tagsQuery) {
  38981. if (tagsQuery === undefined) {
  38982. return true;
  38983. }
  38984. if (tagsQuery === "") {
  38985. return Tags.HasTags(obj);
  38986. }
  38987. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38988. };
  38989. return Tags;
  38990. }());
  38991. BABYLON.Tags = Tags;
  38992. })(BABYLON || (BABYLON = {}));
  38993. //# sourceMappingURL=babylon.tags.js.map
  38994. var BABYLON;
  38995. (function (BABYLON) {
  38996. var Internals;
  38997. (function (Internals) {
  38998. var AndOrNotEvaluator = (function () {
  38999. function AndOrNotEvaluator() {
  39000. }
  39001. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  39002. if (!query.match(/\([^\(\)]*\)/g)) {
  39003. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  39004. }
  39005. else {
  39006. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  39007. // remove parenthesis
  39008. r = r.slice(1, r.length - 1);
  39009. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  39010. });
  39011. }
  39012. if (query === "true") {
  39013. return true;
  39014. }
  39015. if (query === "false") {
  39016. return false;
  39017. }
  39018. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  39019. };
  39020. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  39021. evaluateCallback = evaluateCallback || (function (r) {
  39022. return r === "true" ? true : false;
  39023. });
  39024. var result;
  39025. var or = parenthesisContent.split("||");
  39026. for (var i in or) {
  39027. if (or.hasOwnProperty(i)) {
  39028. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  39029. var and = ori.split("&&");
  39030. if (and.length > 1) {
  39031. for (var j = 0; j < and.length; ++j) {
  39032. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  39033. if (andj !== "true" && andj !== "false") {
  39034. if (andj[0] === "!") {
  39035. result = !evaluateCallback(andj.substring(1));
  39036. }
  39037. else {
  39038. result = evaluateCallback(andj);
  39039. }
  39040. }
  39041. else {
  39042. result = andj === "true" ? true : false;
  39043. }
  39044. if (!result) {
  39045. ori = "false";
  39046. break;
  39047. }
  39048. }
  39049. }
  39050. if (result || ori === "true") {
  39051. result = true;
  39052. break;
  39053. }
  39054. // result equals false (or undefined)
  39055. if (ori !== "true" && ori !== "false") {
  39056. if (ori[0] === "!") {
  39057. result = !evaluateCallback(ori.substring(1));
  39058. }
  39059. else {
  39060. result = evaluateCallback(ori);
  39061. }
  39062. }
  39063. else {
  39064. result = ori === "true" ? true : false;
  39065. }
  39066. }
  39067. }
  39068. // the whole parenthesis scope is replaced by 'true' or 'false'
  39069. return result ? "true" : "false";
  39070. };
  39071. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  39072. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  39073. // remove whitespaces
  39074. r = r.replace(/[\s]/g, function () { return ""; });
  39075. return r.length % 2 ? "!" : "";
  39076. });
  39077. booleanString = booleanString.trim();
  39078. if (booleanString === "!true") {
  39079. booleanString = "false";
  39080. }
  39081. else if (booleanString === "!false") {
  39082. booleanString = "true";
  39083. }
  39084. return booleanString;
  39085. };
  39086. return AndOrNotEvaluator;
  39087. }());
  39088. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  39089. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39090. })(BABYLON || (BABYLON = {}));
  39091. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  39092. var BABYLON;
  39093. (function (BABYLON) {
  39094. var PostProcessRenderPass = (function () {
  39095. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39096. this._enabled = true;
  39097. this._refCount = 0;
  39098. this._name = name;
  39099. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39100. this.setRenderList(renderList);
  39101. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39102. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39103. this._scene = scene;
  39104. this._renderList = renderList;
  39105. }
  39106. // private
  39107. PostProcessRenderPass.prototype._incRefCount = function () {
  39108. if (this._refCount === 0) {
  39109. this._scene.customRenderTargets.push(this._renderTexture);
  39110. }
  39111. return ++this._refCount;
  39112. };
  39113. PostProcessRenderPass.prototype._decRefCount = function () {
  39114. this._refCount--;
  39115. if (this._refCount <= 0) {
  39116. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39117. }
  39118. return this._refCount;
  39119. };
  39120. PostProcessRenderPass.prototype._update = function () {
  39121. this.setRenderList(this._renderList);
  39122. };
  39123. // public
  39124. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39125. this._renderTexture.renderList = renderList;
  39126. };
  39127. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39128. return this._renderTexture;
  39129. };
  39130. return PostProcessRenderPass;
  39131. }());
  39132. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39133. })(BABYLON || (BABYLON = {}));
  39134. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39135. var BABYLON;
  39136. (function (BABYLON) {
  39137. var PostProcessRenderEffect = (function () {
  39138. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39139. this._engine = engine;
  39140. this._name = name;
  39141. this._singleInstance = singleInstance || true;
  39142. this._getPostProcess = getPostProcess;
  39143. this._cameras = [];
  39144. this._indicesForCamera = [];
  39145. this._postProcesses = {};
  39146. this._renderPasses = {};
  39147. this._renderEffectAsPasses = {};
  39148. }
  39149. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39150. get: function () {
  39151. for (var index in this._postProcesses) {
  39152. if (!this._postProcesses[index].isSupported) {
  39153. return false;
  39154. }
  39155. }
  39156. return true;
  39157. },
  39158. enumerable: true,
  39159. configurable: true
  39160. });
  39161. PostProcessRenderEffect.prototype._update = function () {
  39162. for (var renderPassName in this._renderPasses) {
  39163. this._renderPasses[renderPassName]._update();
  39164. }
  39165. };
  39166. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39167. this._renderPasses[renderPass._name] = renderPass;
  39168. this._linkParameters();
  39169. };
  39170. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39171. delete this._renderPasses[renderPass._name];
  39172. this._linkParameters();
  39173. };
  39174. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39175. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39176. this._linkParameters();
  39177. };
  39178. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39179. for (var renderPassName in this._renderPasses) {
  39180. if (renderPassName === passName) {
  39181. return this._renderPasses[passName];
  39182. }
  39183. }
  39184. };
  39185. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39186. this._renderPasses = {};
  39187. this._linkParameters();
  39188. };
  39189. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39190. var cameraKey;
  39191. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39192. for (var i = 0; i < _cam.length; i++) {
  39193. var camera = _cam[i];
  39194. var cameraName = camera.name;
  39195. if (this._singleInstance) {
  39196. cameraKey = 0;
  39197. }
  39198. else {
  39199. cameraKey = cameraName;
  39200. }
  39201. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39202. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39203. if (!this._indicesForCamera[cameraName]) {
  39204. this._indicesForCamera[cameraName] = [];
  39205. }
  39206. this._indicesForCamera[cameraName].push(index);
  39207. if (this._cameras.indexOf(camera) === -1) {
  39208. this._cameras[cameraName] = camera;
  39209. }
  39210. for (var passName in this._renderPasses) {
  39211. this._renderPasses[passName]._incRefCount();
  39212. }
  39213. }
  39214. this._linkParameters();
  39215. };
  39216. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39217. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39218. for (var i = 0; i < _cam.length; i++) {
  39219. var camera = _cam[i];
  39220. var cameraName = camera.name;
  39221. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39222. var index = this._cameras.indexOf(cameraName);
  39223. this._indicesForCamera.splice(index, 1);
  39224. this._cameras.splice(index, 1);
  39225. for (var passName in this._renderPasses) {
  39226. this._renderPasses[passName]._decRefCount();
  39227. }
  39228. }
  39229. };
  39230. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39231. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39232. for (var i = 0; i < _cam.length; i++) {
  39233. var camera = _cam[i];
  39234. var cameraName = camera.name;
  39235. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39236. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39237. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39238. }
  39239. }
  39240. for (var passName in this._renderPasses) {
  39241. this._renderPasses[passName]._incRefCount();
  39242. }
  39243. }
  39244. };
  39245. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39246. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39247. for (var i = 0; i < _cam.length; i++) {
  39248. var camera = _cam[i];
  39249. var cameraName = camera.Name;
  39250. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39251. for (var passName in this._renderPasses) {
  39252. this._renderPasses[passName]._decRefCount();
  39253. }
  39254. }
  39255. };
  39256. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39257. if (this._singleInstance) {
  39258. return this._postProcesses[0];
  39259. }
  39260. else {
  39261. return this._postProcesses[camera.name];
  39262. }
  39263. };
  39264. PostProcessRenderEffect.prototype._linkParameters = function () {
  39265. var _this = this;
  39266. for (var index in this._postProcesses) {
  39267. if (this.applyParameters) {
  39268. this.applyParameters(this._postProcesses[index]);
  39269. }
  39270. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39271. _this._linkTextures(effect);
  39272. });
  39273. }
  39274. };
  39275. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39276. for (var renderPassName in this._renderPasses) {
  39277. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39278. }
  39279. for (var renderEffectName in this._renderEffectAsPasses) {
  39280. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39281. }
  39282. };
  39283. return PostProcessRenderEffect;
  39284. }());
  39285. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39286. })(BABYLON || (BABYLON = {}));
  39287. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39288. var BABYLON;
  39289. (function (BABYLON) {
  39290. var PostProcessRenderPipeline = (function () {
  39291. function PostProcessRenderPipeline(engine, name) {
  39292. this._engine = engine;
  39293. this._name = name;
  39294. this._renderEffects = {};
  39295. this._renderEffectsForIsolatedPass = {};
  39296. this._cameras = [];
  39297. }
  39298. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39299. get: function () {
  39300. for (var renderEffectName in this._renderEffects) {
  39301. if (!this._renderEffects[renderEffectName].isSupported) {
  39302. return false;
  39303. }
  39304. }
  39305. return true;
  39306. },
  39307. enumerable: true,
  39308. configurable: true
  39309. });
  39310. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39311. this._renderEffects[renderEffect._name] = renderEffect;
  39312. };
  39313. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39314. var renderEffects = this._renderEffects[renderEffectName];
  39315. if (!renderEffects) {
  39316. return;
  39317. }
  39318. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39319. };
  39320. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39321. var renderEffects = this._renderEffects[renderEffectName];
  39322. if (!renderEffects) {
  39323. return;
  39324. }
  39325. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39326. };
  39327. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39328. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39329. var indicesToDelete = [];
  39330. var i;
  39331. for (i = 0; i < _cam.length; i++) {
  39332. var camera = _cam[i];
  39333. var cameraName = camera.name;
  39334. if (this._cameras.indexOf(camera) === -1) {
  39335. this._cameras[cameraName] = camera;
  39336. }
  39337. else if (unique) {
  39338. indicesToDelete.push(i);
  39339. }
  39340. }
  39341. for (i = 0; i < indicesToDelete.length; i++) {
  39342. cameras.splice(indicesToDelete[i], 1);
  39343. }
  39344. for (var renderEffectName in this._renderEffects) {
  39345. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39346. }
  39347. };
  39348. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39349. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39350. for (var renderEffectName in this._renderEffects) {
  39351. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39352. }
  39353. for (var i = 0; i < _cam.length; i++) {
  39354. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39355. }
  39356. };
  39357. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39358. var _this = this;
  39359. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39360. var pass = null;
  39361. var renderEffectName;
  39362. for (renderEffectName in this._renderEffects) {
  39363. pass = this._renderEffects[renderEffectName].getPass(passName);
  39364. if (pass != null) {
  39365. break;
  39366. }
  39367. }
  39368. if (pass === null) {
  39369. return;
  39370. }
  39371. for (renderEffectName in this._renderEffects) {
  39372. this._renderEffects[renderEffectName]._disable(_cam);
  39373. }
  39374. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39375. for (var i = 0; i < _cam.length; i++) {
  39376. var camera = _cam[i];
  39377. var cameraName = camera.name;
  39378. 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); });
  39379. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39380. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39381. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39382. }
  39383. };
  39384. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39385. var _this = this;
  39386. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39387. for (var i = 0; i < _cam.length; i++) {
  39388. var camera = _cam[i];
  39389. var cameraName = camera.name;
  39390. 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); });
  39391. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39392. }
  39393. for (var renderEffectName in this._renderEffects) {
  39394. this._renderEffects[renderEffectName]._enable(_cam);
  39395. }
  39396. };
  39397. PostProcessRenderPipeline.prototype._update = function () {
  39398. for (var renderEffectName in this._renderEffects) {
  39399. this._renderEffects[renderEffectName]._update();
  39400. }
  39401. for (var i = 0; i < this._cameras.length; i++) {
  39402. var cameraName = this._cameras[i].name;
  39403. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39404. this._renderEffectsForIsolatedPass[cameraName]._update();
  39405. }
  39406. }
  39407. };
  39408. PostProcessRenderPipeline.prototype.dispose = function () {
  39409. // Must be implemented by children
  39410. };
  39411. return PostProcessRenderPipeline;
  39412. }());
  39413. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39414. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39415. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39416. })(BABYLON || (BABYLON = {}));
  39417. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39418. var BABYLON;
  39419. (function (BABYLON) {
  39420. var PostProcessRenderPipelineManager = (function () {
  39421. function PostProcessRenderPipelineManager() {
  39422. this._renderPipelines = {};
  39423. }
  39424. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39425. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39426. };
  39427. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39428. var renderPipeline = this._renderPipelines[renderPipelineName];
  39429. if (!renderPipeline) {
  39430. return;
  39431. }
  39432. renderPipeline._attachCameras(cameras, unique);
  39433. };
  39434. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39435. var renderPipeline = this._renderPipelines[renderPipelineName];
  39436. if (!renderPipeline) {
  39437. return;
  39438. }
  39439. renderPipeline._detachCameras(cameras);
  39440. };
  39441. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39442. var renderPipeline = this._renderPipelines[renderPipelineName];
  39443. if (!renderPipeline) {
  39444. return;
  39445. }
  39446. renderPipeline._enableEffect(renderEffectName, cameras);
  39447. };
  39448. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39449. var renderPipeline = this._renderPipelines[renderPipelineName];
  39450. if (!renderPipeline) {
  39451. return;
  39452. }
  39453. renderPipeline._disableEffect(renderEffectName, cameras);
  39454. };
  39455. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39456. var renderPipeline = this._renderPipelines[renderPipelineName];
  39457. if (!renderPipeline) {
  39458. return;
  39459. }
  39460. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39461. };
  39462. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39463. var renderPipeline = this._renderPipelines[renderPipelineName];
  39464. if (!renderPipeline) {
  39465. return;
  39466. }
  39467. renderPipeline._disableDisplayOnlyPass(cameras);
  39468. };
  39469. PostProcessRenderPipelineManager.prototype.update = function () {
  39470. for (var renderPipelineName in this._renderPipelines) {
  39471. var pipeline = this._renderPipelines[renderPipelineName];
  39472. if (!pipeline.isSupported) {
  39473. pipeline.dispose();
  39474. delete this._renderPipelines[renderPipelineName];
  39475. }
  39476. else {
  39477. pipeline._update();
  39478. }
  39479. }
  39480. };
  39481. return PostProcessRenderPipelineManager;
  39482. }());
  39483. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39484. })(BABYLON || (BABYLON = {}));
  39485. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39486. var BABYLON;
  39487. (function (BABYLON) {
  39488. var BoundingBoxRenderer = (function () {
  39489. function BoundingBoxRenderer(scene) {
  39490. this.frontColor = new BABYLON.Color3(1, 1, 1);
  39491. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  39492. this.showBackLines = true;
  39493. this.renderList = new BABYLON.SmartArray(32);
  39494. this._vertexBuffers = {};
  39495. this._scene = scene;
  39496. }
  39497. BoundingBoxRenderer.prototype._prepareRessources = function () {
  39498. if (this._colorShader) {
  39499. return;
  39500. }
  39501. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  39502. attributes: [BABYLON.VertexBuffer.PositionKind],
  39503. uniforms: ["worldViewProjection", "color"]
  39504. });
  39505. var engine = this._scene.getEngine();
  39506. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  39507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  39508. 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]);
  39509. };
  39510. BoundingBoxRenderer.prototype.reset = function () {
  39511. this.renderList.reset();
  39512. };
  39513. BoundingBoxRenderer.prototype.render = function () {
  39514. if (this.renderList.length === 0) {
  39515. return;
  39516. }
  39517. this._prepareRessources();
  39518. if (!this._colorShader.isReady()) {
  39519. return;
  39520. }
  39521. var engine = this._scene.getEngine();
  39522. engine.setDepthWrite(false);
  39523. this._colorShader._preBind();
  39524. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  39525. var boundingBox = this.renderList.data[boundingBoxIndex];
  39526. var min = boundingBox.minimum;
  39527. var max = boundingBox.maximum;
  39528. var diff = max.subtract(min);
  39529. var median = min.add(diff.scale(0.5));
  39530. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  39531. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  39532. .multiply(boundingBox.getWorldMatrix());
  39533. // VBOs
  39534. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  39535. if (this.showBackLines) {
  39536. // Back
  39537. engine.setDepthFunctionToGreaterOrEqual();
  39538. this._scene.resetCachedMaterial();
  39539. this._colorShader.setColor4("color", this.backColor.toColor4());
  39540. this._colorShader.bind(worldMatrix);
  39541. // Draw order
  39542. engine.draw(false, 0, 24);
  39543. }
  39544. // Front
  39545. engine.setDepthFunctionToLess();
  39546. this._scene.resetCachedMaterial();
  39547. this._colorShader.setColor4("color", this.frontColor.toColor4());
  39548. this._colorShader.bind(worldMatrix);
  39549. // Draw order
  39550. engine.draw(false, 0, 24);
  39551. }
  39552. this._colorShader.unbind();
  39553. engine.setDepthFunctionToLessOrEqual();
  39554. engine.setDepthWrite(true);
  39555. };
  39556. BoundingBoxRenderer.prototype.dispose = function () {
  39557. if (!this._colorShader) {
  39558. return;
  39559. }
  39560. this.renderList.dispose();
  39561. this._colorShader.dispose();
  39562. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39563. if (buffer) {
  39564. buffer.dispose();
  39565. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39566. }
  39567. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39568. };
  39569. return BoundingBoxRenderer;
  39570. }());
  39571. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  39572. })(BABYLON || (BABYLON = {}));
  39573. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  39574. var BABYLON;
  39575. (function (BABYLON) {
  39576. var Condition = (function () {
  39577. function Condition(actionManager) {
  39578. this._actionManager = actionManager;
  39579. }
  39580. Condition.prototype.isValid = function () {
  39581. return true;
  39582. };
  39583. Condition.prototype._getProperty = function (propertyPath) {
  39584. return this._actionManager._getProperty(propertyPath);
  39585. };
  39586. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39587. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39588. };
  39589. Condition.prototype.serialize = function () {
  39590. };
  39591. Condition.prototype._serialize = function (serializedCondition) {
  39592. return {
  39593. type: 2,
  39594. children: [],
  39595. name: serializedCondition.name,
  39596. properties: serializedCondition.properties
  39597. };
  39598. };
  39599. return Condition;
  39600. }());
  39601. BABYLON.Condition = Condition;
  39602. var ValueCondition = (function (_super) {
  39603. __extends(ValueCondition, _super);
  39604. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39605. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39606. var _this = _super.call(this, actionManager) || this;
  39607. _this.propertyPath = propertyPath;
  39608. _this.value = value;
  39609. _this.operator = operator;
  39610. _this._target = target;
  39611. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39612. _this._property = _this._getProperty(_this.propertyPath);
  39613. return _this;
  39614. }
  39615. Object.defineProperty(ValueCondition, "IsEqual", {
  39616. get: function () {
  39617. return ValueCondition._IsEqual;
  39618. },
  39619. enumerable: true,
  39620. configurable: true
  39621. });
  39622. Object.defineProperty(ValueCondition, "IsDifferent", {
  39623. get: function () {
  39624. return ValueCondition._IsDifferent;
  39625. },
  39626. enumerable: true,
  39627. configurable: true
  39628. });
  39629. Object.defineProperty(ValueCondition, "IsGreater", {
  39630. get: function () {
  39631. return ValueCondition._IsGreater;
  39632. },
  39633. enumerable: true,
  39634. configurable: true
  39635. });
  39636. Object.defineProperty(ValueCondition, "IsLesser", {
  39637. get: function () {
  39638. return ValueCondition._IsLesser;
  39639. },
  39640. enumerable: true,
  39641. configurable: true
  39642. });
  39643. // Methods
  39644. ValueCondition.prototype.isValid = function () {
  39645. switch (this.operator) {
  39646. case ValueCondition.IsGreater:
  39647. return this._effectiveTarget[this._property] > this.value;
  39648. case ValueCondition.IsLesser:
  39649. return this._effectiveTarget[this._property] < this.value;
  39650. case ValueCondition.IsEqual:
  39651. case ValueCondition.IsDifferent:
  39652. var check;
  39653. if (this.value.equals) {
  39654. check = this.value.equals(this._effectiveTarget[this._property]);
  39655. }
  39656. else {
  39657. check = this.value === this._effectiveTarget[this._property];
  39658. }
  39659. return this.operator === ValueCondition.IsEqual ? check : !check;
  39660. }
  39661. return false;
  39662. };
  39663. ValueCondition.prototype.serialize = function () {
  39664. return this._serialize({
  39665. name: "ValueCondition",
  39666. properties: [
  39667. BABYLON.Action._GetTargetProperty(this._target),
  39668. { name: "propertyPath", value: this.propertyPath },
  39669. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39670. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39671. ]
  39672. });
  39673. };
  39674. ValueCondition.GetOperatorName = function (operator) {
  39675. switch (operator) {
  39676. case ValueCondition._IsEqual: return "IsEqual";
  39677. case ValueCondition._IsDifferent: return "IsDifferent";
  39678. case ValueCondition._IsGreater: return "IsGreater";
  39679. case ValueCondition._IsLesser: return "IsLesser";
  39680. default: return "";
  39681. }
  39682. };
  39683. return ValueCondition;
  39684. }(Condition));
  39685. // Statics
  39686. ValueCondition._IsEqual = 0;
  39687. ValueCondition._IsDifferent = 1;
  39688. ValueCondition._IsGreater = 2;
  39689. ValueCondition._IsLesser = 3;
  39690. BABYLON.ValueCondition = ValueCondition;
  39691. var PredicateCondition = (function (_super) {
  39692. __extends(PredicateCondition, _super);
  39693. function PredicateCondition(actionManager, predicate) {
  39694. var _this = _super.call(this, actionManager) || this;
  39695. _this.predicate = predicate;
  39696. return _this;
  39697. }
  39698. PredicateCondition.prototype.isValid = function () {
  39699. return this.predicate();
  39700. };
  39701. return PredicateCondition;
  39702. }(Condition));
  39703. BABYLON.PredicateCondition = PredicateCondition;
  39704. var StateCondition = (function (_super) {
  39705. __extends(StateCondition, _super);
  39706. function StateCondition(actionManager, target, value) {
  39707. var _this = _super.call(this, actionManager) || this;
  39708. _this.value = value;
  39709. _this._target = target;
  39710. return _this;
  39711. }
  39712. // Methods
  39713. StateCondition.prototype.isValid = function () {
  39714. return this._target.state === this.value;
  39715. };
  39716. StateCondition.prototype.serialize = function () {
  39717. return this._serialize({
  39718. name: "StateCondition",
  39719. properties: [
  39720. BABYLON.Action._GetTargetProperty(this._target),
  39721. { name: "value", value: this.value }
  39722. ]
  39723. });
  39724. };
  39725. return StateCondition;
  39726. }(Condition));
  39727. BABYLON.StateCondition = StateCondition;
  39728. })(BABYLON || (BABYLON = {}));
  39729. //# sourceMappingURL=babylon.condition.js.map
  39730. var BABYLON;
  39731. (function (BABYLON) {
  39732. var Action = (function () {
  39733. function Action(triggerOptions, condition) {
  39734. this.triggerOptions = triggerOptions;
  39735. if (triggerOptions.parameter) {
  39736. this.trigger = triggerOptions.trigger;
  39737. this._triggerParameter = triggerOptions.parameter;
  39738. }
  39739. else {
  39740. this.trigger = triggerOptions;
  39741. }
  39742. this._nextActiveAction = this;
  39743. this._condition = condition;
  39744. }
  39745. // Methods
  39746. Action.prototype._prepare = function () {
  39747. };
  39748. Action.prototype.getTriggerParameter = function () {
  39749. return this._triggerParameter;
  39750. };
  39751. Action.prototype._executeCurrent = function (evt) {
  39752. if (this._nextActiveAction._condition) {
  39753. var condition = this._nextActiveAction._condition;
  39754. var currentRenderId = this._actionManager.getScene().getRenderId();
  39755. // We cache the current evaluation for the current frame
  39756. if (condition._evaluationId === currentRenderId) {
  39757. if (!condition._currentResult) {
  39758. return;
  39759. }
  39760. }
  39761. else {
  39762. condition._evaluationId = currentRenderId;
  39763. if (!condition.isValid()) {
  39764. condition._currentResult = false;
  39765. return;
  39766. }
  39767. condition._currentResult = true;
  39768. }
  39769. }
  39770. this._nextActiveAction.execute(evt);
  39771. this.skipToNextActiveAction();
  39772. };
  39773. Action.prototype.execute = function (evt) {
  39774. };
  39775. Action.prototype.skipToNextActiveAction = function () {
  39776. if (this._nextActiveAction._child) {
  39777. if (!this._nextActiveAction._child._actionManager) {
  39778. this._nextActiveAction._child._actionManager = this._actionManager;
  39779. }
  39780. this._nextActiveAction = this._nextActiveAction._child;
  39781. }
  39782. else {
  39783. this._nextActiveAction = this;
  39784. }
  39785. };
  39786. Action.prototype.then = function (action) {
  39787. this._child = action;
  39788. action._actionManager = this._actionManager;
  39789. action._prepare();
  39790. return action;
  39791. };
  39792. Action.prototype._getProperty = function (propertyPath) {
  39793. return this._actionManager._getProperty(propertyPath);
  39794. };
  39795. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39796. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39797. };
  39798. Action.prototype.serialize = function (parent) {
  39799. };
  39800. // Called by BABYLON.Action objects in serialize(...). Internal use
  39801. Action.prototype._serialize = function (serializedAction, parent) {
  39802. var serializationObject = {
  39803. type: 1,
  39804. children: [],
  39805. name: serializedAction.name,
  39806. properties: serializedAction.properties || []
  39807. };
  39808. // Serialize child
  39809. if (this._child) {
  39810. this._child.serialize(serializationObject);
  39811. }
  39812. // Check if "this" has a condition
  39813. if (this._condition) {
  39814. var serializedCondition = this._condition.serialize();
  39815. serializedCondition.children.push(serializationObject);
  39816. if (parent) {
  39817. parent.children.push(serializedCondition);
  39818. }
  39819. return serializedCondition;
  39820. }
  39821. if (parent) {
  39822. parent.children.push(serializationObject);
  39823. }
  39824. return serializationObject;
  39825. };
  39826. return Action;
  39827. }());
  39828. Action._SerializeValueAsString = function (value) {
  39829. if (typeof value === "number") {
  39830. return value.toString();
  39831. }
  39832. if (typeof value === "boolean") {
  39833. return value ? "true" : "false";
  39834. }
  39835. if (value instanceof BABYLON.Vector2) {
  39836. return value.x + ", " + value.y;
  39837. }
  39838. if (value instanceof BABYLON.Vector3) {
  39839. return value.x + ", " + value.y + ", " + value.z;
  39840. }
  39841. if (value instanceof BABYLON.Color3) {
  39842. return value.r + ", " + value.g + ", " + value.b;
  39843. }
  39844. if (value instanceof BABYLON.Color4) {
  39845. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39846. }
  39847. return value; // string
  39848. };
  39849. Action._GetTargetProperty = function (target) {
  39850. return {
  39851. name: "target",
  39852. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39853. : target instanceof BABYLON.Light ? "LightProperties"
  39854. : target instanceof BABYLON.Camera ? "CameraProperties"
  39855. : "SceneProperties",
  39856. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39857. };
  39858. };
  39859. BABYLON.Action = Action;
  39860. })(BABYLON || (BABYLON = {}));
  39861. //# sourceMappingURL=babylon.action.js.map
  39862. var BABYLON;
  39863. (function (BABYLON) {
  39864. /**
  39865. * ActionEvent is the event beint sent when an action is triggered.
  39866. */
  39867. var ActionEvent = (function () {
  39868. /**
  39869. * @constructor
  39870. * @param source The mesh or sprite that triggered the action.
  39871. * @param pointerX The X mouse cursor position at the time of the event
  39872. * @param pointerY The Y mouse cursor position at the time of the event
  39873. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39874. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39875. */
  39876. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39877. this.source = source;
  39878. this.pointerX = pointerX;
  39879. this.pointerY = pointerY;
  39880. this.meshUnderPointer = meshUnderPointer;
  39881. this.sourceEvent = sourceEvent;
  39882. this.additionalData = additionalData;
  39883. }
  39884. /**
  39885. * Helper function to auto-create an ActionEvent from a source mesh.
  39886. * @param source The source mesh that triggered the event
  39887. * @param evt {Event} The original (browser) event
  39888. */
  39889. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39890. var scene = source.getScene();
  39891. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39892. };
  39893. /**
  39894. * Helper function to auto-create an ActionEvent from a source mesh.
  39895. * @param source The source sprite that triggered the event
  39896. * @param scene Scene associated with the sprite
  39897. * @param evt {Event} The original (browser) event
  39898. */
  39899. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39900. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39901. };
  39902. /**
  39903. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39904. * @param scene the scene where the event occurred
  39905. * @param evt {Event} The original (browser) event
  39906. */
  39907. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39908. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39909. };
  39910. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39911. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39912. };
  39913. return ActionEvent;
  39914. }());
  39915. BABYLON.ActionEvent = ActionEvent;
  39916. /**
  39917. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39918. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39919. */
  39920. var ActionManager = (function () {
  39921. function ActionManager(scene) {
  39922. // Members
  39923. this.actions = new Array();
  39924. this.hoverCursor = '';
  39925. this._scene = scene;
  39926. scene._actionManagers.push(this);
  39927. }
  39928. Object.defineProperty(ActionManager, "NothingTrigger", {
  39929. get: function () {
  39930. return ActionManager._NothingTrigger;
  39931. },
  39932. enumerable: true,
  39933. configurable: true
  39934. });
  39935. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39936. get: function () {
  39937. return ActionManager._OnPickTrigger;
  39938. },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39943. get: function () {
  39944. return ActionManager._OnLeftPickTrigger;
  39945. },
  39946. enumerable: true,
  39947. configurable: true
  39948. });
  39949. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39950. get: function () {
  39951. return ActionManager._OnRightPickTrigger;
  39952. },
  39953. enumerable: true,
  39954. configurable: true
  39955. });
  39956. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39957. get: function () {
  39958. return ActionManager._OnCenterPickTrigger;
  39959. },
  39960. enumerable: true,
  39961. configurable: true
  39962. });
  39963. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39964. get: function () {
  39965. return ActionManager._OnPickDownTrigger;
  39966. },
  39967. enumerable: true,
  39968. configurable: true
  39969. });
  39970. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  39971. get: function () {
  39972. return ActionManager._OnDoublePickTrigger;
  39973. },
  39974. enumerable: true,
  39975. configurable: true
  39976. });
  39977. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39978. get: function () {
  39979. return ActionManager._OnPickUpTrigger;
  39980. },
  39981. enumerable: true,
  39982. configurable: true
  39983. });
  39984. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39985. /// This trigger will only be raised if you also declared a OnPickDown
  39986. get: function () {
  39987. return ActionManager._OnPickOutTrigger;
  39988. },
  39989. enumerable: true,
  39990. configurable: true
  39991. });
  39992. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39993. get: function () {
  39994. return ActionManager._OnLongPressTrigger;
  39995. },
  39996. enumerable: true,
  39997. configurable: true
  39998. });
  39999. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40000. get: function () {
  40001. return ActionManager._OnPointerOverTrigger;
  40002. },
  40003. enumerable: true,
  40004. configurable: true
  40005. });
  40006. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  40007. get: function () {
  40008. return ActionManager._OnPointerOutTrigger;
  40009. },
  40010. enumerable: true,
  40011. configurable: true
  40012. });
  40013. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  40014. get: function () {
  40015. return ActionManager._OnEveryFrameTrigger;
  40016. },
  40017. enumerable: true,
  40018. configurable: true
  40019. });
  40020. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  40021. get: function () {
  40022. return ActionManager._OnIntersectionEnterTrigger;
  40023. },
  40024. enumerable: true,
  40025. configurable: true
  40026. });
  40027. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  40028. get: function () {
  40029. return ActionManager._OnIntersectionExitTrigger;
  40030. },
  40031. enumerable: true,
  40032. configurable: true
  40033. });
  40034. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  40035. get: function () {
  40036. return ActionManager._OnKeyDownTrigger;
  40037. },
  40038. enumerable: true,
  40039. configurable: true
  40040. });
  40041. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  40042. get: function () {
  40043. return ActionManager._OnKeyUpTrigger;
  40044. },
  40045. enumerable: true,
  40046. configurable: true
  40047. });
  40048. // Methods
  40049. ActionManager.prototype.dispose = function () {
  40050. var index = this._scene._actionManagers.indexOf(this);
  40051. for (var i = 0; i < this.actions.length; i++) {
  40052. var action = this.actions[i];
  40053. ActionManager.Triggers[action.trigger]--;
  40054. if (ActionManager.Triggers[action.trigger] === 0) {
  40055. delete ActionManager.Triggers[action.trigger];
  40056. }
  40057. }
  40058. if (index > -1) {
  40059. this._scene._actionManagers.splice(index, 1);
  40060. }
  40061. };
  40062. ActionManager.prototype.getScene = function () {
  40063. return this._scene;
  40064. };
  40065. /**
  40066. * Does this action manager handles actions of any of the given triggers
  40067. * @param {number[]} triggers - the triggers to be tested
  40068. * @return {boolean} whether one (or more) of the triggers is handeled
  40069. */
  40070. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  40071. for (var index = 0; index < this.actions.length; index++) {
  40072. var action = this.actions[index];
  40073. if (triggers.indexOf(action.trigger) > -1) {
  40074. return true;
  40075. }
  40076. }
  40077. return false;
  40078. };
  40079. /**
  40080. * Does this action manager handles actions of a given trigger
  40081. * @param {number} trigger - the trigger to be tested
  40082. * @return {boolean} whether the trigger is handeled
  40083. */
  40084. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  40085. for (var index = 0; index < this.actions.length; index++) {
  40086. var action = this.actions[index];
  40087. if (action.trigger === trigger) {
  40088. return true;
  40089. }
  40090. }
  40091. return false;
  40092. };
  40093. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40094. /**
  40095. * Does this action manager has pointer triggers
  40096. * @return {boolean} whether or not it has pointer triggers
  40097. */
  40098. get: function () {
  40099. for (var index = 0; index < this.actions.length; index++) {
  40100. var action = this.actions[index];
  40101. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40102. return true;
  40103. }
  40104. }
  40105. return false;
  40106. },
  40107. enumerable: true,
  40108. configurable: true
  40109. });
  40110. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40111. /**
  40112. * Does this action manager has pick triggers
  40113. * @return {boolean} whether or not it has pick triggers
  40114. */
  40115. get: function () {
  40116. for (var index = 0; index < this.actions.length; index++) {
  40117. var action = this.actions[index];
  40118. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40119. return true;
  40120. }
  40121. }
  40122. return false;
  40123. },
  40124. enumerable: true,
  40125. configurable: true
  40126. });
  40127. Object.defineProperty(ActionManager, "HasTriggers", {
  40128. /**
  40129. * Does exist one action manager with at least one trigger
  40130. * @return {boolean} whether or not it exists one action manager with one trigger
  40131. **/
  40132. get: function () {
  40133. for (var t in ActionManager.Triggers) {
  40134. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40135. return true;
  40136. }
  40137. }
  40138. return false;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40144. /**
  40145. * Does exist one action manager with at least one pick trigger
  40146. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40147. **/
  40148. get: function () {
  40149. for (var t in ActionManager.Triggers) {
  40150. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40151. var t_int = parseInt(t);
  40152. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40153. return true;
  40154. }
  40155. }
  40156. }
  40157. return false;
  40158. },
  40159. enumerable: true,
  40160. configurable: true
  40161. });
  40162. /**
  40163. * Does exist one action manager that handles actions of a given trigger
  40164. * @param {number} trigger - the trigger to be tested
  40165. * @return {boolean} whether the trigger is handeled by at least one action manager
  40166. **/
  40167. ActionManager.HasSpecificTrigger = function (trigger) {
  40168. for (var t in ActionManager.Triggers) {
  40169. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40170. var t_int = parseInt(t);
  40171. if (t_int === trigger) {
  40172. return true;
  40173. }
  40174. }
  40175. }
  40176. return false;
  40177. };
  40178. /**
  40179. * Registers an action to this action manager
  40180. * @param {BABYLON.Action} action - the action to be registered
  40181. * @return {BABYLON.Action} the action amended (prepared) after registration
  40182. */
  40183. ActionManager.prototype.registerAction = function (action) {
  40184. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40185. if (this.getScene().actionManager !== this) {
  40186. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40187. return null;
  40188. }
  40189. }
  40190. this.actions.push(action);
  40191. if (ActionManager.Triggers[action.trigger]) {
  40192. ActionManager.Triggers[action.trigger]++;
  40193. }
  40194. else {
  40195. ActionManager.Triggers[action.trigger] = 1;
  40196. }
  40197. action._actionManager = this;
  40198. action._prepare();
  40199. return action;
  40200. };
  40201. /**
  40202. * Process a specific trigger
  40203. * @param {number} trigger - the trigger to process
  40204. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40205. */
  40206. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40207. for (var index = 0; index < this.actions.length; index++) {
  40208. var action = this.actions[index];
  40209. if (action.trigger === trigger) {
  40210. if (trigger === ActionManager.OnKeyUpTrigger
  40211. || trigger === ActionManager.OnKeyDownTrigger) {
  40212. var parameter = action.getTriggerParameter();
  40213. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40214. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40215. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40216. if (actualkey !== parameter.toLowerCase()) {
  40217. continue;
  40218. }
  40219. }
  40220. }
  40221. action._executeCurrent(evt);
  40222. }
  40223. }
  40224. };
  40225. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40226. var properties = propertyPath.split(".");
  40227. for (var index = 0; index < properties.length - 1; index++) {
  40228. target = target[properties[index]];
  40229. }
  40230. return target;
  40231. };
  40232. ActionManager.prototype._getProperty = function (propertyPath) {
  40233. var properties = propertyPath.split(".");
  40234. return properties[properties.length - 1];
  40235. };
  40236. ActionManager.prototype.serialize = function (name) {
  40237. var root = {
  40238. children: [],
  40239. name: name,
  40240. type: 3,
  40241. properties: [] // Empty for root but required
  40242. };
  40243. for (var i = 0; i < this.actions.length; i++) {
  40244. var triggerObject = {
  40245. type: 0,
  40246. children: [],
  40247. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40248. properties: []
  40249. };
  40250. var triggerOptions = this.actions[i].triggerOptions;
  40251. if (triggerOptions && typeof triggerOptions !== "number") {
  40252. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40253. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40254. }
  40255. else {
  40256. var parameter = {};
  40257. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40258. if (triggerOptions.parameter.mesh) {
  40259. parameter._meshId = triggerOptions.parameter.mesh.id;
  40260. }
  40261. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40262. }
  40263. }
  40264. // Serialize child action, recursively
  40265. this.actions[i].serialize(triggerObject);
  40266. // Add serialized trigger
  40267. root.children.push(triggerObject);
  40268. }
  40269. return root;
  40270. };
  40271. ActionManager.Parse = function (parsedActions, object, scene) {
  40272. var actionManager = new BABYLON.ActionManager(scene);
  40273. if (object === null)
  40274. scene.actionManager = actionManager;
  40275. else
  40276. object.actionManager = actionManager;
  40277. // instanciate a new object
  40278. var instanciate = function (name, params) {
  40279. var newInstance = Object.create(BABYLON[name].prototype);
  40280. newInstance.constructor.apply(newInstance, params);
  40281. return newInstance;
  40282. };
  40283. var parseParameter = function (name, value, target, propertyPath) {
  40284. if (propertyPath === null) {
  40285. // String, boolean or float
  40286. var floatValue = parseFloat(value);
  40287. if (value === "true" || value === "false")
  40288. return value === "true";
  40289. else
  40290. return isNaN(floatValue) ? value : floatValue;
  40291. }
  40292. var effectiveTarget = propertyPath.split(".");
  40293. var values = value.split(",");
  40294. // Get effective Target
  40295. for (var i = 0; i < effectiveTarget.length; i++) {
  40296. target = target[effectiveTarget[i]];
  40297. }
  40298. // Return appropriate value with its type
  40299. if (typeof (target) === "boolean")
  40300. return values[0] === "true";
  40301. if (typeof (target) === "string")
  40302. return values[0];
  40303. // Parameters with multiple values such as Vector3 etc.
  40304. var split = new Array();
  40305. for (var i = 0; i < values.length; i++)
  40306. split.push(parseFloat(values[i]));
  40307. if (target instanceof BABYLON.Vector3)
  40308. return BABYLON.Vector3.FromArray(split);
  40309. if (target instanceof BABYLON.Vector4)
  40310. return BABYLON.Vector4.FromArray(split);
  40311. if (target instanceof BABYLON.Color3)
  40312. return BABYLON.Color3.FromArray(split);
  40313. if (target instanceof BABYLON.Color4)
  40314. return BABYLON.Color4.FromArray(split);
  40315. return parseFloat(values[0]);
  40316. };
  40317. // traverse graph per trigger
  40318. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40319. if (combineArray === void 0) { combineArray = null; }
  40320. if (parsedAction.detached)
  40321. return;
  40322. var parameters = new Array();
  40323. var target = null;
  40324. var propertyPath = null;
  40325. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40326. // Parameters
  40327. if (parsedAction.type === 2)
  40328. parameters.push(actionManager);
  40329. else
  40330. parameters.push(trigger);
  40331. if (combine) {
  40332. var actions = new Array();
  40333. for (var j = 0; j < parsedAction.combine.length; j++) {
  40334. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40335. }
  40336. parameters.push(actions);
  40337. }
  40338. else {
  40339. for (var i = 0; i < parsedAction.properties.length; i++) {
  40340. var value = parsedAction.properties[i].value;
  40341. var name = parsedAction.properties[i].name;
  40342. var targetType = parsedAction.properties[i].targetType;
  40343. if (name === "target")
  40344. if (targetType !== null && targetType === "SceneProperties")
  40345. value = target = scene;
  40346. else
  40347. value = target = scene.getNodeByName(value);
  40348. else if (name === "parent")
  40349. value = scene.getNodeByName(value);
  40350. else if (name === "sound")
  40351. value = scene.getSoundByName(value);
  40352. else if (name !== "propertyPath") {
  40353. if (parsedAction.type === 2 && name === "operator")
  40354. value = BABYLON.ValueCondition[value];
  40355. else
  40356. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40357. }
  40358. else {
  40359. propertyPath = value;
  40360. }
  40361. parameters.push(value);
  40362. }
  40363. }
  40364. if (combineArray === null) {
  40365. parameters.push(condition);
  40366. }
  40367. else {
  40368. parameters.push(null);
  40369. }
  40370. // If interpolate value action
  40371. if (parsedAction.name === "InterpolateValueAction") {
  40372. var param = parameters[parameters.length - 2];
  40373. parameters[parameters.length - 1] = param;
  40374. parameters[parameters.length - 2] = condition;
  40375. }
  40376. // Action or condition(s) and not CombineAction
  40377. var newAction = instanciate(parsedAction.name, parameters);
  40378. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40379. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40380. if (action)
  40381. action.then(nothing);
  40382. else
  40383. actionManager.registerAction(nothing);
  40384. action = nothing;
  40385. }
  40386. if (combineArray === null) {
  40387. if (newAction instanceof BABYLON.Condition) {
  40388. condition = newAction;
  40389. newAction = action;
  40390. }
  40391. else {
  40392. condition = null;
  40393. if (action)
  40394. action.then(newAction);
  40395. else
  40396. actionManager.registerAction(newAction);
  40397. }
  40398. }
  40399. else {
  40400. combineArray.push(newAction);
  40401. }
  40402. for (var i = 0; i < parsedAction.children.length; i++)
  40403. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40404. };
  40405. // triggers
  40406. for (var i = 0; i < parsedActions.children.length; i++) {
  40407. var triggerParams;
  40408. var trigger = parsedActions.children[i];
  40409. if (trigger.properties.length > 0) {
  40410. var param = trigger.properties[0].value;
  40411. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40412. if (value._meshId) {
  40413. value.mesh = scene.getMeshByID(value._meshId);
  40414. }
  40415. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  40416. }
  40417. else
  40418. triggerParams = BABYLON.ActionManager[trigger.name];
  40419. for (var j = 0; j < trigger.children.length; j++) {
  40420. if (!trigger.detached)
  40421. traverse(trigger.children[j], triggerParams, null, null);
  40422. }
  40423. }
  40424. };
  40425. ActionManager.GetTriggerName = function (trigger) {
  40426. switch (trigger) {
  40427. case 0: return "NothingTrigger";
  40428. case 1: return "OnPickTrigger";
  40429. case 2: return "OnLeftPickTrigger";
  40430. case 3: return "OnRightPickTrigger";
  40431. case 4: return "OnCenterPickTrigger";
  40432. case 5: return "OnPickDownTrigger";
  40433. case 6: return "OnPickUpTrigger";
  40434. case 7: return "OnLongPressTrigger";
  40435. case 8: return "OnPointerOverTrigger";
  40436. case 9: return "OnPointerOutTrigger";
  40437. case 10: return "OnEveryFrameTrigger";
  40438. case 11: return "OnIntersectionEnterTrigger";
  40439. case 12: return "OnIntersectionExitTrigger";
  40440. case 13: return "OnKeyDownTrigger";
  40441. case 14: return "OnKeyUpTrigger";
  40442. case 15: return "OnPickOutTrigger";
  40443. default: return "";
  40444. }
  40445. };
  40446. return ActionManager;
  40447. }());
  40448. // Statics
  40449. ActionManager._NothingTrigger = 0;
  40450. ActionManager._OnPickTrigger = 1;
  40451. ActionManager._OnLeftPickTrigger = 2;
  40452. ActionManager._OnRightPickTrigger = 3;
  40453. ActionManager._OnCenterPickTrigger = 4;
  40454. ActionManager._OnPickDownTrigger = 5;
  40455. ActionManager._OnDoublePickTrigger = 6;
  40456. ActionManager._OnPickUpTrigger = 7;
  40457. ActionManager._OnLongPressTrigger = 8;
  40458. ActionManager._OnPointerOverTrigger = 9;
  40459. ActionManager._OnPointerOutTrigger = 10;
  40460. ActionManager._OnEveryFrameTrigger = 11;
  40461. ActionManager._OnIntersectionEnterTrigger = 12;
  40462. ActionManager._OnIntersectionExitTrigger = 13;
  40463. ActionManager._OnKeyDownTrigger = 14;
  40464. ActionManager._OnKeyUpTrigger = 15;
  40465. ActionManager._OnPickOutTrigger = 16;
  40466. ActionManager.Triggers = {};
  40467. BABYLON.ActionManager = ActionManager;
  40468. })(BABYLON || (BABYLON = {}));
  40469. //# sourceMappingURL=babylon.actionManager.js.map
  40470. var BABYLON;
  40471. (function (BABYLON) {
  40472. var InterpolateValueAction = (function (_super) {
  40473. __extends(InterpolateValueAction, _super);
  40474. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40475. if (duration === void 0) { duration = 1000; }
  40476. var _this = _super.call(this, triggerOptions, condition) || this;
  40477. _this.propertyPath = propertyPath;
  40478. _this.value = value;
  40479. _this.duration = duration;
  40480. _this.stopOtherAnimations = stopOtherAnimations;
  40481. _this.onInterpolationDone = onInterpolationDone;
  40482. _this._target = _this._effectiveTarget = target;
  40483. return _this;
  40484. }
  40485. InterpolateValueAction.prototype._prepare = function () {
  40486. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40487. this._property = this._getProperty(this.propertyPath);
  40488. };
  40489. InterpolateValueAction.prototype.execute = function () {
  40490. var scene = this._actionManager.getScene();
  40491. var keys = [
  40492. {
  40493. frame: 0,
  40494. value: this._effectiveTarget[this._property]
  40495. }, {
  40496. frame: 100,
  40497. value: this.value
  40498. }
  40499. ];
  40500. var dataType;
  40501. if (typeof this.value === "number") {
  40502. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40503. }
  40504. else if (this.value instanceof BABYLON.Color3) {
  40505. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40506. }
  40507. else if (this.value instanceof BABYLON.Vector3) {
  40508. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40509. }
  40510. else if (this.value instanceof BABYLON.Matrix) {
  40511. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40512. }
  40513. else if (this.value instanceof BABYLON.Quaternion) {
  40514. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40515. }
  40516. else {
  40517. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40518. return;
  40519. }
  40520. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40521. animation.setKeys(keys);
  40522. if (this.stopOtherAnimations) {
  40523. scene.stopAnimation(this._effectiveTarget);
  40524. }
  40525. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  40526. };
  40527. InterpolateValueAction.prototype.serialize = function (parent) {
  40528. return _super.prototype._serialize.call(this, {
  40529. name: "InterpolateValueAction",
  40530. properties: [
  40531. BABYLON.Action._GetTargetProperty(this._target),
  40532. { name: "propertyPath", value: this.propertyPath },
  40533. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40534. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40535. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40536. ]
  40537. }, parent);
  40538. };
  40539. return InterpolateValueAction;
  40540. }(BABYLON.Action));
  40541. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40542. })(BABYLON || (BABYLON = {}));
  40543. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40544. var BABYLON;
  40545. (function (BABYLON) {
  40546. var SwitchBooleanAction = (function (_super) {
  40547. __extends(SwitchBooleanAction, _super);
  40548. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40549. var _this = _super.call(this, triggerOptions, condition) || this;
  40550. _this.propertyPath = propertyPath;
  40551. _this._target = _this._effectiveTarget = target;
  40552. return _this;
  40553. }
  40554. SwitchBooleanAction.prototype._prepare = function () {
  40555. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40556. this._property = this._getProperty(this.propertyPath);
  40557. };
  40558. SwitchBooleanAction.prototype.execute = function () {
  40559. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40560. };
  40561. SwitchBooleanAction.prototype.serialize = function (parent) {
  40562. return _super.prototype._serialize.call(this, {
  40563. name: "SwitchBooleanAction",
  40564. properties: [
  40565. BABYLON.Action._GetTargetProperty(this._target),
  40566. { name: "propertyPath", value: this.propertyPath }
  40567. ]
  40568. }, parent);
  40569. };
  40570. return SwitchBooleanAction;
  40571. }(BABYLON.Action));
  40572. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40573. var SetStateAction = (function (_super) {
  40574. __extends(SetStateAction, _super);
  40575. function SetStateAction(triggerOptions, target, value, condition) {
  40576. var _this = _super.call(this, triggerOptions, condition) || this;
  40577. _this.value = value;
  40578. _this._target = target;
  40579. return _this;
  40580. }
  40581. SetStateAction.prototype.execute = function () {
  40582. this._target.state = this.value;
  40583. };
  40584. SetStateAction.prototype.serialize = function (parent) {
  40585. return _super.prototype._serialize.call(this, {
  40586. name: "SetStateAction",
  40587. properties: [
  40588. BABYLON.Action._GetTargetProperty(this._target),
  40589. { name: "value", value: this.value }
  40590. ]
  40591. }, parent);
  40592. };
  40593. return SetStateAction;
  40594. }(BABYLON.Action));
  40595. BABYLON.SetStateAction = SetStateAction;
  40596. var SetValueAction = (function (_super) {
  40597. __extends(SetValueAction, _super);
  40598. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40599. var _this = _super.call(this, triggerOptions, condition) || this;
  40600. _this.propertyPath = propertyPath;
  40601. _this.value = value;
  40602. _this._target = _this._effectiveTarget = target;
  40603. return _this;
  40604. }
  40605. SetValueAction.prototype._prepare = function () {
  40606. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40607. this._property = this._getProperty(this.propertyPath);
  40608. };
  40609. SetValueAction.prototype.execute = function () {
  40610. this._effectiveTarget[this._property] = this.value;
  40611. if (this._target.markAsDirty) {
  40612. this._target.markAsDirty(this._property);
  40613. }
  40614. };
  40615. SetValueAction.prototype.serialize = function (parent) {
  40616. return _super.prototype._serialize.call(this, {
  40617. name: "SetValueAction",
  40618. properties: [
  40619. BABYLON.Action._GetTargetProperty(this._target),
  40620. { name: "propertyPath", value: this.propertyPath },
  40621. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40622. ]
  40623. }, parent);
  40624. };
  40625. return SetValueAction;
  40626. }(BABYLON.Action));
  40627. BABYLON.SetValueAction = SetValueAction;
  40628. var IncrementValueAction = (function (_super) {
  40629. __extends(IncrementValueAction, _super);
  40630. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40631. var _this = _super.call(this, triggerOptions, condition) || this;
  40632. _this.propertyPath = propertyPath;
  40633. _this.value = value;
  40634. _this._target = _this._effectiveTarget = target;
  40635. return _this;
  40636. }
  40637. IncrementValueAction.prototype._prepare = function () {
  40638. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40639. this._property = this._getProperty(this.propertyPath);
  40640. if (typeof this._effectiveTarget[this._property] !== "number") {
  40641. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40642. }
  40643. };
  40644. IncrementValueAction.prototype.execute = function () {
  40645. this._effectiveTarget[this._property] += this.value;
  40646. if (this._target.markAsDirty) {
  40647. this._target.markAsDirty(this._property);
  40648. }
  40649. };
  40650. IncrementValueAction.prototype.serialize = function (parent) {
  40651. return _super.prototype._serialize.call(this, {
  40652. name: "IncrementValueAction",
  40653. properties: [
  40654. BABYLON.Action._GetTargetProperty(this._target),
  40655. { name: "propertyPath", value: this.propertyPath },
  40656. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40657. ]
  40658. }, parent);
  40659. };
  40660. return IncrementValueAction;
  40661. }(BABYLON.Action));
  40662. BABYLON.IncrementValueAction = IncrementValueAction;
  40663. var PlayAnimationAction = (function (_super) {
  40664. __extends(PlayAnimationAction, _super);
  40665. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40666. var _this = _super.call(this, triggerOptions, condition) || this;
  40667. _this.from = from;
  40668. _this.to = to;
  40669. _this.loop = loop;
  40670. _this._target = target;
  40671. return _this;
  40672. }
  40673. PlayAnimationAction.prototype._prepare = function () {
  40674. };
  40675. PlayAnimationAction.prototype.execute = function () {
  40676. var scene = this._actionManager.getScene();
  40677. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40678. };
  40679. PlayAnimationAction.prototype.serialize = function (parent) {
  40680. return _super.prototype._serialize.call(this, {
  40681. name: "PlayAnimationAction",
  40682. properties: [
  40683. BABYLON.Action._GetTargetProperty(this._target),
  40684. { name: "from", value: String(this.from) },
  40685. { name: "to", value: String(this.to) },
  40686. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40687. ]
  40688. }, parent);
  40689. };
  40690. return PlayAnimationAction;
  40691. }(BABYLON.Action));
  40692. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40693. var StopAnimationAction = (function (_super) {
  40694. __extends(StopAnimationAction, _super);
  40695. function StopAnimationAction(triggerOptions, target, condition) {
  40696. var _this = _super.call(this, triggerOptions, condition) || this;
  40697. _this._target = target;
  40698. return _this;
  40699. }
  40700. StopAnimationAction.prototype._prepare = function () {
  40701. };
  40702. StopAnimationAction.prototype.execute = function () {
  40703. var scene = this._actionManager.getScene();
  40704. scene.stopAnimation(this._target);
  40705. };
  40706. StopAnimationAction.prototype.serialize = function (parent) {
  40707. return _super.prototype._serialize.call(this, {
  40708. name: "StopAnimationAction",
  40709. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  40710. }, parent);
  40711. };
  40712. return StopAnimationAction;
  40713. }(BABYLON.Action));
  40714. BABYLON.StopAnimationAction = StopAnimationAction;
  40715. var DoNothingAction = (function (_super) {
  40716. __extends(DoNothingAction, _super);
  40717. function DoNothingAction(triggerOptions, condition) {
  40718. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  40719. return _super.call(this, triggerOptions, condition) || this;
  40720. }
  40721. DoNothingAction.prototype.execute = function () {
  40722. };
  40723. DoNothingAction.prototype.serialize = function (parent) {
  40724. return _super.prototype._serialize.call(this, {
  40725. name: "DoNothingAction",
  40726. properties: []
  40727. }, parent);
  40728. };
  40729. return DoNothingAction;
  40730. }(BABYLON.Action));
  40731. BABYLON.DoNothingAction = DoNothingAction;
  40732. var CombineAction = (function (_super) {
  40733. __extends(CombineAction, _super);
  40734. function CombineAction(triggerOptions, children, condition) {
  40735. var _this = _super.call(this, triggerOptions, condition) || this;
  40736. _this.children = children;
  40737. return _this;
  40738. }
  40739. CombineAction.prototype._prepare = function () {
  40740. for (var index = 0; index < this.children.length; index++) {
  40741. this.children[index]._actionManager = this._actionManager;
  40742. this.children[index]._prepare();
  40743. }
  40744. };
  40745. CombineAction.prototype.execute = function (evt) {
  40746. for (var index = 0; index < this.children.length; index++) {
  40747. this.children[index].execute(evt);
  40748. }
  40749. };
  40750. CombineAction.prototype.serialize = function (parent) {
  40751. var serializationObject = _super.prototype._serialize.call(this, {
  40752. name: "CombineAction",
  40753. properties: [],
  40754. combine: []
  40755. }, parent);
  40756. for (var i = 0; i < this.children.length; i++) {
  40757. serializationObject.combine.push(this.children[i].serialize(null));
  40758. }
  40759. return serializationObject;
  40760. };
  40761. return CombineAction;
  40762. }(BABYLON.Action));
  40763. BABYLON.CombineAction = CombineAction;
  40764. var ExecuteCodeAction = (function (_super) {
  40765. __extends(ExecuteCodeAction, _super);
  40766. function ExecuteCodeAction(triggerOptions, func, condition) {
  40767. var _this = _super.call(this, triggerOptions, condition) || this;
  40768. _this.func = func;
  40769. return _this;
  40770. }
  40771. ExecuteCodeAction.prototype.execute = function (evt) {
  40772. this.func(evt);
  40773. };
  40774. return ExecuteCodeAction;
  40775. }(BABYLON.Action));
  40776. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40777. var SetParentAction = (function (_super) {
  40778. __extends(SetParentAction, _super);
  40779. function SetParentAction(triggerOptions, target, parent, condition) {
  40780. var _this = _super.call(this, triggerOptions, condition) || this;
  40781. _this._target = target;
  40782. _this._parent = parent;
  40783. return _this;
  40784. }
  40785. SetParentAction.prototype._prepare = function () {
  40786. };
  40787. SetParentAction.prototype.execute = function () {
  40788. if (this._target.parent === this._parent) {
  40789. return;
  40790. }
  40791. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40792. invertParentWorldMatrix.invert();
  40793. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40794. this._target.parent = this._parent;
  40795. };
  40796. SetParentAction.prototype.serialize = function (parent) {
  40797. return _super.prototype._serialize.call(this, {
  40798. name: "SetParentAction",
  40799. properties: [
  40800. BABYLON.Action._GetTargetProperty(this._target),
  40801. BABYLON.Action._GetTargetProperty(this._parent),
  40802. ]
  40803. }, parent);
  40804. };
  40805. return SetParentAction;
  40806. }(BABYLON.Action));
  40807. BABYLON.SetParentAction = SetParentAction;
  40808. var PlaySoundAction = (function (_super) {
  40809. __extends(PlaySoundAction, _super);
  40810. function PlaySoundAction(triggerOptions, sound, condition) {
  40811. var _this = _super.call(this, triggerOptions, condition) || this;
  40812. _this._sound = sound;
  40813. return _this;
  40814. }
  40815. PlaySoundAction.prototype._prepare = function () {
  40816. };
  40817. PlaySoundAction.prototype.execute = function () {
  40818. if (this._sound !== undefined)
  40819. this._sound.play();
  40820. };
  40821. PlaySoundAction.prototype.serialize = function (parent) {
  40822. return _super.prototype._serialize.call(this, {
  40823. name: "PlaySoundAction",
  40824. properties: [{ name: "sound", value: this._sound.name }]
  40825. }, parent);
  40826. };
  40827. return PlaySoundAction;
  40828. }(BABYLON.Action));
  40829. BABYLON.PlaySoundAction = PlaySoundAction;
  40830. var StopSoundAction = (function (_super) {
  40831. __extends(StopSoundAction, _super);
  40832. function StopSoundAction(triggerOptions, sound, condition) {
  40833. var _this = _super.call(this, triggerOptions, condition) || this;
  40834. _this._sound = sound;
  40835. return _this;
  40836. }
  40837. StopSoundAction.prototype._prepare = function () {
  40838. };
  40839. StopSoundAction.prototype.execute = function () {
  40840. if (this._sound !== undefined)
  40841. this._sound.stop();
  40842. };
  40843. StopSoundAction.prototype.serialize = function (parent) {
  40844. return _super.prototype._serialize.call(this, {
  40845. name: "StopSoundAction",
  40846. properties: [{ name: "sound", value: this._sound.name }]
  40847. }, parent);
  40848. };
  40849. return StopSoundAction;
  40850. }(BABYLON.Action));
  40851. BABYLON.StopSoundAction = StopSoundAction;
  40852. })(BABYLON || (BABYLON = {}));
  40853. //# sourceMappingURL=babylon.directActions.js.map
  40854. var BABYLON;
  40855. (function (BABYLON) {
  40856. var Geometry = (function () {
  40857. function Geometry(id, scene, vertexData, updatable, mesh) {
  40858. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40859. this._totalVertices = 0;
  40860. this._isDisposed = false;
  40861. this.id = id;
  40862. this._engine = scene.getEngine();
  40863. this._meshes = [];
  40864. this._scene = scene;
  40865. //Init vertex buffer cache
  40866. this._vertexBuffers = {};
  40867. this._indices = [];
  40868. // vertexData
  40869. if (vertexData) {
  40870. this.setAllVerticesData(vertexData, updatable);
  40871. }
  40872. else {
  40873. this._totalVertices = 0;
  40874. this._indices = [];
  40875. }
  40876. if (this._engine.getCaps().vertexArrayObject) {
  40877. this._vertexArrayObjects = {};
  40878. }
  40879. // applyToMesh
  40880. if (mesh) {
  40881. if (mesh instanceof BABYLON.LinesMesh) {
  40882. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40883. this.updateExtend();
  40884. }
  40885. this.applyToMesh(mesh);
  40886. mesh.computeWorldMatrix(true);
  40887. }
  40888. }
  40889. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40890. /**
  40891. * 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
  40892. * @returns The Bias Vector
  40893. */
  40894. get: function () {
  40895. return this._boundingBias;
  40896. },
  40897. set: function (value) {
  40898. if (this._boundingBias && this._boundingBias.equals(value)) {
  40899. return;
  40900. }
  40901. this._boundingBias = value.clone();
  40902. this.updateBoundingInfo(true, null);
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. Object.defineProperty(Geometry.prototype, "extend", {
  40908. get: function () {
  40909. return this._extend;
  40910. },
  40911. enumerable: true,
  40912. configurable: true
  40913. });
  40914. Geometry.prototype.getScene = function () {
  40915. return this._scene;
  40916. };
  40917. Geometry.prototype.getEngine = function () {
  40918. return this._engine;
  40919. };
  40920. Geometry.prototype.isReady = function () {
  40921. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40922. };
  40923. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40924. get: function () {
  40925. for (var index = 0; index < this._meshes.length; index++) {
  40926. if (!this._meshes[index].doNotSerialize) {
  40927. return false;
  40928. }
  40929. }
  40930. return true;
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40936. vertexData.applyToGeometry(this, updatable);
  40937. this.notifyUpdate();
  40938. };
  40939. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40940. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40941. this.setVerticesBuffer(buffer);
  40942. };
  40943. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40944. var kind = buffer.getKind();
  40945. if (this._vertexBuffers[kind]) {
  40946. this._vertexBuffers[kind].dispose();
  40947. }
  40948. this._vertexBuffers[kind] = buffer;
  40949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40950. var data = buffer.getData();
  40951. var stride = buffer.getStrideSize();
  40952. this._totalVertices = data.length / stride;
  40953. this.updateExtend(data, stride);
  40954. var meshes = this._meshes;
  40955. var numOfMeshes = meshes.length;
  40956. for (var index = 0; index < numOfMeshes; index++) {
  40957. var mesh = meshes[index];
  40958. mesh._resetPointsArrayCache();
  40959. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40960. mesh._createGlobalSubMesh();
  40961. mesh.computeWorldMatrix(true);
  40962. }
  40963. }
  40964. this.notifyUpdate(kind);
  40965. if (this._vertexArrayObjects) {
  40966. this._disposeVertexArrayObjects();
  40967. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40968. }
  40969. };
  40970. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40971. var vertexBuffer = this.getVertexBuffer(kind);
  40972. if (!vertexBuffer) {
  40973. return;
  40974. }
  40975. vertexBuffer.updateDirectly(data, offset);
  40976. this.notifyUpdate(kind);
  40977. };
  40978. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40979. var vertexBuffer = this.getVertexBuffer(kind);
  40980. if (!vertexBuffer) {
  40981. return;
  40982. }
  40983. vertexBuffer.update(data);
  40984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40985. var stride = vertexBuffer.getStrideSize();
  40986. this._totalVertices = data.length / stride;
  40987. this.updateBoundingInfo(updateExtends, data);
  40988. }
  40989. this.notifyUpdate(kind);
  40990. };
  40991. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40992. if (updateExtends) {
  40993. this.updateExtend(data);
  40994. }
  40995. var meshes = this._meshes;
  40996. var numOfMeshes = meshes.length;
  40997. for (var index = 0; index < numOfMeshes; index++) {
  40998. var mesh = meshes[index];
  40999. mesh._resetPointsArrayCache();
  41000. if (updateExtends) {
  41001. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41002. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41003. var subMesh = mesh.subMeshes[subIndex];
  41004. subMesh.refreshBoundingInfo();
  41005. }
  41006. }
  41007. }
  41008. };
  41009. Geometry.prototype._bind = function (effect, indexToBind) {
  41010. if (indexToBind === void 0) { indexToBind = undefined; }
  41011. if (indexToBind === undefined) {
  41012. indexToBind = this._indexBuffer;
  41013. }
  41014. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  41015. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  41016. return;
  41017. }
  41018. // Using VAO
  41019. if (!this._vertexArrayObjects[effect.key]) {
  41020. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  41021. }
  41022. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  41023. };
  41024. Geometry.prototype.getTotalVertices = function () {
  41025. if (!this.isReady()) {
  41026. return 0;
  41027. }
  41028. return this._totalVertices;
  41029. };
  41030. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  41031. var vertexBuffer = this.getVertexBuffer(kind);
  41032. if (!vertexBuffer) {
  41033. return null;
  41034. }
  41035. var orig = vertexBuffer.getData();
  41036. if (!copyWhenShared || this._meshes.length === 1) {
  41037. return orig;
  41038. }
  41039. else {
  41040. var len = orig.length;
  41041. var copy = [];
  41042. for (var i = 0; i < len; i++) {
  41043. copy.push(orig[i]);
  41044. }
  41045. return copy;
  41046. }
  41047. };
  41048. Geometry.prototype.getVertexBuffer = function (kind) {
  41049. if (!this.isReady()) {
  41050. return null;
  41051. }
  41052. return this._vertexBuffers[kind];
  41053. };
  41054. Geometry.prototype.getVertexBuffers = function () {
  41055. if (!this.isReady()) {
  41056. return null;
  41057. }
  41058. return this._vertexBuffers;
  41059. };
  41060. Geometry.prototype.isVerticesDataPresent = function (kind) {
  41061. if (!this._vertexBuffers) {
  41062. if (this._delayInfo) {
  41063. return this._delayInfo.indexOf(kind) !== -1;
  41064. }
  41065. return false;
  41066. }
  41067. return this._vertexBuffers[kind] !== undefined;
  41068. };
  41069. Geometry.prototype.getVerticesDataKinds = function () {
  41070. var result = [];
  41071. var kind;
  41072. if (!this._vertexBuffers && this._delayInfo) {
  41073. for (kind in this._delayInfo) {
  41074. result.push(kind);
  41075. }
  41076. }
  41077. else {
  41078. for (kind in this._vertexBuffers) {
  41079. result.push(kind);
  41080. }
  41081. }
  41082. return result;
  41083. };
  41084. Geometry.prototype.setIndices = function (indices, totalVertices) {
  41085. if (this._indexBuffer) {
  41086. this._engine._releaseBuffer(this._indexBuffer);
  41087. }
  41088. this._disposeVertexArrayObjects();
  41089. this._indices = indices;
  41090. if (this._meshes.length !== 0 && this._indices) {
  41091. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41092. }
  41093. if (totalVertices !== undefined) {
  41094. this._totalVertices = totalVertices;
  41095. }
  41096. var meshes = this._meshes;
  41097. var numOfMeshes = meshes.length;
  41098. for (var index = 0; index < numOfMeshes; index++) {
  41099. meshes[index]._createGlobalSubMesh();
  41100. }
  41101. this.notifyUpdate();
  41102. };
  41103. Geometry.prototype.getTotalIndices = function () {
  41104. if (!this.isReady()) {
  41105. return 0;
  41106. }
  41107. return this._indices.length;
  41108. };
  41109. Geometry.prototype.getIndices = function (copyWhenShared) {
  41110. if (!this.isReady()) {
  41111. return null;
  41112. }
  41113. var orig = this._indices;
  41114. if (!copyWhenShared || this._meshes.length === 1) {
  41115. return orig;
  41116. }
  41117. else {
  41118. var len = orig.length;
  41119. var copy = [];
  41120. for (var i = 0; i < len; i++) {
  41121. copy.push(orig[i]);
  41122. }
  41123. return copy;
  41124. }
  41125. };
  41126. Geometry.prototype.getIndexBuffer = function () {
  41127. if (!this.isReady()) {
  41128. return null;
  41129. }
  41130. return this._indexBuffer;
  41131. };
  41132. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41133. var meshes = this._meshes;
  41134. var index = meshes.indexOf(mesh);
  41135. if (index === -1) {
  41136. return;
  41137. }
  41138. meshes.splice(index, 1);
  41139. mesh._geometry = null;
  41140. if (meshes.length === 0 && shouldDispose) {
  41141. this.dispose();
  41142. }
  41143. };
  41144. Geometry.prototype.applyToMesh = function (mesh) {
  41145. if (mesh._geometry === this) {
  41146. return;
  41147. }
  41148. var previousGeometry = mesh._geometry;
  41149. if (previousGeometry) {
  41150. previousGeometry.releaseForMesh(mesh);
  41151. }
  41152. var meshes = this._meshes;
  41153. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41154. mesh._geometry = this;
  41155. this._scene.pushGeometry(this);
  41156. meshes.push(mesh);
  41157. if (this.isReady()) {
  41158. this._applyToMesh(mesh);
  41159. }
  41160. else {
  41161. mesh._boundingInfo = this._boundingInfo;
  41162. }
  41163. };
  41164. Geometry.prototype.updateExtend = function (data, stride) {
  41165. if (data === void 0) { data = null; }
  41166. if (!data) {
  41167. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  41168. }
  41169. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  41170. };
  41171. Geometry.prototype._applyToMesh = function (mesh) {
  41172. var numOfMeshes = this._meshes.length;
  41173. // vertexBuffers
  41174. for (var kind in this._vertexBuffers) {
  41175. if (numOfMeshes === 1) {
  41176. this._vertexBuffers[kind].create();
  41177. }
  41178. var buffer = this._vertexBuffers[kind].getBuffer();
  41179. if (buffer)
  41180. buffer.references = numOfMeshes;
  41181. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41182. mesh._resetPointsArrayCache();
  41183. if (!this._extend) {
  41184. this.updateExtend(this._vertexBuffers[kind].getData());
  41185. }
  41186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41187. mesh._createGlobalSubMesh();
  41188. //bounding info was just created again, world matrix should be applied again.
  41189. mesh._updateBoundingInfo();
  41190. }
  41191. }
  41192. // indexBuffer
  41193. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41195. }
  41196. if (this._indexBuffer) {
  41197. this._indexBuffer.references = numOfMeshes;
  41198. }
  41199. };
  41200. Geometry.prototype.notifyUpdate = function (kind) {
  41201. if (this.onGeometryUpdated) {
  41202. this.onGeometryUpdated(this, kind);
  41203. }
  41204. };
  41205. Geometry.prototype.load = function (scene, onLoaded) {
  41206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41207. return;
  41208. }
  41209. if (this.isReady()) {
  41210. if (onLoaded) {
  41211. onLoaded();
  41212. }
  41213. return;
  41214. }
  41215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41216. this._queueLoad(scene, onLoaded);
  41217. };
  41218. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41219. var _this = this;
  41220. scene._addPendingData(this);
  41221. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  41222. _this._delayLoadingFunction(JSON.parse(data), _this);
  41223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41224. _this._delayInfo = [];
  41225. scene._removePendingData(_this);
  41226. var meshes = _this._meshes;
  41227. var numOfMeshes = meshes.length;
  41228. for (var index = 0; index < numOfMeshes; index++) {
  41229. _this._applyToMesh(meshes[index]);
  41230. }
  41231. if (onLoaded) {
  41232. onLoaded();
  41233. }
  41234. }, function () { }, scene.database);
  41235. };
  41236. /**
  41237. * Invert the geometry to move from a right handed system to a left handed one.
  41238. */
  41239. Geometry.prototype.toLeftHanded = function () {
  41240. // Flip faces
  41241. var tIndices = this.getIndices(false);
  41242. if (tIndices != null && tIndices.length > 0) {
  41243. for (var i = 0; i < tIndices.length; i += 3) {
  41244. var tTemp = tIndices[i + 0];
  41245. tIndices[i + 0] = tIndices[i + 2];
  41246. tIndices[i + 2] = tTemp;
  41247. }
  41248. this.setIndices(tIndices);
  41249. }
  41250. // Negate position.z
  41251. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41252. if (tPositions != null && tPositions.length > 0) {
  41253. for (var i = 0; i < tPositions.length; i += 3) {
  41254. tPositions[i + 2] = -tPositions[i + 2];
  41255. }
  41256. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41257. }
  41258. // Negate normal.z
  41259. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41260. if (tNormals != null && tNormals.length > 0) {
  41261. for (var i = 0; i < tNormals.length; i += 3) {
  41262. tNormals[i + 2] = -tNormals[i + 2];
  41263. }
  41264. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41265. }
  41266. };
  41267. Geometry.prototype.isDisposed = function () {
  41268. return this._isDisposed;
  41269. };
  41270. Geometry.prototype._disposeVertexArrayObjects = function () {
  41271. if (this._vertexArrayObjects) {
  41272. for (var kind in this._vertexArrayObjects) {
  41273. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41274. }
  41275. this._vertexArrayObjects = {};
  41276. }
  41277. };
  41278. Geometry.prototype.dispose = function () {
  41279. var meshes = this._meshes;
  41280. var numOfMeshes = meshes.length;
  41281. var index;
  41282. for (index = 0; index < numOfMeshes; index++) {
  41283. this.releaseForMesh(meshes[index]);
  41284. }
  41285. this._meshes = [];
  41286. this._disposeVertexArrayObjects();
  41287. for (var kind in this._vertexBuffers) {
  41288. this._vertexBuffers[kind].dispose();
  41289. }
  41290. this._vertexBuffers = {};
  41291. this._totalVertices = 0;
  41292. if (this._indexBuffer) {
  41293. this._engine._releaseBuffer(this._indexBuffer);
  41294. }
  41295. this._indexBuffer = null;
  41296. this._indices = [];
  41297. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41298. this.delayLoadingFile = null;
  41299. this._delayLoadingFunction = null;
  41300. this._delayInfo = [];
  41301. this._boundingInfo = null;
  41302. this._scene.removeGeometry(this);
  41303. this._isDisposed = true;
  41304. };
  41305. Geometry.prototype.copy = function (id) {
  41306. var vertexData = new BABYLON.VertexData();
  41307. vertexData.indices = [];
  41308. var indices = this.getIndices();
  41309. for (var index = 0; index < indices.length; index++) {
  41310. vertexData.indices.push(indices[index]);
  41311. }
  41312. var updatable = false;
  41313. var stopChecking = false;
  41314. var kind;
  41315. for (kind in this._vertexBuffers) {
  41316. // using slice() to make a copy of the array and not just reference it
  41317. var data = this.getVerticesData(kind);
  41318. if (data instanceof Float32Array) {
  41319. vertexData.set(new Float32Array(data), kind);
  41320. }
  41321. else {
  41322. vertexData.set(data.slice(0), kind);
  41323. }
  41324. if (!stopChecking) {
  41325. updatable = this.getVertexBuffer(kind).isUpdatable();
  41326. stopChecking = !updatable;
  41327. }
  41328. }
  41329. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  41330. geometry.delayLoadState = this.delayLoadState;
  41331. geometry.delayLoadingFile = this.delayLoadingFile;
  41332. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41333. for (kind in this._delayInfo) {
  41334. geometry._delayInfo = geometry._delayInfo || [];
  41335. geometry._delayInfo.push(kind);
  41336. }
  41337. // Bounding info
  41338. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41339. return geometry;
  41340. };
  41341. Geometry.prototype.serialize = function () {
  41342. var serializationObject = {};
  41343. serializationObject.id = this.id;
  41344. if (BABYLON.Tags.HasTags(this)) {
  41345. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41346. }
  41347. return serializationObject;
  41348. };
  41349. Geometry.prototype.serializeVerticeData = function () {
  41350. var serializationObject = this.serialize();
  41351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41352. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41353. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  41354. serializationObject.positions._updatable = true;
  41355. }
  41356. }
  41357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41358. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41359. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  41360. serializationObject.normals._updatable = true;
  41361. }
  41362. }
  41363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41364. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41365. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  41366. serializationObject.uvs._updatable = true;
  41367. }
  41368. }
  41369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41370. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  41371. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  41372. serializationObject.uv2s._updatable = true;
  41373. }
  41374. }
  41375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41376. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  41377. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  41378. serializationObject.uv3s._updatable = true;
  41379. }
  41380. }
  41381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41382. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  41383. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  41384. serializationObject.uv4s._updatable = true;
  41385. }
  41386. }
  41387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41388. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  41389. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  41390. serializationObject.uv5s._updatable = true;
  41391. }
  41392. }
  41393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41394. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  41395. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  41396. serializationObject.uv6s._updatable = true;
  41397. }
  41398. }
  41399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41400. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41401. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  41402. serializationObject.colors._updatable = true;
  41403. }
  41404. }
  41405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41406. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41407. serializationObject.matricesIndices._isExpanded = true;
  41408. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  41409. serializationObject.matricesIndices._updatable = true;
  41410. }
  41411. }
  41412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41413. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  41414. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  41415. serializationObject.matricesWeights._updatable = true;
  41416. }
  41417. }
  41418. serializationObject.indices = this.getIndices();
  41419. return serializationObject;
  41420. };
  41421. // Statics
  41422. Geometry.ExtractFromMesh = function (mesh, id) {
  41423. var geometry = mesh._geometry;
  41424. if (!geometry) {
  41425. return null;
  41426. }
  41427. return geometry.copy(id);
  41428. };
  41429. /**
  41430. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41431. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41432. * Be aware Math.random() could cause collisions, but:
  41433. * "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"
  41434. */
  41435. Geometry.RandomId = function () {
  41436. return BABYLON.Tools.RandomId();
  41437. };
  41438. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  41439. var scene = mesh.getScene();
  41440. // Geometry
  41441. var geometryId = parsedGeometry.geometryId;
  41442. if (geometryId) {
  41443. var geometry = scene.getGeometryByID(geometryId);
  41444. if (geometry) {
  41445. geometry.applyToMesh(mesh);
  41446. }
  41447. }
  41448. else if (parsedGeometry instanceof ArrayBuffer) {
  41449. var binaryInfo = mesh._binaryInfo;
  41450. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41451. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41452. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41453. }
  41454. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41455. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41456. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41457. }
  41458. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41459. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41460. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41461. }
  41462. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41463. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41464. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41465. }
  41466. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41467. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41468. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41469. }
  41470. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41471. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41472. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41473. }
  41474. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41475. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41476. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41477. }
  41478. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41479. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41480. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41481. }
  41482. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41483. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41484. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41485. }
  41486. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41487. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  41489. }
  41490. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41491. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41492. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41493. }
  41494. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41495. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41496. mesh.setIndices(indicesData);
  41497. }
  41498. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41499. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41500. mesh.subMeshes = [];
  41501. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41502. var materialIndex = subMeshesData[(i * 5) + 0];
  41503. var verticesStart = subMeshesData[(i * 5) + 1];
  41504. var verticesCount = subMeshesData[(i * 5) + 2];
  41505. var indexStart = subMeshesData[(i * 5) + 3];
  41506. var indexCount = subMeshesData[(i * 5) + 4];
  41507. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41508. }
  41509. }
  41510. }
  41511. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41512. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41513. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41514. if (parsedGeometry.uvs) {
  41515. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41516. }
  41517. if (parsedGeometry.uvs2) {
  41518. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41519. }
  41520. if (parsedGeometry.uvs3) {
  41521. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41522. }
  41523. if (parsedGeometry.uvs4) {
  41524. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41525. }
  41526. if (parsedGeometry.uvs5) {
  41527. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41528. }
  41529. if (parsedGeometry.uvs6) {
  41530. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41531. }
  41532. if (parsedGeometry.colors) {
  41533. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41534. }
  41535. if (parsedGeometry.matricesIndices) {
  41536. if (!parsedGeometry.matricesIndices._isExpanded) {
  41537. var floatIndices = [];
  41538. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41539. var matricesIndex = parsedGeometry.matricesIndices[i];
  41540. floatIndices.push(matricesIndex & 0x000000FF);
  41541. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41542. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41543. floatIndices.push(matricesIndex >> 24);
  41544. }
  41545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41546. }
  41547. else {
  41548. delete parsedGeometry.matricesIndices._isExpanded;
  41549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41550. }
  41551. }
  41552. if (parsedGeometry.matricesIndicesExtra) {
  41553. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41554. var floatIndices = [];
  41555. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41556. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41557. floatIndices.push(matricesIndex & 0x000000FF);
  41558. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41559. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41560. floatIndices.push(matricesIndex >> 24);
  41561. }
  41562. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41563. }
  41564. else {
  41565. delete parsedGeometry.matricesIndices._isExpanded;
  41566. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41567. }
  41568. }
  41569. if (parsedGeometry.matricesWeights) {
  41570. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41571. }
  41572. if (parsedGeometry.matricesWeightsExtra) {
  41573. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41574. }
  41575. mesh.setIndices(parsedGeometry.indices);
  41576. }
  41577. // SubMeshes
  41578. if (parsedGeometry.subMeshes) {
  41579. mesh.subMeshes = [];
  41580. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41581. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41582. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41583. }
  41584. }
  41585. // Flat shading
  41586. if (mesh._shouldGenerateFlatShading) {
  41587. mesh.convertToFlatShadedMesh();
  41588. delete mesh._shouldGenerateFlatShading;
  41589. }
  41590. // Update
  41591. mesh.computeWorldMatrix(true);
  41592. // Octree
  41593. if (scene['_selectionOctree']) {
  41594. scene['_selectionOctree'].addMesh(mesh);
  41595. }
  41596. };
  41597. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41598. if (scene.getGeometryByID(parsedVertexData.id)) {
  41599. return null; // null since geometry could be something else than a box...
  41600. }
  41601. var geometry = new Geometry(parsedVertexData.id, scene);
  41602. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41603. if (parsedVertexData.delayLoadingFile) {
  41604. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41605. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41606. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41607. geometry._delayInfo = [];
  41608. if (parsedVertexData.hasUVs) {
  41609. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41610. }
  41611. if (parsedVertexData.hasUVs2) {
  41612. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41613. }
  41614. if (parsedVertexData.hasUVs3) {
  41615. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41616. }
  41617. if (parsedVertexData.hasUVs4) {
  41618. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41619. }
  41620. if (parsedVertexData.hasUVs5) {
  41621. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41622. }
  41623. if (parsedVertexData.hasUVs6) {
  41624. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41625. }
  41626. if (parsedVertexData.hasColors) {
  41627. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41628. }
  41629. if (parsedVertexData.hasMatricesIndices) {
  41630. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41631. }
  41632. if (parsedVertexData.hasMatricesWeights) {
  41633. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41634. }
  41635. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41636. }
  41637. else {
  41638. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41639. }
  41640. scene.pushGeometry(geometry, true);
  41641. return geometry;
  41642. };
  41643. return Geometry;
  41644. }());
  41645. BABYLON.Geometry = Geometry;
  41646. /////// Primitives //////////////////////////////////////////////
  41647. (function (Geometry) {
  41648. var Primitives;
  41649. (function (Primitives) {
  41650. /// Abstract class
  41651. var _Primitive = (function (_super) {
  41652. __extends(_Primitive, _super);
  41653. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  41654. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  41655. _this._canBeRegenerated = _canBeRegenerated;
  41656. _this._beingRegenerated = true;
  41657. _this.regenerate();
  41658. _this._beingRegenerated = false;
  41659. return _this;
  41660. }
  41661. _Primitive.prototype.canBeRegenerated = function () {
  41662. return this._canBeRegenerated;
  41663. };
  41664. _Primitive.prototype.regenerate = function () {
  41665. if (!this._canBeRegenerated) {
  41666. return;
  41667. }
  41668. this._beingRegenerated = true;
  41669. this.setAllVerticesData(this._regenerateVertexData(), false);
  41670. this._beingRegenerated = false;
  41671. };
  41672. _Primitive.prototype.asNewGeometry = function (id) {
  41673. return _super.prototype.copy.call(this, id);
  41674. };
  41675. // overrides
  41676. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  41677. if (!this._beingRegenerated) {
  41678. return;
  41679. }
  41680. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41681. };
  41682. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  41683. if (!this._beingRegenerated) {
  41684. return;
  41685. }
  41686. _super.prototype.setVerticesData.call(this, kind, data, false);
  41687. };
  41688. // to override
  41689. // protected
  41690. _Primitive.prototype._regenerateVertexData = function () {
  41691. throw new Error("Abstract method");
  41692. };
  41693. _Primitive.prototype.copy = function (id) {
  41694. throw new Error("Must be overriden in sub-classes.");
  41695. };
  41696. _Primitive.prototype.serialize = function () {
  41697. var serializationObject = _super.prototype.serialize.call(this);
  41698. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41699. return serializationObject;
  41700. };
  41701. return _Primitive;
  41702. }(Geometry));
  41703. Primitives._Primitive = _Primitive;
  41704. var Ribbon = (function (_super) {
  41705. __extends(Ribbon, _super);
  41706. // Members
  41707. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  41708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41709. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41710. _this.pathArray = pathArray;
  41711. _this.closeArray = closeArray;
  41712. _this.closePath = closePath;
  41713. _this.offset = offset;
  41714. _this.side = side;
  41715. return _this;
  41716. }
  41717. Ribbon.prototype._regenerateVertexData = function () {
  41718. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41719. };
  41720. Ribbon.prototype.copy = function (id) {
  41721. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  41722. };
  41723. return Ribbon;
  41724. }(_Primitive));
  41725. Primitives.Ribbon = Ribbon;
  41726. var Box = (function (_super) {
  41727. __extends(Box, _super);
  41728. // Members
  41729. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  41730. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41731. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41732. _this.size = size;
  41733. _this.side = side;
  41734. return _this;
  41735. }
  41736. Box.prototype._regenerateVertexData = function () {
  41737. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41738. };
  41739. Box.prototype.copy = function (id) {
  41740. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41741. };
  41742. Box.prototype.serialize = function () {
  41743. var serializationObject = _super.prototype.serialize.call(this);
  41744. serializationObject.size = this.size;
  41745. return serializationObject;
  41746. };
  41747. Box.Parse = function (parsedBox, scene) {
  41748. if (scene.getGeometryByID(parsedBox.id)) {
  41749. return null; // null since geometry could be something else than a box...
  41750. }
  41751. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41752. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41753. scene.pushGeometry(box, true);
  41754. return box;
  41755. };
  41756. return Box;
  41757. }(_Primitive));
  41758. Primitives.Box = Box;
  41759. var Sphere = (function (_super) {
  41760. __extends(Sphere, _super);
  41761. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  41762. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41763. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41764. _this.segments = segments;
  41765. _this.diameter = diameter;
  41766. _this.side = side;
  41767. return _this;
  41768. }
  41769. Sphere.prototype._regenerateVertexData = function () {
  41770. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41771. };
  41772. Sphere.prototype.copy = function (id) {
  41773. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41774. };
  41775. Sphere.prototype.serialize = function () {
  41776. var serializationObject = _super.prototype.serialize.call(this);
  41777. serializationObject.segments = this.segments;
  41778. serializationObject.diameter = this.diameter;
  41779. return serializationObject;
  41780. };
  41781. Sphere.Parse = function (parsedSphere, scene) {
  41782. if (scene.getGeometryByID(parsedSphere.id)) {
  41783. return null; // null since geometry could be something else than a sphere...
  41784. }
  41785. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41786. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41787. scene.pushGeometry(sphere, true);
  41788. return sphere;
  41789. };
  41790. return Sphere;
  41791. }(_Primitive));
  41792. Primitives.Sphere = Sphere;
  41793. var Disc = (function (_super) {
  41794. __extends(Disc, _super);
  41795. // Members
  41796. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41798. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41799. _this.radius = radius;
  41800. _this.tessellation = tessellation;
  41801. _this.side = side;
  41802. return _this;
  41803. }
  41804. Disc.prototype._regenerateVertexData = function () {
  41805. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41806. };
  41807. Disc.prototype.copy = function (id) {
  41808. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41809. };
  41810. return Disc;
  41811. }(_Primitive));
  41812. Primitives.Disc = Disc;
  41813. var Cylinder = (function (_super) {
  41814. __extends(Cylinder, _super);
  41815. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41816. if (subdivisions === void 0) { subdivisions = 1; }
  41817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41819. _this.height = height;
  41820. _this.diameterTop = diameterTop;
  41821. _this.diameterBottom = diameterBottom;
  41822. _this.tessellation = tessellation;
  41823. _this.subdivisions = subdivisions;
  41824. _this.side = side;
  41825. return _this;
  41826. }
  41827. Cylinder.prototype._regenerateVertexData = function () {
  41828. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41829. };
  41830. Cylinder.prototype.copy = function (id) {
  41831. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41832. };
  41833. Cylinder.prototype.serialize = function () {
  41834. var serializationObject = _super.prototype.serialize.call(this);
  41835. serializationObject.height = this.height;
  41836. serializationObject.diameterTop = this.diameterTop;
  41837. serializationObject.diameterBottom = this.diameterBottom;
  41838. serializationObject.tessellation = this.tessellation;
  41839. return serializationObject;
  41840. };
  41841. Cylinder.Parse = function (parsedCylinder, scene) {
  41842. if (scene.getGeometryByID(parsedCylinder.id)) {
  41843. return null; // null since geometry could be something else than a cylinder...
  41844. }
  41845. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41846. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41847. scene.pushGeometry(cylinder, true);
  41848. return cylinder;
  41849. };
  41850. return Cylinder;
  41851. }(_Primitive));
  41852. Primitives.Cylinder = Cylinder;
  41853. var Torus = (function (_super) {
  41854. __extends(Torus, _super);
  41855. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41857. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41858. _this.diameter = diameter;
  41859. _this.thickness = thickness;
  41860. _this.tessellation = tessellation;
  41861. _this.side = side;
  41862. return _this;
  41863. }
  41864. Torus.prototype._regenerateVertexData = function () {
  41865. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41866. };
  41867. Torus.prototype.copy = function (id) {
  41868. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41869. };
  41870. Torus.prototype.serialize = function () {
  41871. var serializationObject = _super.prototype.serialize.call(this);
  41872. serializationObject.diameter = this.diameter;
  41873. serializationObject.thickness = this.thickness;
  41874. serializationObject.tessellation = this.tessellation;
  41875. return serializationObject;
  41876. };
  41877. Torus.Parse = function (parsedTorus, scene) {
  41878. if (scene.getGeometryByID(parsedTorus.id)) {
  41879. return null; // null since geometry could be something else than a torus...
  41880. }
  41881. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41882. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41883. scene.pushGeometry(torus, true);
  41884. return torus;
  41885. };
  41886. return Torus;
  41887. }(_Primitive));
  41888. Primitives.Torus = Torus;
  41889. var Ground = (function (_super) {
  41890. __extends(Ground, _super);
  41891. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41892. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41893. _this.width = width;
  41894. _this.height = height;
  41895. _this.subdivisions = subdivisions;
  41896. return _this;
  41897. }
  41898. Ground.prototype._regenerateVertexData = function () {
  41899. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41900. };
  41901. Ground.prototype.copy = function (id) {
  41902. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41903. };
  41904. Ground.prototype.serialize = function () {
  41905. var serializationObject = _super.prototype.serialize.call(this);
  41906. serializationObject.width = this.width;
  41907. serializationObject.height = this.height;
  41908. serializationObject.subdivisions = this.subdivisions;
  41909. return serializationObject;
  41910. };
  41911. Ground.Parse = function (parsedGround, scene) {
  41912. if (scene.getGeometryByID(parsedGround.id)) {
  41913. return null; // null since geometry could be something else than a ground...
  41914. }
  41915. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41916. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41917. scene.pushGeometry(ground, true);
  41918. return ground;
  41919. };
  41920. return Ground;
  41921. }(_Primitive));
  41922. Primitives.Ground = Ground;
  41923. var TiledGround = (function (_super) {
  41924. __extends(TiledGround, _super);
  41925. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41927. _this.xmin = xmin;
  41928. _this.zmin = zmin;
  41929. _this.xmax = xmax;
  41930. _this.zmax = zmax;
  41931. _this.subdivisions = subdivisions;
  41932. _this.precision = precision;
  41933. return _this;
  41934. }
  41935. TiledGround.prototype._regenerateVertexData = function () {
  41936. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41937. };
  41938. TiledGround.prototype.copy = function (id) {
  41939. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41940. };
  41941. return TiledGround;
  41942. }(_Primitive));
  41943. Primitives.TiledGround = TiledGround;
  41944. var Plane = (function (_super) {
  41945. __extends(Plane, _super);
  41946. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41948. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41949. _this.size = size;
  41950. _this.side = side;
  41951. return _this;
  41952. }
  41953. Plane.prototype._regenerateVertexData = function () {
  41954. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41955. };
  41956. Plane.prototype.copy = function (id) {
  41957. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41958. };
  41959. Plane.prototype.serialize = function () {
  41960. var serializationObject = _super.prototype.serialize.call(this);
  41961. serializationObject.size = this.size;
  41962. return serializationObject;
  41963. };
  41964. Plane.Parse = function (parsedPlane, scene) {
  41965. if (scene.getGeometryByID(parsedPlane.id)) {
  41966. return null; // null since geometry could be something else than a ground...
  41967. }
  41968. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41969. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41970. scene.pushGeometry(plane, true);
  41971. return plane;
  41972. };
  41973. return Plane;
  41974. }(_Primitive));
  41975. Primitives.Plane = Plane;
  41976. var TorusKnot = (function (_super) {
  41977. __extends(TorusKnot, _super);
  41978. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41979. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41980. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41981. _this.radius = radius;
  41982. _this.tube = tube;
  41983. _this.radialSegments = radialSegments;
  41984. _this.tubularSegments = tubularSegments;
  41985. _this.p = p;
  41986. _this.q = q;
  41987. _this.side = side;
  41988. return _this;
  41989. }
  41990. TorusKnot.prototype._regenerateVertexData = function () {
  41991. 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 });
  41992. };
  41993. TorusKnot.prototype.copy = function (id) {
  41994. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41995. };
  41996. TorusKnot.prototype.serialize = function () {
  41997. var serializationObject = _super.prototype.serialize.call(this);
  41998. serializationObject.radius = this.radius;
  41999. serializationObject.tube = this.tube;
  42000. serializationObject.radialSegments = this.radialSegments;
  42001. serializationObject.tubularSegments = this.tubularSegments;
  42002. serializationObject.p = this.p;
  42003. serializationObject.q = this.q;
  42004. return serializationObject;
  42005. };
  42006. ;
  42007. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  42008. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42009. return null; // null since geometry could be something else than a ground...
  42010. }
  42011. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42012. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42013. scene.pushGeometry(torusKnot, true);
  42014. return torusKnot;
  42015. };
  42016. return TorusKnot;
  42017. }(_Primitive));
  42018. Primitives.TorusKnot = TorusKnot;
  42019. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  42020. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  42021. })(BABYLON || (BABYLON = {}));
  42022. //# sourceMappingURL=babylon.geometry.js.map
  42023. /// <reference path="babylon.mesh.ts" />
  42024. var BABYLON;
  42025. (function (BABYLON) {
  42026. var GroundMesh = (function (_super) {
  42027. __extends(GroundMesh, _super);
  42028. function GroundMesh(name, scene) {
  42029. var _this = _super.call(this, name, scene) || this;
  42030. _this.generateOctree = false;
  42031. _this._worldInverse = new BABYLON.Matrix();
  42032. return _this;
  42033. }
  42034. GroundMesh.prototype.getClassName = function () {
  42035. return "GroundMesh";
  42036. };
  42037. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42038. get: function () {
  42039. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42040. },
  42041. enumerable: true,
  42042. configurable: true
  42043. });
  42044. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42045. get: function () {
  42046. return this._subdivisionsX;
  42047. },
  42048. enumerable: true,
  42049. configurable: true
  42050. });
  42051. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42052. get: function () {
  42053. return this._subdivisionsY;
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42059. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42060. this._subdivisionsX = chunksCount;
  42061. this._subdivisionsY = chunksCount;
  42062. this.subdivide(chunksCount);
  42063. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42064. };
  42065. /**
  42066. * Returns a height (y) value in the Worl system :
  42067. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42068. * Returns the ground y position if (x, z) are outside the ground surface.
  42069. */
  42070. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42071. var world = this.getWorldMatrix();
  42072. var invMat = BABYLON.Tmp.Matrix[5];
  42073. world.invertToRef(invMat);
  42074. var tmpVect = BABYLON.Tmp.Vector3[8];
  42075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42076. x = tmpVect.x;
  42077. z = tmpVect.z;
  42078. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42079. return this.position.y;
  42080. }
  42081. if (!this._heightQuads || this._heightQuads.length == 0) {
  42082. this._initHeightQuads();
  42083. this._computeHeightQuads();
  42084. }
  42085. var facet = this._getFacetAt(x, z);
  42086. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42087. // return y in the World system
  42088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42089. return tmpVect.y;
  42090. };
  42091. /**
  42092. * Returns a normalized vector (Vector3) orthogonal to the ground
  42093. * at the ground coordinates (x, z) expressed in the World system.
  42094. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42095. */
  42096. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42097. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42098. this.getNormalAtCoordinatesToRef(x, z, normal);
  42099. return normal;
  42100. };
  42101. /**
  42102. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42103. * at the ground coordinates (x, z) expressed in the World system.
  42104. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42105. * Returns the GroundMesh.
  42106. */
  42107. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42108. var world = this.getWorldMatrix();
  42109. var tmpMat = BABYLON.Tmp.Matrix[5];
  42110. world.invertToRef(tmpMat);
  42111. var tmpVect = BABYLON.Tmp.Vector3[8];
  42112. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42113. x = tmpVect.x;
  42114. z = tmpVect.z;
  42115. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42116. return this;
  42117. }
  42118. if (!this._heightQuads || this._heightQuads.length == 0) {
  42119. this._initHeightQuads();
  42120. this._computeHeightQuads();
  42121. }
  42122. var facet = this._getFacetAt(x, z);
  42123. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42124. return this;
  42125. };
  42126. /**
  42127. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42128. * if the ground has been updated.
  42129. * This can be used in the render loop.
  42130. * Returns the GroundMesh.
  42131. */
  42132. GroundMesh.prototype.updateCoordinateHeights = function () {
  42133. if (!this._heightQuads || this._heightQuads.length == 0) {
  42134. this._initHeightQuads();
  42135. }
  42136. this._computeHeightQuads();
  42137. return this;
  42138. };
  42139. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42140. GroundMesh.prototype._getFacetAt = function (x, z) {
  42141. // retrieve col and row from x, z coordinates in the ground local system
  42142. var subdivisionsX = this._subdivisionsX;
  42143. var subdivisionsY = this._subdivisionsY;
  42144. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42145. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42146. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42147. var facet;
  42148. if (z < quad.slope.x * x + quad.slope.y) {
  42149. facet = quad.facet1;
  42150. }
  42151. else {
  42152. facet = quad.facet2;
  42153. }
  42154. return facet;
  42155. };
  42156. // Creates and populates the heightMap array with "facet" elements :
  42157. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42158. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42159. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42160. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42161. // Returns the GroundMesh.
  42162. GroundMesh.prototype._initHeightQuads = function () {
  42163. var subdivisionsX = this._subdivisionsX;
  42164. var subdivisionsY = this._subdivisionsY;
  42165. this._heightQuads = new Array();
  42166. for (var row = 0; row < subdivisionsY; row++) {
  42167. for (var col = 0; col < subdivisionsX; col++) {
  42168. 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) };
  42169. this._heightQuads[row * subdivisionsX + col] = quad;
  42170. }
  42171. }
  42172. return this;
  42173. };
  42174. // Compute each quad element values and update the the heightMap array :
  42175. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42176. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42177. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42178. // Returns the GroundMesh.
  42179. GroundMesh.prototype._computeHeightQuads = function () {
  42180. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42181. var v1 = BABYLON.Tmp.Vector3[3];
  42182. var v2 = BABYLON.Tmp.Vector3[2];
  42183. var v3 = BABYLON.Tmp.Vector3[1];
  42184. var v4 = BABYLON.Tmp.Vector3[0];
  42185. var v1v2 = BABYLON.Tmp.Vector3[4];
  42186. var v1v3 = BABYLON.Tmp.Vector3[5];
  42187. var v1v4 = BABYLON.Tmp.Vector3[6];
  42188. var norm1 = BABYLON.Tmp.Vector3[7];
  42189. var norm2 = BABYLON.Tmp.Vector3[8];
  42190. var i = 0;
  42191. var j = 0;
  42192. var k = 0;
  42193. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42194. var h = 0;
  42195. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42196. var d2 = 0;
  42197. var subdivisionsX = this._subdivisionsX;
  42198. var subdivisionsY = this._subdivisionsY;
  42199. for (var row = 0; row < subdivisionsY; row++) {
  42200. for (var col = 0; col < subdivisionsX; col++) {
  42201. i = col * 3;
  42202. j = row * (subdivisionsX + 1) * 3;
  42203. k = (row + 1) * (subdivisionsX + 1) * 3;
  42204. v1.x = positions[j + i];
  42205. v1.y = positions[j + i + 1];
  42206. v1.z = positions[j + i + 2];
  42207. v2.x = positions[j + i + 3];
  42208. v2.y = positions[j + i + 4];
  42209. v2.z = positions[j + i + 5];
  42210. v3.x = positions[k + i];
  42211. v3.y = positions[k + i + 1];
  42212. v3.z = positions[k + i + 2];
  42213. v4.x = positions[k + i + 3];
  42214. v4.y = positions[k + i + 4];
  42215. v4.z = positions[k + i + 5];
  42216. // 2D slope V1V4
  42217. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42218. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42219. // facet equations :
  42220. // we compute each facet normal vector
  42221. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42222. // we compute the value d by applying the equation to v1 which belongs to the plane
  42223. // then we store the facet equation in a Vector4
  42224. v2.subtractToRef(v1, v1v2);
  42225. v3.subtractToRef(v1, v1v3);
  42226. v4.subtractToRef(v1, v1v4);
  42227. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42228. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42229. norm1.normalize();
  42230. norm2.normalize();
  42231. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42232. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42233. var quad = this._heightQuads[row * subdivisionsX + col];
  42234. quad.slope.copyFromFloats(cd, h);
  42235. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42236. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42237. }
  42238. }
  42239. return this;
  42240. };
  42241. GroundMesh.prototype.serialize = function (serializationObject) {
  42242. _super.prototype.serialize.call(this, serializationObject);
  42243. serializationObject.subdivisionsX = this._subdivisionsX;
  42244. serializationObject.subdivisionsY = this._subdivisionsY;
  42245. serializationObject.minX = this._minX;
  42246. serializationObject.maxX = this._maxX;
  42247. serializationObject.minZ = this._minZ;
  42248. serializationObject.maxZ = this._maxZ;
  42249. serializationObject.width = this._width;
  42250. serializationObject.height = this._height;
  42251. };
  42252. GroundMesh.Parse = function (parsedMesh, scene) {
  42253. var result = new GroundMesh(parsedMesh.name, scene);
  42254. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42255. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42256. result._minX = parsedMesh.minX;
  42257. result._maxX = parsedMesh.maxX;
  42258. result._minZ = parsedMesh.minZ;
  42259. result._maxZ = parsedMesh.maxZ;
  42260. result._width = parsedMesh.width;
  42261. result._height = parsedMesh.height;
  42262. return result;
  42263. };
  42264. return GroundMesh;
  42265. }(BABYLON.Mesh));
  42266. BABYLON.GroundMesh = GroundMesh;
  42267. })(BABYLON || (BABYLON = {}));
  42268. //# sourceMappingURL=babylon.groundMesh.js.map
  42269. /// <reference path="babylon.mesh.ts" />
  42270. var BABYLON;
  42271. (function (BABYLON) {
  42272. var LinesMesh = (function (_super) {
  42273. __extends(LinesMesh, _super);
  42274. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  42275. if (parent === void 0) { parent = null; }
  42276. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42277. _this.color = new BABYLON.Color3(1, 1, 1);
  42278. _this.alpha = 1;
  42279. _this._positionBuffer = {};
  42280. if (source) {
  42281. _this.color = source.color.clone();
  42282. _this.alpha = source.alpha;
  42283. }
  42284. _this._intersectionThreshold = 0.1;
  42285. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  42286. attributes: [BABYLON.VertexBuffer.PositionKind],
  42287. uniforms: ["worldViewProjection", "color"],
  42288. needAlphaBlending: true
  42289. });
  42290. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  42291. return _this;
  42292. }
  42293. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42294. /**
  42295. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42296. * This margin is expressed in world space coordinates, so its value may vary.
  42297. * Default value is 0.1
  42298. * @returns the intersection Threshold value.
  42299. */
  42300. get: function () {
  42301. return this._intersectionThreshold;
  42302. },
  42303. /**
  42304. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42305. * This margin is expressed in world space coordinates, so its value may vary.
  42306. * @param value the new threshold to apply
  42307. */
  42308. set: function (value) {
  42309. if (this._intersectionThreshold === value) {
  42310. return;
  42311. }
  42312. this._intersectionThreshold = value;
  42313. if (this.geometry) {
  42314. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42315. }
  42316. },
  42317. enumerable: true,
  42318. configurable: true
  42319. });
  42320. /**
  42321. * Returns the string "LineMesh"
  42322. */
  42323. LinesMesh.prototype.getClassName = function () {
  42324. return "LinesMesh";
  42325. };
  42326. Object.defineProperty(LinesMesh.prototype, "material", {
  42327. get: function () {
  42328. return this._colorShader;
  42329. },
  42330. enumerable: true,
  42331. configurable: true
  42332. });
  42333. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42334. get: function () {
  42335. return false;
  42336. },
  42337. enumerable: true,
  42338. configurable: true
  42339. });
  42340. LinesMesh.prototype.createInstance = function (name) {
  42341. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42342. return null;
  42343. };
  42344. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42345. var engine = this.getScene().getEngine();
  42346. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  42347. // VBOs
  42348. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  42349. // Color
  42350. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42351. return this;
  42352. };
  42353. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42354. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42355. return this;
  42356. }
  42357. var engine = this.getScene().getEngine();
  42358. // Draw order
  42359. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42360. return this;
  42361. };
  42362. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42363. this._colorShader.dispose();
  42364. _super.prototype.dispose.call(this, doNotRecurse);
  42365. };
  42366. /**
  42367. * Returns a new LineMesh object cloned from the current one.
  42368. */
  42369. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42370. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42371. };
  42372. return LinesMesh;
  42373. }(BABYLON.Mesh));
  42374. BABYLON.LinesMesh = LinesMesh;
  42375. })(BABYLON || (BABYLON = {}));
  42376. //# sourceMappingURL=babylon.linesMesh.js.map
  42377. var BABYLON;
  42378. (function (BABYLON) {
  42379. var DefaultLoadingScreen = (function () {
  42380. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42381. if (_loadingText === void 0) { _loadingText = ""; }
  42382. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42383. var _this = this;
  42384. this._renderingCanvas = _renderingCanvas;
  42385. this._loadingText = _loadingText;
  42386. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42387. // Resize
  42388. this._resizeLoadingUI = function () {
  42389. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42390. _this._loadingDiv.style.position = "absolute";
  42391. _this._loadingDiv.style.left = canvasRect.left + "px";
  42392. _this._loadingDiv.style.top = canvasRect.top + "px";
  42393. _this._loadingDiv.style.width = canvasRect.width + "px";
  42394. _this._loadingDiv.style.height = canvasRect.height + "px";
  42395. };
  42396. }
  42397. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42398. var _this = this;
  42399. if (this._loadingDiv) {
  42400. // Do not add a loading screen if there is already one
  42401. return;
  42402. }
  42403. this._loadingDiv = document.createElement("div");
  42404. this._loadingDiv.id = "babylonjsLoadingDiv";
  42405. this._loadingDiv.style.opacity = "0";
  42406. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42407. // Loading text
  42408. this._loadingTextDiv = document.createElement("div");
  42409. this._loadingTextDiv.style.position = "absolute";
  42410. this._loadingTextDiv.style.left = "0";
  42411. this._loadingTextDiv.style.top = "50%";
  42412. this._loadingTextDiv.style.marginTop = "80px";
  42413. this._loadingTextDiv.style.width = "100%";
  42414. this._loadingTextDiv.style.height = "20px";
  42415. this._loadingTextDiv.style.fontFamily = "Arial";
  42416. this._loadingTextDiv.style.fontSize = "14px";
  42417. this._loadingTextDiv.style.color = "white";
  42418. this._loadingTextDiv.style.textAlign = "center";
  42419. this._loadingTextDiv.innerHTML = "Loading";
  42420. this._loadingDiv.appendChild(this._loadingTextDiv);
  42421. //set the predefined text
  42422. this._loadingTextDiv.innerHTML = this._loadingText;
  42423. // Loading img
  42424. var imgBack = new Image();
  42425. 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==";
  42426. imgBack.style.position = "absolute";
  42427. imgBack.style.left = "50%";
  42428. imgBack.style.top = "50%";
  42429. imgBack.style.marginLeft = "-50px";
  42430. imgBack.style.marginTop = "-50px";
  42431. imgBack.style.transition = "transform 1.0s ease";
  42432. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42433. var deg = 360;
  42434. var onTransitionEnd = function () {
  42435. deg += 360;
  42436. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42437. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42438. };
  42439. imgBack.addEventListener("transitionend", onTransitionEnd);
  42440. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42441. this._loadingDiv.appendChild(imgBack);
  42442. // front image
  42443. var imgFront = new Image();
  42444. 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=";
  42445. imgFront.style.position = "absolute";
  42446. imgFront.style.left = "50%";
  42447. imgFront.style.top = "50%";
  42448. imgFront.style.marginLeft = "-50px";
  42449. imgFront.style.marginTop = "-50px";
  42450. this._loadingDiv.appendChild(imgFront);
  42451. this._resizeLoadingUI();
  42452. window.addEventListener("resize", this._resizeLoadingUI);
  42453. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42454. document.body.appendChild(this._loadingDiv);
  42455. setTimeout(function () {
  42456. _this._loadingDiv.style.opacity = "1";
  42457. imgBack.style.transform = "rotateZ(360deg)";
  42458. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42459. }, 0);
  42460. };
  42461. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42462. var _this = this;
  42463. if (!this._loadingDiv) {
  42464. return;
  42465. }
  42466. var onTransitionEnd = function () {
  42467. if (!_this._loadingDiv) {
  42468. return;
  42469. }
  42470. document.body.removeChild(_this._loadingDiv);
  42471. window.removeEventListener("resize", _this._resizeLoadingUI);
  42472. _this._loadingDiv = null;
  42473. };
  42474. this._loadingDiv.style.opacity = "0";
  42475. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42476. };
  42477. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42478. set: function (text) {
  42479. this._loadingText = text;
  42480. if (this._loadingTextDiv) {
  42481. this._loadingTextDiv.innerHTML = this._loadingText;
  42482. }
  42483. },
  42484. enumerable: true,
  42485. configurable: true
  42486. });
  42487. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42488. get: function () {
  42489. return this._loadingDivBackgroundColor;
  42490. },
  42491. set: function (color) {
  42492. this._loadingDivBackgroundColor = color;
  42493. if (!this._loadingDiv) {
  42494. return;
  42495. }
  42496. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42497. },
  42498. enumerable: true,
  42499. configurable: true
  42500. });
  42501. return DefaultLoadingScreen;
  42502. }());
  42503. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42504. })(BABYLON || (BABYLON = {}));
  42505. //# sourceMappingURL=babylon.loadingScreen.js.map
  42506. var BABYLON;
  42507. (function (BABYLON) {
  42508. var AudioEngine = (function () {
  42509. function AudioEngine() {
  42510. this._audioContext = null;
  42511. this._audioContextInitialized = false;
  42512. this.canUseWebAudio = false;
  42513. this.WarnedWebAudioUnsupported = false;
  42514. this.unlocked = false;
  42515. this.isMP3supported = false;
  42516. this.isOGGsupported = false;
  42517. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42518. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42519. this.canUseWebAudio = true;
  42520. }
  42521. var audioElem = document.createElement('audio');
  42522. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42523. this.isMP3supported = true;
  42524. }
  42525. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42526. this.isOGGsupported = true;
  42527. }
  42528. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42529. this._unlockiOSaudio();
  42530. }
  42531. else {
  42532. this.unlocked = true;
  42533. }
  42534. }
  42535. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42536. get: function () {
  42537. if (!this._audioContextInitialized) {
  42538. this._initializeAudioContext();
  42539. }
  42540. return this._audioContext;
  42541. },
  42542. enumerable: true,
  42543. configurable: true
  42544. });
  42545. AudioEngine.prototype._unlockiOSaudio = function () {
  42546. var _this = this;
  42547. var unlockaudio = function () {
  42548. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42549. var source = _this.audioContext.createBufferSource();
  42550. source.buffer = buffer;
  42551. source.connect(_this.audioContext.destination);
  42552. source.start(0);
  42553. setTimeout(function () {
  42554. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42555. _this.unlocked = true;
  42556. window.removeEventListener('touchend', unlockaudio, false);
  42557. if (_this.onAudioUnlocked) {
  42558. _this.onAudioUnlocked();
  42559. }
  42560. }
  42561. }, 0);
  42562. };
  42563. window.addEventListener('touchend', unlockaudio, false);
  42564. };
  42565. AudioEngine.prototype._initializeAudioContext = function () {
  42566. try {
  42567. if (this.canUseWebAudio) {
  42568. this._audioContext = new AudioContext();
  42569. // create a global volume gain node
  42570. this.masterGain = this._audioContext.createGain();
  42571. this.masterGain.gain.value = 1;
  42572. this.masterGain.connect(this._audioContext.destination);
  42573. this._audioContextInitialized = true;
  42574. }
  42575. }
  42576. catch (e) {
  42577. this.canUseWebAudio = false;
  42578. BABYLON.Tools.Error("Web Audio: " + e.message);
  42579. }
  42580. };
  42581. AudioEngine.prototype.dispose = function () {
  42582. if (this.canUseWebAudio && this._audioContextInitialized) {
  42583. if (this._connectedAnalyser) {
  42584. this._connectedAnalyser.stopDebugCanvas();
  42585. this._connectedAnalyser.dispose();
  42586. this.masterGain.disconnect();
  42587. this.masterGain.connect(this._audioContext.destination);
  42588. this._connectedAnalyser = null;
  42589. }
  42590. this.masterGain.gain.value = 1;
  42591. }
  42592. this.WarnedWebAudioUnsupported = false;
  42593. };
  42594. AudioEngine.prototype.getGlobalVolume = function () {
  42595. if (this.canUseWebAudio && this._audioContextInitialized) {
  42596. return this.masterGain.gain.value;
  42597. }
  42598. else {
  42599. return -1;
  42600. }
  42601. };
  42602. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42603. if (this.canUseWebAudio && this._audioContextInitialized) {
  42604. this.masterGain.gain.value = newVolume;
  42605. }
  42606. };
  42607. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42608. if (this._connectedAnalyser) {
  42609. this._connectedAnalyser.stopDebugCanvas();
  42610. }
  42611. if (this.canUseWebAudio && this._audioContextInitialized) {
  42612. this._connectedAnalyser = analyser;
  42613. this.masterGain.disconnect();
  42614. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42615. }
  42616. };
  42617. return AudioEngine;
  42618. }());
  42619. BABYLON.AudioEngine = AudioEngine;
  42620. })(BABYLON || (BABYLON = {}));
  42621. //# sourceMappingURL=babylon.audioEngine.js.map
  42622. var BABYLON;
  42623. (function (BABYLON) {
  42624. var Sound = (function () {
  42625. /**
  42626. * Create a sound and attach it to a scene
  42627. * @param name Name of your sound
  42628. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42629. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42630. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42631. */
  42632. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42633. var _this = this;
  42634. this.autoplay = false;
  42635. this.loop = false;
  42636. this.useCustomAttenuation = false;
  42637. this.spatialSound = false;
  42638. this.refDistance = 1;
  42639. this.rolloffFactor = 1;
  42640. this.maxDistance = 100;
  42641. this.distanceModel = "linear";
  42642. this._panningModel = "equalpower";
  42643. this._playbackRate = 1;
  42644. this._streaming = false;
  42645. this._startTime = 0;
  42646. this._startOffset = 0;
  42647. this._position = BABYLON.Vector3.Zero();
  42648. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42649. this._volume = 1;
  42650. this._isLoaded = false;
  42651. this._isReadyToPlay = false;
  42652. this.isPlaying = false;
  42653. this.isPaused = false;
  42654. this._isDirectional = false;
  42655. // Used if you'd like to create a directional sound.
  42656. // If not set, the sound will be omnidirectional
  42657. this._coneInnerAngle = 360;
  42658. this._coneOuterAngle = 360;
  42659. this._coneOuterGain = 0;
  42660. this._isOutputConnected = false;
  42661. this._urlType = "Unknown";
  42662. this.name = name;
  42663. this._scene = scene;
  42664. this._readyToPlayCallback = readyToPlayCallback;
  42665. // Default custom attenuation function is a linear attenuation
  42666. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42667. if (currentDistance < maxDistance) {
  42668. return currentVolume * (1 - currentDistance / maxDistance);
  42669. }
  42670. else {
  42671. return 0;
  42672. }
  42673. };
  42674. if (options) {
  42675. this.autoplay = options.autoplay || false;
  42676. this.loop = options.loop || false;
  42677. // if volume === 0, we need another way to check this option
  42678. if (options.volume !== undefined) {
  42679. this._volume = options.volume;
  42680. }
  42681. this.spatialSound = options.spatialSound || false;
  42682. this.maxDistance = options.maxDistance || 100;
  42683. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42684. this.rolloffFactor = options.rolloffFactor || 1;
  42685. this.refDistance = options.refDistance || 1;
  42686. this.distanceModel = options.distanceModel || "linear";
  42687. this._playbackRate = options.playbackRate || 1;
  42688. this._streaming = options.streaming || false;
  42689. }
  42690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42691. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42692. this._soundGain.gain.value = this._volume;
  42693. this._inputAudioNode = this._soundGain;
  42694. this._ouputAudioNode = this._soundGain;
  42695. if (this.spatialSound) {
  42696. this._createSpatialParameters();
  42697. }
  42698. this._scene.mainSoundTrack.AddSound(this);
  42699. var validParameter = true;
  42700. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42701. if (urlOrArrayBuffer) {
  42702. if (typeof (urlOrArrayBuffer) === "string")
  42703. this._urlType = "String";
  42704. if (Array.isArray(urlOrArrayBuffer))
  42705. this._urlType = "Array";
  42706. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42707. this._urlType = "ArrayBuffer";
  42708. var urls = [];
  42709. var codecSupportedFound = false;
  42710. switch (this._urlType) {
  42711. case "ArrayBuffer":
  42712. if (urlOrArrayBuffer.byteLength > 0) {
  42713. codecSupportedFound = true;
  42714. this._soundLoaded(urlOrArrayBuffer);
  42715. }
  42716. break;
  42717. case "String":
  42718. urls.push(urlOrArrayBuffer);
  42719. case "Array":
  42720. if (urls.length === 0)
  42721. urls = urlOrArrayBuffer;
  42722. // If we found a supported format, we load it immediately and stop the loop
  42723. for (var i = 0; i < urls.length; i++) {
  42724. var url = urls[i];
  42725. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42726. codecSupportedFound = true;
  42727. }
  42728. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42729. codecSupportedFound = true;
  42730. }
  42731. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42732. codecSupportedFound = true;
  42733. }
  42734. if (codecSupportedFound) {
  42735. // Loading sound using XHR2
  42736. if (!this._streaming) {
  42737. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42738. }
  42739. else {
  42740. this._htmlAudioElement = new Audio(url);
  42741. this._htmlAudioElement.controls = false;
  42742. this._htmlAudioElement.loop = this.loop;
  42743. this._htmlAudioElement.crossOrigin = "anonymous";
  42744. this._htmlAudioElement.preload = "auto";
  42745. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42746. _this._isReadyToPlay = true;
  42747. if (_this.autoplay) {
  42748. _this.play();
  42749. }
  42750. if (_this._readyToPlayCallback) {
  42751. _this._readyToPlayCallback();
  42752. }
  42753. });
  42754. document.body.appendChild(this._htmlAudioElement);
  42755. }
  42756. break;
  42757. }
  42758. }
  42759. break;
  42760. default:
  42761. validParameter = false;
  42762. break;
  42763. }
  42764. if (!validParameter) {
  42765. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42766. }
  42767. else {
  42768. if (!codecSupportedFound) {
  42769. this._isReadyToPlay = true;
  42770. // Simulating a ready to play event to avoid breaking code path
  42771. if (this._readyToPlayCallback) {
  42772. window.setTimeout(function () {
  42773. _this._readyToPlayCallback();
  42774. }, 1000);
  42775. }
  42776. }
  42777. }
  42778. }
  42779. }
  42780. else {
  42781. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42782. this._scene.mainSoundTrack.AddSound(this);
  42783. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42784. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42785. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42786. }
  42787. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42788. if (this._readyToPlayCallback) {
  42789. window.setTimeout(function () {
  42790. _this._readyToPlayCallback();
  42791. }, 1000);
  42792. }
  42793. }
  42794. }
  42795. Sound.prototype.dispose = function () {
  42796. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42797. if (this.isPlaying) {
  42798. this.stop();
  42799. }
  42800. this._isReadyToPlay = false;
  42801. if (this.soundTrackId === -1) {
  42802. this._scene.mainSoundTrack.RemoveSound(this);
  42803. }
  42804. else {
  42805. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42806. }
  42807. if (this._soundGain) {
  42808. this._soundGain.disconnect();
  42809. this._soundGain = null;
  42810. }
  42811. if (this._soundPanner) {
  42812. this._soundPanner.disconnect();
  42813. this._soundPanner = null;
  42814. }
  42815. if (this._soundSource) {
  42816. this._soundSource.disconnect();
  42817. this._soundSource = null;
  42818. }
  42819. this._audioBuffer = null;
  42820. if (this._htmlAudioElement) {
  42821. this._htmlAudioElement.pause();
  42822. this._htmlAudioElement.src = "";
  42823. document.body.removeChild(this._htmlAudioElement);
  42824. }
  42825. if (this._connectedMesh) {
  42826. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42827. this._connectedMesh = null;
  42828. }
  42829. }
  42830. };
  42831. Sound.prototype.isReady = function () {
  42832. return this._isReadyToPlay;
  42833. };
  42834. Sound.prototype._soundLoaded = function (audioData) {
  42835. var _this = this;
  42836. this._isLoaded = true;
  42837. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42838. _this._audioBuffer = buffer;
  42839. _this._isReadyToPlay = true;
  42840. if (_this.autoplay) {
  42841. _this.play();
  42842. }
  42843. if (_this._readyToPlayCallback) {
  42844. _this._readyToPlayCallback();
  42845. }
  42846. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42847. };
  42848. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42850. this._audioBuffer = audioBuffer;
  42851. this._isReadyToPlay = true;
  42852. }
  42853. };
  42854. Sound.prototype.updateOptions = function (options) {
  42855. if (options) {
  42856. this.loop = options.loop || this.loop;
  42857. this.maxDistance = options.maxDistance || this.maxDistance;
  42858. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42859. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42860. this.refDistance = options.refDistance || this.refDistance;
  42861. this.distanceModel = options.distanceModel || this.distanceModel;
  42862. this._playbackRate = options.playbackRate || this._playbackRate;
  42863. this._updateSpatialParameters();
  42864. if (this.isPlaying) {
  42865. if (this._streaming) {
  42866. this._htmlAudioElement.playbackRate = this._playbackRate;
  42867. }
  42868. else {
  42869. this._soundSource.playbackRate.value = this._playbackRate;
  42870. }
  42871. }
  42872. }
  42873. };
  42874. Sound.prototype._createSpatialParameters = function () {
  42875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42876. if (this._scene.headphone) {
  42877. this._panningModel = "HRTF";
  42878. }
  42879. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42880. this._updateSpatialParameters();
  42881. this._soundPanner.connect(this._ouputAudioNode);
  42882. this._inputAudioNode = this._soundPanner;
  42883. }
  42884. };
  42885. Sound.prototype._updateSpatialParameters = function () {
  42886. if (this.spatialSound) {
  42887. if (this.useCustomAttenuation) {
  42888. // Tricks to disable in a way embedded Web Audio attenuation
  42889. this._soundPanner.distanceModel = "linear";
  42890. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42891. this._soundPanner.refDistance = 1;
  42892. this._soundPanner.rolloffFactor = 1;
  42893. this._soundPanner.panningModel = this._panningModel;
  42894. }
  42895. else {
  42896. this._soundPanner.distanceModel = this.distanceModel;
  42897. this._soundPanner.maxDistance = this.maxDistance;
  42898. this._soundPanner.refDistance = this.refDistance;
  42899. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42900. this._soundPanner.panningModel = this._panningModel;
  42901. }
  42902. }
  42903. };
  42904. Sound.prototype.switchPanningModelToHRTF = function () {
  42905. this._panningModel = "HRTF";
  42906. this._switchPanningModel();
  42907. };
  42908. Sound.prototype.switchPanningModelToEqualPower = function () {
  42909. this._panningModel = "equalpower";
  42910. this._switchPanningModel();
  42911. };
  42912. Sound.prototype._switchPanningModel = function () {
  42913. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42914. this._soundPanner.panningModel = this._panningModel;
  42915. }
  42916. };
  42917. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42919. if (this._isOutputConnected) {
  42920. this._ouputAudioNode.disconnect();
  42921. }
  42922. this._ouputAudioNode.connect(soundTrackAudioNode);
  42923. this._isOutputConnected = true;
  42924. }
  42925. };
  42926. /**
  42927. * Transform this sound into a directional source
  42928. * @param coneInnerAngle Size of the inner cone in degree
  42929. * @param coneOuterAngle Size of the outer cone in degree
  42930. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42931. */
  42932. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42933. if (coneOuterAngle < coneInnerAngle) {
  42934. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42935. return;
  42936. }
  42937. this._coneInnerAngle = coneInnerAngle;
  42938. this._coneOuterAngle = coneOuterAngle;
  42939. this._coneOuterGain = coneOuterGain;
  42940. this._isDirectional = true;
  42941. if (this.isPlaying && this.loop) {
  42942. this.stop();
  42943. this.play();
  42944. }
  42945. };
  42946. Sound.prototype.setPosition = function (newPosition) {
  42947. this._position = newPosition;
  42948. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42949. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42950. }
  42951. };
  42952. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42953. this._localDirection = newLocalDirection;
  42954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42955. this._updateDirection();
  42956. }
  42957. };
  42958. Sound.prototype._updateDirection = function () {
  42959. var mat = this._connectedMesh.getWorldMatrix();
  42960. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42961. direction.normalize();
  42962. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42963. };
  42964. Sound.prototype.updateDistanceFromListener = function () {
  42965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42966. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42967. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42968. }
  42969. };
  42970. Sound.prototype.setAttenuationFunction = function (callback) {
  42971. this._customAttenuationFunction = callback;
  42972. };
  42973. /**
  42974. * Play the sound
  42975. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42976. * @param offset (optional) Start the sound setting it at a specific time
  42977. */
  42978. Sound.prototype.play = function (time, offset) {
  42979. var _this = this;
  42980. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42981. try {
  42982. if (this._startOffset < 0) {
  42983. time = -this._startOffset;
  42984. this._startOffset = 0;
  42985. }
  42986. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42987. if (!this._soundSource || !this._streamingSource) {
  42988. if (this.spatialSound) {
  42989. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42990. if (this._isDirectional) {
  42991. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42992. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42993. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42994. if (this._connectedMesh) {
  42995. this._updateDirection();
  42996. }
  42997. else {
  42998. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42999. }
  43000. }
  43001. }
  43002. }
  43003. if (this._streaming) {
  43004. if (!this._streamingSource) {
  43005. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  43006. this._htmlAudioElement.onended = function () { _this._onended(); };
  43007. this._htmlAudioElement.playbackRate = this._playbackRate;
  43008. }
  43009. this._streamingSource.disconnect();
  43010. this._streamingSource.connect(this._inputAudioNode);
  43011. this._htmlAudioElement.play();
  43012. }
  43013. else {
  43014. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  43015. this._soundSource.buffer = this._audioBuffer;
  43016. this._soundSource.connect(this._inputAudioNode);
  43017. this._soundSource.loop = this.loop;
  43018. this._soundSource.playbackRate.value = this._playbackRate;
  43019. this._soundSource.onended = function () { _this._onended(); };
  43020. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  43021. }
  43022. this._startTime = startTime;
  43023. this.isPlaying = true;
  43024. this.isPaused = false;
  43025. }
  43026. catch (ex) {
  43027. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  43028. }
  43029. }
  43030. };
  43031. Sound.prototype._onended = function () {
  43032. this.isPlaying = false;
  43033. if (this.onended) {
  43034. this.onended();
  43035. }
  43036. };
  43037. /**
  43038. * Stop the sound
  43039. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  43040. */
  43041. Sound.prototype.stop = function (time) {
  43042. if (this.isPlaying) {
  43043. if (this._streaming) {
  43044. this._htmlAudioElement.pause();
  43045. // Test needed for Firefox or it will generate an Invalid State Error
  43046. if (this._htmlAudioElement.currentTime > 0) {
  43047. this._htmlAudioElement.currentTime = 0;
  43048. }
  43049. }
  43050. else {
  43051. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43052. this._soundSource.stop(stopTime);
  43053. this._soundSource.onended = null;
  43054. if (!this.isPaused) {
  43055. this._startOffset = 0;
  43056. }
  43057. }
  43058. this.isPlaying = false;
  43059. }
  43060. };
  43061. Sound.prototype.pause = function () {
  43062. if (this.isPlaying) {
  43063. this.isPaused = true;
  43064. if (this._streaming) {
  43065. this._htmlAudioElement.pause();
  43066. }
  43067. else {
  43068. this.stop(0);
  43069. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  43070. }
  43071. }
  43072. };
  43073. Sound.prototype.setVolume = function (newVolume, time) {
  43074. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43075. if (time) {
  43076. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  43077. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  43078. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  43079. }
  43080. else {
  43081. this._soundGain.gain.value = newVolume;
  43082. }
  43083. }
  43084. this._volume = newVolume;
  43085. };
  43086. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  43087. this._playbackRate = newPlaybackRate;
  43088. if (this.isPlaying) {
  43089. if (this._streaming) {
  43090. this._htmlAudioElement.playbackRate = this._playbackRate;
  43091. }
  43092. else {
  43093. this._soundSource.playbackRate.value = this._playbackRate;
  43094. }
  43095. }
  43096. };
  43097. Sound.prototype.getVolume = function () {
  43098. return this._volume;
  43099. };
  43100. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43101. var _this = this;
  43102. if (this._connectedMesh) {
  43103. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43104. this._registerFunc = null;
  43105. }
  43106. this._connectedMesh = meshToConnectTo;
  43107. if (!this.spatialSound) {
  43108. this.spatialSound = true;
  43109. this._createSpatialParameters();
  43110. if (this.isPlaying && this.loop) {
  43111. this.stop();
  43112. this.play();
  43113. }
  43114. }
  43115. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43116. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43117. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43118. };
  43119. Sound.prototype.detachFromMesh = function () {
  43120. if (this._connectedMesh) {
  43121. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43122. this._registerFunc = null;
  43123. this._connectedMesh = null;
  43124. }
  43125. };
  43126. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43127. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43129. this._updateDirection();
  43130. }
  43131. };
  43132. Sound.prototype.clone = function () {
  43133. var _this = this;
  43134. if (!this._streaming) {
  43135. var setBufferAndRun = function () {
  43136. if (_this._isReadyToPlay) {
  43137. clonedSound._audioBuffer = _this.getAudioBuffer();
  43138. clonedSound._isReadyToPlay = true;
  43139. if (clonedSound.autoplay) {
  43140. clonedSound.play();
  43141. }
  43142. }
  43143. else {
  43144. window.setTimeout(setBufferAndRun, 300);
  43145. }
  43146. };
  43147. var currentOptions = {
  43148. autoplay: this.autoplay, loop: this.loop,
  43149. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43150. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43151. refDistance: this.refDistance, distanceModel: this.distanceModel
  43152. };
  43153. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43154. if (this.useCustomAttenuation) {
  43155. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43156. }
  43157. clonedSound.setPosition(this._position);
  43158. clonedSound.setPlaybackRate(this._playbackRate);
  43159. setBufferAndRun();
  43160. return clonedSound;
  43161. }
  43162. else {
  43163. return null;
  43164. }
  43165. };
  43166. Sound.prototype.getAudioBuffer = function () {
  43167. return this._audioBuffer;
  43168. };
  43169. Sound.prototype.serialize = function () {
  43170. var serializationObject = {
  43171. name: this.name,
  43172. url: this.name,
  43173. autoplay: this.autoplay,
  43174. loop: this.loop,
  43175. volume: this._volume,
  43176. spatialSound: this.spatialSound,
  43177. maxDistance: this.maxDistance,
  43178. rolloffFactor: this.rolloffFactor,
  43179. refDistance: this.refDistance,
  43180. distanceModel: this.distanceModel,
  43181. playbackRate: this._playbackRate,
  43182. panningModel: this._panningModel,
  43183. soundTrackId: this.soundTrackId
  43184. };
  43185. if (this.spatialSound) {
  43186. if (this._connectedMesh)
  43187. serializationObject.connectedMeshId = this._connectedMesh.id;
  43188. serializationObject.position = this._position.asArray();
  43189. serializationObject.refDistance = this.refDistance;
  43190. serializationObject.distanceModel = this.distanceModel;
  43191. serializationObject.isDirectional = this._isDirectional;
  43192. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43193. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43194. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43195. serializationObject.coneOuterGain = this._coneOuterGain;
  43196. }
  43197. return serializationObject;
  43198. };
  43199. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43200. var soundName = parsedSound.name;
  43201. var soundUrl;
  43202. if (parsedSound.url) {
  43203. soundUrl = rootUrl + parsedSound.url;
  43204. }
  43205. else {
  43206. soundUrl = rootUrl + soundName;
  43207. }
  43208. var options = {
  43209. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43210. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43211. rolloffFactor: parsedSound.rolloffFactor,
  43212. refDistance: parsedSound.refDistance,
  43213. distanceModel: parsedSound.distanceModel,
  43214. playbackRate: parsedSound.playbackRate
  43215. };
  43216. var newSound;
  43217. if (!sourceSound) {
  43218. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43219. scene._addPendingData(newSound);
  43220. }
  43221. else {
  43222. var setBufferAndRun = function () {
  43223. if (sourceSound._isReadyToPlay) {
  43224. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43225. newSound._isReadyToPlay = true;
  43226. if (newSound.autoplay) {
  43227. newSound.play();
  43228. }
  43229. }
  43230. else {
  43231. window.setTimeout(setBufferAndRun, 300);
  43232. }
  43233. };
  43234. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43235. setBufferAndRun();
  43236. }
  43237. if (parsedSound.position) {
  43238. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43239. newSound.setPosition(soundPosition);
  43240. }
  43241. if (parsedSound.isDirectional) {
  43242. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43243. if (parsedSound.localDirectionToMesh) {
  43244. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43245. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43246. }
  43247. }
  43248. if (parsedSound.connectedMeshId) {
  43249. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43250. if (connectedMesh) {
  43251. newSound.attachToMesh(connectedMesh);
  43252. }
  43253. }
  43254. return newSound;
  43255. };
  43256. return Sound;
  43257. }());
  43258. BABYLON.Sound = Sound;
  43259. })(BABYLON || (BABYLON = {}));
  43260. //# sourceMappingURL=babylon.sound.js.map
  43261. var BABYLON;
  43262. (function (BABYLON) {
  43263. var SoundTrack = (function () {
  43264. function SoundTrack(scene, options) {
  43265. this.id = -1;
  43266. this._isMainTrack = false;
  43267. this._isInitialized = false;
  43268. this._scene = scene;
  43269. this.soundCollection = new Array();
  43270. this._options = options;
  43271. if (!this._isMainTrack) {
  43272. this._scene.soundTracks.push(this);
  43273. this.id = this._scene.soundTracks.length - 1;
  43274. }
  43275. }
  43276. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43278. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43279. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43280. if (this._options) {
  43281. if (this._options.volume) {
  43282. this._outputAudioNode.gain.value = this._options.volume;
  43283. }
  43284. if (this._options.mainTrack) {
  43285. this._isMainTrack = this._options.mainTrack;
  43286. }
  43287. }
  43288. this._isInitialized = true;
  43289. }
  43290. };
  43291. SoundTrack.prototype.dispose = function () {
  43292. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43293. if (this._connectedAnalyser) {
  43294. this._connectedAnalyser.stopDebugCanvas();
  43295. }
  43296. while (this.soundCollection.length) {
  43297. this.soundCollection[0].dispose();
  43298. }
  43299. if (this._outputAudioNode) {
  43300. this._outputAudioNode.disconnect();
  43301. }
  43302. this._outputAudioNode = null;
  43303. }
  43304. };
  43305. SoundTrack.prototype.AddSound = function (sound) {
  43306. if (!this._isInitialized) {
  43307. this._initializeSoundTrackAudioGraph();
  43308. }
  43309. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43310. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43311. }
  43312. if (sound.soundTrackId) {
  43313. if (sound.soundTrackId === -1) {
  43314. this._scene.mainSoundTrack.RemoveSound(sound);
  43315. }
  43316. else {
  43317. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43318. }
  43319. }
  43320. this.soundCollection.push(sound);
  43321. sound.soundTrackId = this.id;
  43322. };
  43323. SoundTrack.prototype.RemoveSound = function (sound) {
  43324. var index = this.soundCollection.indexOf(sound);
  43325. if (index !== -1) {
  43326. this.soundCollection.splice(index, 1);
  43327. }
  43328. };
  43329. SoundTrack.prototype.setVolume = function (newVolume) {
  43330. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43331. this._outputAudioNode.gain.value = newVolume;
  43332. }
  43333. };
  43334. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43335. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43336. for (var i = 0; i < this.soundCollection.length; i++) {
  43337. this.soundCollection[i].switchPanningModelToHRTF();
  43338. }
  43339. }
  43340. };
  43341. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43342. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43343. for (var i = 0; i < this.soundCollection.length; i++) {
  43344. this.soundCollection[i].switchPanningModelToEqualPower();
  43345. }
  43346. }
  43347. };
  43348. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43349. if (this._connectedAnalyser) {
  43350. this._connectedAnalyser.stopDebugCanvas();
  43351. }
  43352. this._connectedAnalyser = analyser;
  43353. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43354. this._outputAudioNode.disconnect();
  43355. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43356. }
  43357. };
  43358. return SoundTrack;
  43359. }());
  43360. BABYLON.SoundTrack = SoundTrack;
  43361. })(BABYLON || (BABYLON = {}));
  43362. //# sourceMappingURL=babylon.soundtrack.js.map
  43363. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  43364. /// <reference path="..\Math\babylon.math.ts" />
  43365. var BABYLON;
  43366. (function (BABYLON) {
  43367. /**
  43368. * Special Glow Blur post process only blurring the alpha channel
  43369. * It enforces keeping the most luminous color in the color channel.
  43370. */
  43371. var GlowBlurPostProcess = (function (_super) {
  43372. __extends(GlowBlurPostProcess, _super);
  43373. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43375. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  43376. _this.direction = direction;
  43377. _this.blurWidth = blurWidth;
  43378. _this.onApplyObservable.add(function (effect) {
  43379. effect.setFloat2("screenSize", _this.width, _this.height);
  43380. effect.setVector2("direction", _this.direction);
  43381. effect.setFloat("blurWidth", _this.blurWidth);
  43382. });
  43383. return _this;
  43384. }
  43385. return GlowBlurPostProcess;
  43386. }(BABYLON.PostProcess));
  43387. /**
  43388. * The highlight layer Helps adding a glow effect around a mesh.
  43389. *
  43390. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  43391. * glowy meshes to your scene.
  43392. *
  43393. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  43394. */
  43395. var HighlightLayer = (function () {
  43396. /**
  43397. * Instantiates a new highlight Layer and references it to the scene..
  43398. * @param name The name of the layer
  43399. * @param scene The scene to use the layer in
  43400. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  43401. */
  43402. function HighlightLayer(name, scene, options) {
  43403. this.name = name;
  43404. this._vertexBuffers = {};
  43405. this._mainTextureDesiredSize = { width: 0, height: 0 };
  43406. this._meshes = {};
  43407. this._maxSize = 0;
  43408. this._shouldRender = false;
  43409. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  43410. this._excludedMeshes = {};
  43411. /**
  43412. * Specifies whether or not the inner glow is ACTIVE in the layer.
  43413. */
  43414. this.innerGlow = true;
  43415. /**
  43416. * Specifies whether or not the outer glow is ACTIVE in the layer.
  43417. */
  43418. this.outerGlow = true;
  43419. /**
  43420. * Specifies wether the highlight layer is enabled or not.
  43421. */
  43422. this.isEnabled = true;
  43423. /**
  43424. * An event triggered when the highlight layer has been disposed.
  43425. * @type {BABYLON.Observable}
  43426. */
  43427. this.onDisposeObservable = new BABYLON.Observable();
  43428. /**
  43429. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  43430. * @type {BABYLON.Observable}
  43431. */
  43432. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  43433. /**
  43434. * An event triggered when the highlight layer is being blurred.
  43435. * @type {BABYLON.Observable}
  43436. */
  43437. this.onBeforeBlurObservable = new BABYLON.Observable();
  43438. /**
  43439. * An event triggered when the highlight layer has been blurred.
  43440. * @type {BABYLON.Observable}
  43441. */
  43442. this.onAfterBlurObservable = new BABYLON.Observable();
  43443. /**
  43444. * An event triggered when the glowing blurred texture is being merged in the scene.
  43445. * @type {BABYLON.Observable}
  43446. */
  43447. this.onBeforeComposeObservable = new BABYLON.Observable();
  43448. /**
  43449. * An event triggered when the glowing blurred texture has been merged in the scene.
  43450. * @type {BABYLON.Observable}
  43451. */
  43452. this.onAfterComposeObservable = new BABYLON.Observable();
  43453. /**
  43454. * An event triggered when the highlight layer changes its size.
  43455. * @type {BABYLON.Observable}
  43456. */
  43457. this.onSizeChangedObservable = new BABYLON.Observable();
  43458. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43459. var engine = scene.getEngine();
  43460. this._engine = engine;
  43461. this._maxSize = this._engine.getCaps().maxTextureSize;
  43462. this._scene.highlightLayers.push(this);
  43463. // Warn on stencil.
  43464. if (!this._engine.isStencilEnable) {
  43465. 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 }");
  43466. }
  43467. // Adapt options
  43468. this._options = options || {
  43469. mainTextureRatio: 0.25,
  43470. blurTextureSizeRatio: 0.5,
  43471. blurHorizontalSize: 1,
  43472. blurVerticalSize: 1,
  43473. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  43474. };
  43475. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  43476. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  43477. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  43478. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  43479. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  43480. // VBO
  43481. var vertices = [];
  43482. vertices.push(1, 1);
  43483. vertices.push(-1, 1);
  43484. vertices.push(-1, -1);
  43485. vertices.push(1, -1);
  43486. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  43488. // Indices
  43489. var indices = [];
  43490. indices.push(0);
  43491. indices.push(1);
  43492. indices.push(2);
  43493. indices.push(0);
  43494. indices.push(2);
  43495. indices.push(3);
  43496. this._indexBuffer = engine.createIndexBuffer(indices);
  43497. // Effect
  43498. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  43499. // Render target
  43500. this.setMainTextureSize();
  43501. // Create Textures and post processes
  43502. this.createTextureAndPostProcesses();
  43503. }
  43504. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  43505. /**
  43506. * Gets the horizontal size of the blur.
  43507. */
  43508. get: function () {
  43509. return this._horizontalBlurPostprocess.blurWidth;
  43510. },
  43511. /**
  43512. * Specifies the horizontal size of the blur.
  43513. */
  43514. set: function (value) {
  43515. this._horizontalBlurPostprocess.blurWidth = value;
  43516. },
  43517. enumerable: true,
  43518. configurable: true
  43519. });
  43520. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  43521. /**
  43522. * Gets the vertical size of the blur.
  43523. */
  43524. get: function () {
  43525. return this._verticalBlurPostprocess.blurWidth;
  43526. },
  43527. /**
  43528. * Specifies the vertical size of the blur.
  43529. */
  43530. set: function (value) {
  43531. this._verticalBlurPostprocess.blurWidth = value;
  43532. },
  43533. enumerable: true,
  43534. configurable: true
  43535. });
  43536. Object.defineProperty(HighlightLayer.prototype, "camera", {
  43537. /**
  43538. * Gets the camera attached to the layer.
  43539. */
  43540. get: function () {
  43541. return this._options.camera;
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. /**
  43547. * Creates the render target textures and post processes used in the highlight layer.
  43548. */
  43549. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  43550. var _this = this;
  43551. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  43552. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  43553. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  43554. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  43555. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  43556. width: this._mainTextureDesiredSize.width,
  43557. height: this._mainTextureDesiredSize.height
  43558. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43559. this._mainTexture.activeCamera = this._options.camera;
  43560. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43561. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43562. this._mainTexture.anisotropicFilteringLevel = 1;
  43563. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43564. this._mainTexture.renderParticles = false;
  43565. this._mainTexture.renderList = null;
  43566. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  43567. width: blurTextureWidth,
  43568. height: blurTextureHeight
  43569. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43570. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43571. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43572. this._blurTexture.anisotropicFilteringLevel = 16;
  43573. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  43574. this._blurTexture.renderParticles = false;
  43575. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43576. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43577. effect.setTexture("textureSampler", _this._mainTexture);
  43578. });
  43579. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  43580. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43581. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43582. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43583. });
  43584. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43585. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43586. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43587. });
  43588. }
  43589. else {
  43590. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43591. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43592. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43593. });
  43594. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43595. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43596. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43597. });
  43598. }
  43599. this._mainTexture.onAfterUnbindObservable.add(function () {
  43600. _this.onBeforeBlurObservable.notifyObservers(_this);
  43601. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  43602. _this.onAfterBlurObservable.notifyObservers(_this);
  43603. });
  43604. // Custom render function
  43605. var renderSubMesh = function (subMesh) {
  43606. var mesh = subMesh.getRenderingMesh();
  43607. var scene = _this._scene;
  43608. var engine = scene.getEngine();
  43609. // Culling
  43610. engine.setState(subMesh.getMaterial().backFaceCulling);
  43611. // Managing instances
  43612. var batch = mesh._getInstancesRenderList(subMesh._id);
  43613. if (batch.mustReturn) {
  43614. return;
  43615. }
  43616. // Excluded Mesh
  43617. if (_this._excludedMeshes[mesh.uniqueId]) {
  43618. return;
  43619. }
  43620. ;
  43621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43622. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  43623. var material = subMesh.getMaterial();
  43624. var emissiveTexture = null;
  43625. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  43626. emissiveTexture = material.emissiveTexture;
  43627. }
  43628. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  43629. engine.enableEffect(_this._glowMapGenerationEffect);
  43630. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  43631. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  43632. if (highlightLayerMesh) {
  43633. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  43634. }
  43635. else {
  43636. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  43637. }
  43638. // Alpha test
  43639. if (material && material.needAlphaTesting()) {
  43640. var alphaTexture = material.getAlphaTestTexture();
  43641. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  43642. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43643. }
  43644. // Glow emissive only
  43645. if (emissiveTexture) {
  43646. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  43647. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  43648. }
  43649. // Bones
  43650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43651. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43652. }
  43653. // Draw
  43654. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  43655. }
  43656. else {
  43657. // Need to reset refresh rate of the shadowMap
  43658. _this._mainTexture.resetRefreshCounter();
  43659. }
  43660. };
  43661. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43662. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  43663. var index;
  43664. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43665. renderSubMesh(opaqueSubMeshes.data[index]);
  43666. }
  43667. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43668. renderSubMesh(alphaTestSubMeshes.data[index]);
  43669. }
  43670. for (index = 0; index < transparentSubMeshes.length; index++) {
  43671. renderSubMesh(transparentSubMeshes.data[index]);
  43672. }
  43673. };
  43674. this._mainTexture.onClearObservable.add(function (engine) {
  43675. engine.clear(HighlightLayer.neutralColor, true, true, true);
  43676. });
  43677. };
  43678. /**
  43679. * Checks for the readiness of the element composing the layer.
  43680. * @param subMesh the mesh to check for
  43681. * @param useInstances specify wether or not to use instances to render the mesh
  43682. * @param emissiveTexture the associated emissive texture used to generate the glow
  43683. * @return true if ready otherwise, false
  43684. */
  43685. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  43686. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  43687. return false;
  43688. }
  43689. var defines = [];
  43690. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43691. var mesh = subMesh.getMesh();
  43692. var material = subMesh.getMaterial();
  43693. var uv1 = false;
  43694. var uv2 = false;
  43695. // Alpha test
  43696. if (material && material.needAlphaTesting()) {
  43697. var alphaTexture = material.getAlphaTestTexture();
  43698. if (alphaTexture) {
  43699. defines.push("#define ALPHATEST");
  43700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43701. alphaTexture.coordinatesIndex === 1) {
  43702. defines.push("#define DIFFUSEUV2");
  43703. uv2 = true;
  43704. }
  43705. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43706. defines.push("#define DIFFUSEUV1");
  43707. uv1 = true;
  43708. }
  43709. }
  43710. }
  43711. // Emissive
  43712. if (emissiveTexture) {
  43713. defines.push("#define EMISSIVE");
  43714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43715. emissiveTexture.coordinatesIndex === 1) {
  43716. defines.push("#define EMISSIVEUV2");
  43717. uv2 = true;
  43718. }
  43719. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43720. defines.push("#define EMISSIVEUV1");
  43721. uv1 = true;
  43722. }
  43723. }
  43724. if (uv1) {
  43725. attribs.push(BABYLON.VertexBuffer.UVKind);
  43726. defines.push("#define UV1");
  43727. }
  43728. if (uv2) {
  43729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43730. defines.push("#define UV2");
  43731. }
  43732. // Bones
  43733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43736. if (mesh.numBoneInfluencers > 4) {
  43737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43739. }
  43740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43741. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43742. }
  43743. else {
  43744. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43745. }
  43746. // Instances
  43747. if (useInstances) {
  43748. defines.push("#define INSTANCES");
  43749. attribs.push("world0");
  43750. attribs.push("world1");
  43751. attribs.push("world2");
  43752. attribs.push("world3");
  43753. }
  43754. // Get correct effect
  43755. var join = defines.join("\n");
  43756. if (this._cachedDefines !== join) {
  43757. this._cachedDefines = join;
  43758. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  43759. }
  43760. return this._glowMapGenerationEffect.isReady();
  43761. };
  43762. /**
  43763. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  43764. */
  43765. HighlightLayer.prototype.render = function () {
  43766. var currentEffect = this._glowMapMergeEffect;
  43767. // Check
  43768. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43769. return;
  43770. var engine = this._scene.getEngine();
  43771. this.onBeforeComposeObservable.notifyObservers(this);
  43772. // Render
  43773. engine.enableEffect(currentEffect);
  43774. engine.setState(false);
  43775. // Cache
  43776. var previousStencilBuffer = engine.getStencilBuffer();
  43777. var previousStencilFunction = engine.getStencilFunction();
  43778. var previousStencilMask = engine.getStencilMask();
  43779. var previousAlphaMode = engine.getAlphaMode();
  43780. // Texture
  43781. currentEffect.setTexture("textureSampler", this._blurTexture);
  43782. // VBOs
  43783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43784. // Draw order
  43785. engine.setAlphaMode(this._options.alphaBlendingMode);
  43786. engine.setStencilMask(0x00);
  43787. engine.setStencilBuffer(true);
  43788. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43789. if (this.outerGlow) {
  43790. currentEffect.setFloat("offset", 0);
  43791. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43792. engine.draw(true, 0, 6);
  43793. }
  43794. if (this.innerGlow) {
  43795. currentEffect.setFloat("offset", 1);
  43796. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43797. engine.draw(true, 0, 6);
  43798. }
  43799. // Restore Cache
  43800. engine.setStencilFunction(previousStencilFunction);
  43801. engine.setStencilMask(previousStencilMask);
  43802. engine.setAlphaMode(previousAlphaMode);
  43803. engine.setStencilBuffer(previousStencilBuffer);
  43804. this.onAfterComposeObservable.notifyObservers(this);
  43805. // Handle size changes.
  43806. var size = this._mainTexture.getSize();
  43807. this.setMainTextureSize();
  43808. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43809. // Recreate RTT and post processes on size change.
  43810. this.onSizeChangedObservable.notifyObservers(this);
  43811. this.disposeTextureAndPostProcesses();
  43812. this.createTextureAndPostProcesses();
  43813. }
  43814. };
  43815. /**
  43816. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43817. * @param mesh The mesh to exclude from the highlight layer
  43818. */
  43819. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43820. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43821. if (!meshExcluded) {
  43822. this._excludedMeshes[mesh.uniqueId] = {
  43823. mesh: mesh,
  43824. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43825. mesh.getEngine().setStencilBuffer(false);
  43826. }),
  43827. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43828. mesh.getEngine().setStencilBuffer(true);
  43829. }),
  43830. };
  43831. }
  43832. };
  43833. /**
  43834. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43835. * @param mesh The mesh to highlight
  43836. */
  43837. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43838. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43839. if (meshExcluded) {
  43840. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43841. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43842. }
  43843. this._excludedMeshes[mesh.uniqueId] = undefined;
  43844. };
  43845. /**
  43846. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43847. * @param mesh The mesh to highlight
  43848. * @param color The color of the highlight
  43849. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43850. */
  43851. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43852. var _this = this;
  43853. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43854. var meshHighlight = this._meshes[mesh.uniqueId];
  43855. if (meshHighlight) {
  43856. meshHighlight.color = color;
  43857. }
  43858. else {
  43859. this._meshes[mesh.uniqueId] = {
  43860. mesh: mesh,
  43861. color: color,
  43862. // Lambda required for capture due to Observable this context
  43863. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43864. if (_this._excludedMeshes[mesh.uniqueId]) {
  43865. _this.defaultStencilReference(mesh);
  43866. }
  43867. else {
  43868. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43869. }
  43870. }),
  43871. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43872. glowEmissiveOnly: glowEmissiveOnly
  43873. };
  43874. }
  43875. this._shouldRender = true;
  43876. };
  43877. /**
  43878. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43879. * @param mesh The mesh to highlight
  43880. */
  43881. HighlightLayer.prototype.removeMesh = function (mesh) {
  43882. var meshHighlight = this._meshes[mesh.uniqueId];
  43883. if (meshHighlight) {
  43884. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43885. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43886. }
  43887. this._meshes[mesh.uniqueId] = undefined;
  43888. this._shouldRender = false;
  43889. for (var meshHighlightToCheck in this._meshes) {
  43890. if (meshHighlightToCheck) {
  43891. this._shouldRender = true;
  43892. break;
  43893. }
  43894. }
  43895. };
  43896. /**
  43897. * Returns true if the layer contains information to display, otherwise false.
  43898. */
  43899. HighlightLayer.prototype.shouldRender = function () {
  43900. return this.isEnabled && this._shouldRender;
  43901. };
  43902. /**
  43903. * Sets the main texture desired size which is the closest power of two
  43904. * of the engine canvas size.
  43905. */
  43906. HighlightLayer.prototype.setMainTextureSize = function () {
  43907. if (this._options.mainTextureFixedSize) {
  43908. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43909. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43910. }
  43911. else {
  43912. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43913. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43914. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43915. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43916. }
  43917. };
  43918. /**
  43919. * Force the stencil to the normal expected value for none glowing parts
  43920. */
  43921. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43922. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43923. };
  43924. /**
  43925. * Dispose only the render target textures and post process.
  43926. */
  43927. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43928. this._blurTexture.dispose();
  43929. this._mainTexture.dispose();
  43930. this._downSamplePostprocess.dispose();
  43931. this._horizontalBlurPostprocess.dispose();
  43932. this._verticalBlurPostprocess.dispose();
  43933. };
  43934. /**
  43935. * Dispose the highlight layer and free resources.
  43936. */
  43937. HighlightLayer.prototype.dispose = function () {
  43938. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43939. if (vertexBuffer) {
  43940. vertexBuffer.dispose();
  43941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43942. }
  43943. if (this._indexBuffer) {
  43944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43945. this._indexBuffer = null;
  43946. }
  43947. // Clean textures and post processes
  43948. this.disposeTextureAndPostProcesses();
  43949. // Clean mesh references
  43950. for (var id in this._meshes) {
  43951. var meshHighlight = this._meshes[id];
  43952. if (meshHighlight && meshHighlight.mesh) {
  43953. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43954. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43955. }
  43956. }
  43957. this._meshes = null;
  43958. for (var id in this._excludedMeshes) {
  43959. var meshHighlight = this._excludedMeshes[id];
  43960. if (meshHighlight) {
  43961. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43962. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43963. }
  43964. }
  43965. this._excludedMeshes = null;
  43966. // Remove from scene
  43967. var index = this._scene.highlightLayers.indexOf(this, 0);
  43968. if (index > -1) {
  43969. this._scene.highlightLayers.splice(index, 1);
  43970. }
  43971. // Callback
  43972. this.onDisposeObservable.notifyObservers(this);
  43973. this.onDisposeObservable.clear();
  43974. this.onBeforeRenderMainTextureObservable.clear();
  43975. this.onBeforeBlurObservable.clear();
  43976. this.onBeforeComposeObservable.clear();
  43977. this.onAfterComposeObservable.clear();
  43978. this.onSizeChangedObservable.clear();
  43979. };
  43980. return HighlightLayer;
  43981. }());
  43982. /**
  43983. * The neutral color used during the preparation of the glow effect.
  43984. * This is black by default as the blend operation is a blend operation.
  43985. */
  43986. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43987. /**
  43988. * Stencil value used for glowing meshes.
  43989. */
  43990. HighlightLayer.glowingMeshStencilReference = 0x02;
  43991. /**
  43992. * Stencil value used for the other meshes in the scene.
  43993. */
  43994. HighlightLayer.normalMeshStencilReference = 0x01;
  43995. BABYLON.HighlightLayer = HighlightLayer;
  43996. })(BABYLON || (BABYLON = {}));
  43997. //# sourceMappingURL=babylon.highlightlayer.js.map
  43998. var BABYLON;
  43999. (function (BABYLON) {
  44000. var SIMDVector3 = (function () {
  44001. function SIMDVector3() {
  44002. }
  44003. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  44004. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  44005. };
  44006. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  44007. var m = transformation.m;
  44008. var m0 = SIMD.Float32x4.load(m, 0);
  44009. var m1 = SIMD.Float32x4.load(m, 4);
  44010. var m2 = SIMD.Float32x4.load(m, 8);
  44011. var m3 = SIMD.Float32x4.load(m, 12);
  44012. 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));
  44013. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  44014. result.x = SIMD.Float32x4.extractLane(r, 0);
  44015. result.y = SIMD.Float32x4.extractLane(r, 1);
  44016. result.z = SIMD.Float32x4.extractLane(r, 2);
  44017. };
  44018. return SIMDVector3;
  44019. }());
  44020. var SIMDMatrix = (function () {
  44021. function SIMDMatrix() {
  44022. }
  44023. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  44024. var tm = this.m;
  44025. var om = other.m;
  44026. var m0 = SIMD.Float32x4.load(om, 0);
  44027. var m1 = SIMD.Float32x4.load(om, 4);
  44028. var m2 = SIMD.Float32x4.load(om, 8);
  44029. var m3 = SIMD.Float32x4.load(om, 12);
  44030. for (var i = 0; i < 16; i += 4) {
  44031. 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)))));
  44032. }
  44033. return this;
  44034. };
  44035. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  44036. var src = this.m;
  44037. var dest = other.m;
  44038. // Load the 4 rows
  44039. var src0 = SIMD.Float32x4.load(src, 0);
  44040. var src1 = SIMD.Float32x4.load(src, 4);
  44041. var src2 = SIMD.Float32x4.load(src, 8);
  44042. var src3 = SIMD.Float32x4.load(src, 12);
  44043. // Transpose the source matrix. Sort of. Not a true transpose operation
  44044. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  44045. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  44046. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  44047. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  44048. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  44049. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  44050. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  44051. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  44052. // This is a true transposition, but it will lead to an incorrect result
  44053. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  44054. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  44055. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  44056. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  44057. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  44058. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  44059. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  44060. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  44061. // ----
  44062. tmp1 = SIMD.Float32x4.mul(row2, row3);
  44063. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44064. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  44065. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  44066. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44067. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  44068. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  44069. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  44070. // ----
  44071. tmp1 = SIMD.Float32x4.mul(row1, row2);
  44072. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44073. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  44074. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  44075. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44076. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  44077. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  44078. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  44079. // ----
  44080. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  44081. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44082. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  44083. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  44084. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  44085. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44086. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  44087. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  44088. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  44089. // ----
  44090. tmp1 = SIMD.Float32x4.mul(row0, row1);
  44091. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44092. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44093. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  44094. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44095. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44096. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  44097. // ----
  44098. tmp1 = SIMD.Float32x4.mul(row0, row3);
  44099. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44100. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  44101. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  44102. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44103. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  44104. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  44105. // ----
  44106. tmp1 = SIMD.Float32x4.mul(row0, row2);
  44107. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44108. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  44109. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  44110. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44111. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  44112. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  44113. // Compute determinant
  44114. var det = SIMD.Float32x4.mul(row0, minor0);
  44115. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  44116. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  44117. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  44118. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  44119. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  44120. // These shuffles aren't necessary if the faulty transposition is done
  44121. // up at the top of this function.
  44122. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  44123. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  44124. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  44125. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  44126. // Compute final values by multiplying with 1/det
  44127. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  44128. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  44129. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  44130. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  44131. return this;
  44132. };
  44133. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  44134. var out = result.m;
  44135. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  44136. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  44137. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  44138. // cc.kmVec3Subtract(f, pCenter, pEye);
  44139. var f = SIMD.Float32x4.sub(center, eye);
  44140. // cc.kmVec3Normalize(f, f);
  44141. var tmp = SIMD.Float32x4.mul(f, f);
  44142. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44143. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44144. // cc.kmVec3Assign(up, pUp);
  44145. // cc.kmVec3Normalize(up, up);
  44146. tmp = SIMD.Float32x4.mul(up, up);
  44147. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44148. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44149. // cc.kmVec3Cross(s, f, up);
  44150. 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)));
  44151. // cc.kmVec3Normalize(s, s);
  44152. tmp = SIMD.Float32x4.mul(s, s);
  44153. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44154. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44155. // cc.kmVec3Cross(u, s, f);
  44156. 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)));
  44157. // cc.kmVec3Normalize(s, s);
  44158. tmp = SIMD.Float32x4.mul(s, s);
  44159. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44160. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44161. var zero = SIMD.Float32x4.splat(0.0);
  44162. s = SIMD.Float32x4.neg(s);
  44163. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  44164. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  44165. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  44166. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  44167. 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);
  44168. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  44169. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  44170. 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)))));
  44171. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  44172. 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)))));
  44173. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  44174. 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)))));
  44175. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  44176. 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)))));
  44177. };
  44178. return SIMDMatrix;
  44179. }());
  44180. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  44181. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  44182. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  44183. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  44184. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  44185. var SIMDHelper = (function () {
  44186. function SIMDHelper() {
  44187. }
  44188. Object.defineProperty(SIMDHelper, "IsEnabled", {
  44189. get: function () {
  44190. return SIMDHelper._isEnabled;
  44191. },
  44192. enumerable: true,
  44193. configurable: true
  44194. });
  44195. SIMDHelper.DisableSIMD = function () {
  44196. // Replace functions
  44197. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  44198. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  44199. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  44200. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  44201. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  44202. SIMDHelper._isEnabled = false;
  44203. };
  44204. SIMDHelper.EnableSIMD = function () {
  44205. if (self.SIMD === undefined) {
  44206. return;
  44207. }
  44208. // check if polyfills needed
  44209. if (!self.Math.fround) {
  44210. self.Math.fround = (function (array) { return function (x) {
  44211. return array[0] = x, array[0];
  44212. }; })(new Float32Array(1));
  44213. }
  44214. if (!self.Math.imul) {
  44215. self.Math.imul = function (a, b) {
  44216. var ah = (a >>> 16) & 0xffff;
  44217. var al = a & 0xffff;
  44218. var bh = (b >>> 16) & 0xffff;
  44219. var bl = b & 0xffff;
  44220. // the shift by 0 fixes the sign on the high part
  44221. // the final |0 converts the unsigned value into a signed value
  44222. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  44223. };
  44224. }
  44225. // Replace functions
  44226. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  44227. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  44228. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  44229. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  44230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  44231. SIMDHelper._isEnabled = true;
  44232. };
  44233. return SIMDHelper;
  44234. }());
  44235. SIMDHelper._isEnabled = false;
  44236. BABYLON.SIMDHelper = SIMDHelper;
  44237. })(BABYLON || (BABYLON = {}));
  44238. //# sourceMappingURL=babylon.math.SIMD.js.map
  44239. var BABYLON;
  44240. (function (BABYLON) {
  44241. /**
  44242. * This class describe a rectangle that were added to the map.
  44243. * You have access to its coordinates either in pixel or normalized (UV)
  44244. */
  44245. var PackedRect = (function () {
  44246. function PackedRect(root, parent, pos, size) {
  44247. this._pos = pos;
  44248. this._size = size;
  44249. this._root = root;
  44250. this._parent = parent;
  44251. this._contentSize = null;
  44252. this._bottomNode = null;
  44253. this._leftNode = null;
  44254. this._initialSize = null;
  44255. this._rightNode = null;
  44256. }
  44257. Object.defineProperty(PackedRect.prototype, "pos", {
  44258. /**
  44259. * @returns the position of this node into the map
  44260. */
  44261. get: function () {
  44262. return this._pos;
  44263. },
  44264. enumerable: true,
  44265. configurable: true
  44266. });
  44267. Object.defineProperty(PackedRect.prototype, "contentSize", {
  44268. /**
  44269. * @returns the size of the rectangle this node handles
  44270. */
  44271. get: function () {
  44272. return this._contentSize;
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. /**
  44278. * Retrieve the inner position (considering the margin) and stores it into the res object
  44279. * @param res must be a valid Vector2 that will contain the inner position after this call
  44280. */
  44281. PackedRect.prototype.getInnerPosToRef = function (res) {
  44282. var m = this._root._margin;
  44283. res.x = this._pos.x + m;
  44284. res.y = this._pos.y + m;
  44285. };
  44286. /**
  44287. * Retrieve the inner size (considering the margin) and stores it into the res object
  44288. * @param res must be a valid Size that will contain the inner size after this call
  44289. */
  44290. PackedRect.prototype.getInnerSizeToRef = function (res) {
  44291. var m = this._root._margin;
  44292. res.width = this._contentSize.width - (m * 2);
  44293. res.height = this._contentSize.height - (m * 2);
  44294. };
  44295. Object.defineProperty(PackedRect.prototype, "UVs", {
  44296. /**
  44297. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  44298. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  44299. */
  44300. get: function () {
  44301. if (!this._contentSize) {
  44302. throw new Error("Can't compute UVs for this object because it's nor allocated");
  44303. }
  44304. return this.getUVsForCustomSize(this._contentSize);
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. /**
  44310. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  44311. * and then using only a part of the PackRect.
  44312. * This method will return the UVs for this part by given the custom size of what you really use
  44313. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  44314. */
  44315. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  44316. var mainWidth = this._root._size.width;
  44317. var mainHeight = this._root._size.height;
  44318. var margin = this._root._margin;
  44319. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  44320. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  44321. var uvs = new Array();
  44322. uvs.push(topLeft);
  44323. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  44324. uvs.push(rightBottom);
  44325. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  44326. return uvs;
  44327. };
  44328. /**
  44329. * Free this rectangle from the map.
  44330. * Call this method when you no longer need the rectangle to be in the map.
  44331. */
  44332. PackedRect.prototype.freeContent = function () {
  44333. if (!this.contentSize) {
  44334. return;
  44335. }
  44336. this._contentSize = null;
  44337. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  44338. this.attemptDefrag();
  44339. };
  44340. Object.defineProperty(PackedRect.prototype, "isUsed", {
  44341. get: function () {
  44342. return this._contentSize != null || this._leftNode != null;
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  44348. var node = this.findNode(contentSize);
  44349. // Not enough space...
  44350. if (!node) {
  44351. return null;
  44352. }
  44353. node.splitNode(contentSize);
  44354. return node;
  44355. };
  44356. PackedRect.prototype.findNode = function (size) {
  44357. var resNode = null;
  44358. var margin = this._root._margin * 2;
  44359. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  44360. if (this.isUsed) {
  44361. if (this._leftNode) {
  44362. resNode = this._leftNode.findNode(size);
  44363. }
  44364. if (!resNode && this._rightNode) {
  44365. resNode = this._rightNode.findNode(size);
  44366. }
  44367. if (!resNode && this._bottomNode) {
  44368. resNode = this._bottomNode.findNode(size);
  44369. }
  44370. }
  44371. else if (this._initialSize) {
  44372. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  44373. resNode = this;
  44374. }
  44375. else {
  44376. return null;
  44377. }
  44378. }
  44379. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  44380. resNode = this;
  44381. }
  44382. return resNode;
  44383. };
  44384. PackedRect.prototype.splitNode = function (contentSize) {
  44385. var cs = PackedRect.TpsSize;
  44386. var margin = this._root._margin * 2;
  44387. cs.copyFrom(contentSize);
  44388. cs.width += margin;
  44389. cs.height += margin;
  44390. // 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)
  44391. if (!this._contentSize && this._initialSize) {
  44392. this._contentSize = cs.clone();
  44393. 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));
  44394. return this._leftNode.splitNode(contentSize);
  44395. }
  44396. else {
  44397. this._contentSize = cs.clone();
  44398. this._initialSize = cs.clone();
  44399. if (cs.width !== this._size.width) {
  44400. 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));
  44401. }
  44402. if (cs.height !== this._size.height) {
  44403. 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));
  44404. }
  44405. return this;
  44406. }
  44407. };
  44408. PackedRect.prototype.attemptDefrag = function () {
  44409. if (!this.isUsed && this.isRecursiveFree) {
  44410. this.clearNode();
  44411. if (this._parent) {
  44412. this._parent.attemptDefrag();
  44413. }
  44414. }
  44415. };
  44416. PackedRect.prototype.clearNode = function () {
  44417. this._initialSize = null;
  44418. this._rightNode = null;
  44419. this._bottomNode = null;
  44420. };
  44421. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  44422. get: function () {
  44423. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. PackedRect.prototype.evalFreeSize = function (size) {
  44429. var levelSize = 0;
  44430. if (!this.isUsed) {
  44431. var margin = this._root._margin;
  44432. var is = this._initialSize;
  44433. if (is) {
  44434. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  44435. }
  44436. else {
  44437. var size_1 = this._size;
  44438. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  44439. }
  44440. }
  44441. if (this._rightNode) {
  44442. levelSize += this._rightNode.evalFreeSize(0);
  44443. }
  44444. if (this._bottomNode) {
  44445. levelSize += this._bottomNode.evalFreeSize(0);
  44446. }
  44447. return levelSize + size;
  44448. };
  44449. return PackedRect;
  44450. }());
  44451. PackedRect.TpsSize = BABYLON.Size.Zero();
  44452. BABYLON.PackedRect = PackedRect;
  44453. /**
  44454. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  44455. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  44456. * 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.
  44457. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  44458. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  44459. */
  44460. var RectPackingMap = (function (_super) {
  44461. __extends(RectPackingMap, _super);
  44462. /**
  44463. * Create an instance of the object with a dimension using the given size
  44464. * @param size The dimension of the rectangle that will contain all the sub ones.
  44465. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  44466. */
  44467. function RectPackingMap(size, margin) {
  44468. if (margin === void 0) { margin = 0; }
  44469. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  44470. _this._margin = margin;
  44471. _this._root = _this;
  44472. return _this;
  44473. }
  44474. /**
  44475. * Add a rectangle, finding the best location to store it into the map
  44476. * @param size the dimension of the rectangle to store
  44477. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  44478. */
  44479. RectPackingMap.prototype.addRect = function (size) {
  44480. var node = this.findAndSplitNode(size);
  44481. return node;
  44482. };
  44483. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  44484. /**
  44485. * Return the current space free normalized between [0;1]
  44486. * @returns {}
  44487. */
  44488. get: function () {
  44489. var freeSize = 0;
  44490. freeSize = this.evalFreeSize(freeSize);
  44491. return freeSize / (this._size.width * this._size.height);
  44492. },
  44493. enumerable: true,
  44494. configurable: true
  44495. });
  44496. return RectPackingMap;
  44497. }(PackedRect));
  44498. BABYLON.RectPackingMap = RectPackingMap;
  44499. })(BABYLON || (BABYLON = {}));
  44500. //# sourceMappingURL=babylon.rectPackingMap.js.map
  44501. var BABYLON;
  44502. (function (BABYLON) {
  44503. var DynamicFloatArrayElementInfo = (function () {
  44504. function DynamicFloatArrayElementInfo() {
  44505. }
  44506. return DynamicFloatArrayElementInfo;
  44507. }());
  44508. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44509. /**
  44510. * 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.
  44511. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44512. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44513. * 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.
  44514. * 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.
  44515. * 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".
  44516. */
  44517. var DynamicFloatArray = (function () {
  44518. /**
  44519. * Construct an instance of the dynamic float array
  44520. * @param stride size of one element in float (i.e. not bytes!)
  44521. * @param initialElementCount the number of available entries at construction
  44522. */
  44523. function DynamicFloatArray(stride, initialElementCount) {
  44524. this.compareValueOffset = null;
  44525. this.sortingAscending = true;
  44526. this._stride = stride;
  44527. this.buffer = new Float32Array(stride * initialElementCount);
  44528. this._lastUsed = 0;
  44529. this._firstFree = 0;
  44530. this._allEntries = new Array(initialElementCount);
  44531. this._freeEntries = new Array(initialElementCount);
  44532. for (var i = 0; i < initialElementCount; i++) {
  44533. var element = new DynamicFloatArrayElementInfo();
  44534. element.offset = i * stride;
  44535. this._allEntries[i] = element;
  44536. this._freeEntries[initialElementCount - i - 1] = element;
  44537. }
  44538. }
  44539. /**
  44540. * Allocate an element in the array.
  44541. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44542. * Beware, this offset may change when you call pack()
  44543. */
  44544. DynamicFloatArray.prototype.allocElement = function () {
  44545. if (this._freeEntries.length === 0) {
  44546. this._growBuffer();
  44547. }
  44548. var el = this._freeEntries.pop();
  44549. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44550. if (el.offset === this._firstFree) {
  44551. if (this._freeEntries.length > 0) {
  44552. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44553. }
  44554. else {
  44555. this._firstFree += this._stride;
  44556. }
  44557. }
  44558. return el;
  44559. };
  44560. /**
  44561. * Free the element corresponding to the given element info
  44562. * @param elInfo the element that describe the allocated element
  44563. */
  44564. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44565. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44566. this._freeEntries.push(elInfo);
  44567. };
  44568. /**
  44569. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44570. * 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().
  44571. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44572. */
  44573. DynamicFloatArray.prototype.pack = function () {
  44574. // no free slot? no need to pack
  44575. if (this._freeEntries.length === 0) {
  44576. return this.buffer;
  44577. }
  44578. // If the buffer is already packed the last used will always be lower than the first free
  44579. // 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.
  44580. if (this._lastUsed < this._firstFree) {
  44581. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44582. return elementsBuffer_1;
  44583. }
  44584. var s = this._stride;
  44585. // 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
  44586. var lastFree = new DynamicFloatArrayElementInfo();
  44587. lastFree.offset = this.totalElementCount * s;
  44588. this._freeEntries.push(lastFree);
  44589. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  44590. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44591. var firstFreeSlotOffset = sortedFree[0].offset;
  44592. var freeZoneSize = 1;
  44593. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  44594. var prevOffset = sortedFree[0].offset;
  44595. for (var i = 1; i < sortedFree.length; i++) {
  44596. // 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
  44597. if (firstFreeSlotOffset >= occupiedZoneSize) {
  44598. break;
  44599. }
  44600. var curFree = sortedFree[i];
  44601. var curOffset = curFree.offset;
  44602. // Compute the distance between this offset and the previous
  44603. var distance = curOffset - prevOffset;
  44604. // If the distance is the stride size, they are adjacent, it good, move to the next
  44605. if (distance === s) {
  44606. // Free zone is one element bigger
  44607. ++freeZoneSize;
  44608. // as we're about to iterate to the next, the cur becomes the previous...
  44609. prevOffset = curOffset;
  44610. continue;
  44611. }
  44612. // Distance is bigger, which means there's x element between the previous free and this one
  44613. var usedRange = (distance / s) - 1;
  44614. // Two cases the free zone is smaller than the data to move or bigger
  44615. // Copy what can fit in the free zone
  44616. var curMoveOffset = curOffset - s;
  44617. var copyCount = Math.min(freeZoneSize, usedRange);
  44618. for (var j = 0; j < copyCount; j++) {
  44619. var freeI = firstFreeSlotOffset / s;
  44620. var curI = curMoveOffset / s;
  44621. var moveEl = sortedAll[curI];
  44622. this._moveElement(moveEl, firstFreeSlotOffset);
  44623. var replacedEl = sortedAll[freeI];
  44624. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  44625. replacedEl.offset = curMoveOffset;
  44626. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  44627. sortedAll[freeI] = moveEl;
  44628. sortedAll[curI] = replacedEl;
  44629. curMoveOffset -= s;
  44630. firstFreeSlotOffset += s;
  44631. }
  44632. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  44633. if (freeZoneSize <= usedRange) {
  44634. firstFreeSlotOffset = curMoveOffset + s;
  44635. freeZoneSize = 1 + copyCount;
  44636. }
  44637. else {
  44638. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  44639. }
  44640. // as we're about to iterate to the next, the cur becomes the previous...
  44641. prevOffset = curOffset;
  44642. }
  44643. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  44644. this._lastUsed = firstFreeSlotOffset - s;
  44645. this._firstFree = firstFreeSlotOffset;
  44646. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  44647. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  44648. this._allEntries = sortedAll;
  44649. return elementsBuffer;
  44650. };
  44651. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  44652. for (var i = 0; i < this._stride; i++) {
  44653. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  44654. }
  44655. element.offset = destOffset;
  44656. };
  44657. DynamicFloatArray.prototype._growBuffer = function () {
  44658. // Allocate the new buffer with 50% more entries, copy the content of the current one
  44659. var newElCount = Math.floor(this.totalElementCount * 1.5);
  44660. var newBuffer = new Float32Array(newElCount * this._stride);
  44661. newBuffer.set(this.buffer);
  44662. var curCount = this.totalElementCount;
  44663. var addedCount = newElCount - this.totalElementCount;
  44664. for (var i = 0; i < addedCount; i++) {
  44665. var element = new DynamicFloatArrayElementInfo();
  44666. element.offset = (curCount + i) * this.stride;
  44667. this._allEntries.push(element);
  44668. this._freeEntries[addedCount - i - 1] = element;
  44669. }
  44670. this._firstFree = curCount * this.stride;
  44671. this.buffer = newBuffer;
  44672. };
  44673. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  44674. /**
  44675. * Get the total count of entries that can fit in the current buffer
  44676. * @returns the elements count
  44677. */
  44678. get: function () {
  44679. return this._allEntries.length;
  44680. },
  44681. enumerable: true,
  44682. configurable: true
  44683. });
  44684. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  44685. /**
  44686. * Get the count of free entries that can still be allocated without resizing the buffer
  44687. * @returns the free elements count
  44688. */
  44689. get: function () {
  44690. return this._freeEntries.length;
  44691. },
  44692. enumerable: true,
  44693. configurable: true
  44694. });
  44695. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  44696. /**
  44697. * Get the count of allocated elements
  44698. * @returns the allocated elements count
  44699. */
  44700. get: function () {
  44701. return this._allEntries.length - this._freeEntries.length;
  44702. },
  44703. enumerable: true,
  44704. configurable: true
  44705. });
  44706. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  44707. /**
  44708. * Return the size of one element in float
  44709. * @returns the size in float
  44710. */
  44711. get: function () {
  44712. return this._stride;
  44713. },
  44714. enumerable: true,
  44715. configurable: true
  44716. });
  44717. DynamicFloatArray.prototype.sort = function () {
  44718. var _this = this;
  44719. if (!this.compareValueOffset) {
  44720. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  44721. }
  44722. var count = this.usedElementCount;
  44723. // Do we have to (re)create the sort table?
  44724. if (!this._sortTable || this._sortTable.length < count) {
  44725. // 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...
  44726. var newCount = Math.min(this.totalElementCount, count * 2);
  44727. this._sortTable = new Array(newCount);
  44728. }
  44729. if (!this._sortedTable || this._sortedTable.length !== count) {
  44730. this._sortedTable = new Array(count);
  44731. }
  44732. // Because, you know...
  44733. this.pack();
  44734. //let stride = this.stride;
  44735. //for (let i = 0; i < count; i++) {
  44736. // let si = this._sortTable[i];
  44737. // if (!si) {
  44738. // si = new SortInfo();
  44739. // this._sortTable[i] = si;
  44740. // }
  44741. // si.entry = this._allEntries[i];
  44742. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  44743. // si.swapedOffset = null;
  44744. // this._sortedTable[i] = si;
  44745. //}
  44746. var curOffset = 0;
  44747. var stride = this.stride;
  44748. for (var i = 0; i < count; i++, curOffset += stride) {
  44749. var si = this._sortTable[i];
  44750. if (!si) {
  44751. si = new SortInfo();
  44752. this._sortTable[i] = si;
  44753. }
  44754. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  44755. si.offset = curOffset;
  44756. si.swapedOffset = null;
  44757. this._sortedTable[i] = si;
  44758. }
  44759. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  44760. if (this.sortingAscending) {
  44761. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  44762. }
  44763. else {
  44764. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  44765. }
  44766. var swapElements = function (src, dst) {
  44767. for (var i = 0; i < stride; i++) {
  44768. var tps = _this.buffer[dst + i];
  44769. _this.buffer[dst + i] = _this.buffer[src + i];
  44770. _this.buffer[src + i] = tps;
  44771. }
  44772. };
  44773. // 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:
  44774. // 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),
  44775. // and I still want something with a good algorithm complexity.
  44776. // 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,
  44777. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  44778. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  44779. // 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
  44780. // until we find a SortInfo object without a swapedOffset which means we got the right location
  44781. // 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
  44782. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  44783. for (var i = 0; i < count; i++) {
  44784. // Get the element to move
  44785. var sourceSI = this._sortedTable[i];
  44786. var destSI = this._sortTable[i];
  44787. var sourceOff = sourceSI.offset;
  44788. // If the source changed location, find the new one
  44789. if (sourceSI.swapedOffset) {
  44790. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  44791. var curSI = sourceSI;
  44792. while (curSI.swapedOffset) {
  44793. curSI = this._sortTable[curSI.swapedOffset / stride];
  44794. }
  44795. // Finally get the right location
  44796. sourceOff = curSI.offset;
  44797. }
  44798. // Tag the element being replaced with its new location
  44799. destSI.swapedOffset = sourceOff;
  44800. // Swap elements (only if needed)
  44801. if (sourceOff !== destSI.offset) {
  44802. swapElements(sourceOff, destSI.offset);
  44803. }
  44804. // Update the offset in the corresponding DFAE
  44805. //sourceSI.entry.offset = destSI.entry.offset;
  44806. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44807. }
  44808. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44809. return true;
  44810. };
  44811. return DynamicFloatArray;
  44812. }());
  44813. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44814. var SortInfo = (function () {
  44815. function SortInfo() {
  44816. this.compareData = this.offset = this.swapedOffset = null;
  44817. }
  44818. return SortInfo;
  44819. }());
  44820. })(BABYLON || (BABYLON = {}));
  44821. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44822. var BABYLON;
  44823. (function (BABYLON) {
  44824. var MapTexture = (function (_super) {
  44825. __extends(MapTexture, _super);
  44826. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  44827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44828. if (useMipMap === void 0) { useMipMap = false; }
  44829. if (margin === void 0) { margin = 0; }
  44830. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44831. _this.name = name;
  44832. _this._size = size;
  44833. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44834. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44835. // Create the rectPackMap that will allocate portion of the texture
  44836. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  44837. // Create the texture that will store the content
  44838. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44839. return _this;
  44840. }
  44841. /**
  44842. * Allocate a rectangle of a given size in the texture map
  44843. * @param size the size of the rectangle to allocation
  44844. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44845. */
  44846. MapTexture.prototype.allocateRect = function (size) {
  44847. return this._rectPackingMap.addRect(size);
  44848. };
  44849. /**
  44850. * Free a given rectangle from the texture map
  44851. * @param rectInfo the instance corresponding to the rect to free.
  44852. */
  44853. MapTexture.prototype.freeRect = function (rectInfo) {
  44854. if (rectInfo) {
  44855. rectInfo.freeContent();
  44856. }
  44857. };
  44858. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44859. /**
  44860. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44861. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44862. * @returns {}
  44863. */
  44864. get: function () {
  44865. return this._rectPackingMap.freeSpace;
  44866. },
  44867. enumerable: true,
  44868. configurable: true
  44869. });
  44870. /**
  44871. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44872. * 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.
  44873. * Don't forget to call unbindTexture when you're done rendering
  44874. * @param rect the zone to render to
  44875. * @param clear true to clear the portion's color/depth data
  44876. */
  44877. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44878. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44879. };
  44880. /**
  44881. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44882. * 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.
  44883. * Don't forget to call unbindTexture when you're done rendering
  44884. * @param pos the position into the texture
  44885. * @param size the portion to fit the clip space to
  44886. * @param clear true to clear the portion's color/depth data
  44887. */
  44888. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44889. var engine = this.getScene().getEngine();
  44890. engine.bindFramebuffer(this._texture);
  44891. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44892. if (clear) {
  44893. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44894. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44895. }
  44896. };
  44897. /**
  44898. * Unbind the texture map from the rendering engine.
  44899. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44900. * @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.
  44901. */
  44902. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44903. // Dump ?
  44904. if (dumpForDebug) {
  44905. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44906. }
  44907. var engine = this.getScene().getEngine();
  44908. if (this._replacedViewport) {
  44909. engine.setViewport(this._replacedViewport);
  44910. this._replacedViewport = null;
  44911. }
  44912. engine.unBindFramebuffer(this._texture);
  44913. };
  44914. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44915. get: function () {
  44916. return false;
  44917. },
  44918. enumerable: true,
  44919. configurable: true
  44920. });
  44921. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44922. // Anyway, there's not much point to use this method for this kind of texture I guess
  44923. MapTexture.prototype.clone = function () {
  44924. return null;
  44925. };
  44926. return MapTexture;
  44927. }(BABYLON.Texture));
  44928. BABYLON.MapTexture = MapTexture;
  44929. })(BABYLON || (BABYLON = {}));
  44930. //# sourceMappingURL=babylon.mapTexture.js.map
  44931. var BABYLON;
  44932. (function (BABYLON) {
  44933. var ShaderMaterial = (function (_super) {
  44934. __extends(ShaderMaterial, _super);
  44935. function ShaderMaterial(name, scene, shaderPath, options) {
  44936. var _this = _super.call(this, name, scene) || this;
  44937. _this._textures = {};
  44938. _this._textureArrays = {};
  44939. _this._floats = {};
  44940. _this._floatsArrays = {};
  44941. _this._colors3 = {};
  44942. _this._colors4 = {};
  44943. _this._vectors2 = {};
  44944. _this._vectors3 = {};
  44945. _this._vectors4 = {};
  44946. _this._matrices = {};
  44947. _this._matrices3x3 = {};
  44948. _this._matrices2x2 = {};
  44949. _this._vectors3Arrays = {};
  44950. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44951. _this._shaderPath = shaderPath;
  44952. options.needAlphaBlending = options.needAlphaBlending || false;
  44953. options.needAlphaTesting = options.needAlphaTesting || false;
  44954. options.attributes = options.attributes || ["position", "normal", "uv"];
  44955. options.uniforms = options.uniforms || ["worldViewProjection"];
  44956. options.samplers = options.samplers || [];
  44957. options.defines = options.defines || [];
  44958. _this._options = options;
  44959. return _this;
  44960. }
  44961. ShaderMaterial.prototype.getClassName = function () {
  44962. return "ShaderMaterial";
  44963. };
  44964. ShaderMaterial.prototype.needAlphaBlending = function () {
  44965. return this._options.needAlphaBlending;
  44966. };
  44967. ShaderMaterial.prototype.needAlphaTesting = function () {
  44968. return this._options.needAlphaTesting;
  44969. };
  44970. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44971. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44972. this._options.uniforms.push(uniformName);
  44973. }
  44974. };
  44975. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44976. if (this._options.samplers.indexOf(name) === -1) {
  44977. this._options.samplers.push(name);
  44978. }
  44979. this._textures[name] = texture;
  44980. return this;
  44981. };
  44982. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44983. if (this._options.samplers.indexOf(name) === -1) {
  44984. this._options.samplers.push(name);
  44985. }
  44986. this._checkUniform(name);
  44987. this._textureArrays[name] = textures;
  44988. return this;
  44989. };
  44990. ShaderMaterial.prototype.setFloat = function (name, value) {
  44991. this._checkUniform(name);
  44992. this._floats[name] = value;
  44993. return this;
  44994. };
  44995. ShaderMaterial.prototype.setFloats = function (name, value) {
  44996. this._checkUniform(name);
  44997. this._floatsArrays[name] = value;
  44998. return this;
  44999. };
  45000. ShaderMaterial.prototype.setColor3 = function (name, value) {
  45001. this._checkUniform(name);
  45002. this._colors3[name] = value;
  45003. return this;
  45004. };
  45005. ShaderMaterial.prototype.setColor4 = function (name, value) {
  45006. this._checkUniform(name);
  45007. this._colors4[name] = value;
  45008. return this;
  45009. };
  45010. ShaderMaterial.prototype.setVector2 = function (name, value) {
  45011. this._checkUniform(name);
  45012. this._vectors2[name] = value;
  45013. return this;
  45014. };
  45015. ShaderMaterial.prototype.setVector3 = function (name, value) {
  45016. this._checkUniform(name);
  45017. this._vectors3[name] = value;
  45018. return this;
  45019. };
  45020. ShaderMaterial.prototype.setVector4 = function (name, value) {
  45021. this._checkUniform(name);
  45022. this._vectors4[name] = value;
  45023. return this;
  45024. };
  45025. ShaderMaterial.prototype.setMatrix = function (name, value) {
  45026. this._checkUniform(name);
  45027. this._matrices[name] = value;
  45028. return this;
  45029. };
  45030. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  45031. this._checkUniform(name);
  45032. this._matrices3x3[name] = value;
  45033. return this;
  45034. };
  45035. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  45036. this._checkUniform(name);
  45037. this._matrices2x2[name] = value;
  45038. return this;
  45039. };
  45040. ShaderMaterial.prototype.setArray3 = function (name, value) {
  45041. this._checkUniform(name);
  45042. this._vectors3Arrays[name] = value;
  45043. return this;
  45044. };
  45045. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45046. if (!mesh) {
  45047. return true;
  45048. }
  45049. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  45050. return false;
  45051. }
  45052. return false;
  45053. };
  45054. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45055. var scene = this.getScene();
  45056. var engine = scene.getEngine();
  45057. if (!this.checkReadyOnEveryCall) {
  45058. if (this._renderId === scene.getRenderId()) {
  45059. if (this._checkCache(scene, mesh, useInstances)) {
  45060. return true;
  45061. }
  45062. }
  45063. }
  45064. // Instances
  45065. var defines = [];
  45066. var fallbacks = new BABYLON.EffectFallbacks();
  45067. if (useInstances) {
  45068. defines.push("#define INSTANCES");
  45069. }
  45070. for (var index = 0; index < this._options.defines.length; index++) {
  45071. defines.push(this._options.defines[index]);
  45072. }
  45073. // Bones
  45074. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45075. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45076. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45077. fallbacks.addCPUSkinningFallback(0, mesh);
  45078. }
  45079. // Textures
  45080. for (var name in this._textures) {
  45081. if (!this._textures[name].isReady()) {
  45082. return false;
  45083. }
  45084. }
  45085. // Alpha test
  45086. if (engine.getAlphaTesting()) {
  45087. defines.push("#define ALPHATEST");
  45088. }
  45089. var previousEffect = this._effect;
  45090. var join = defines.join("\n");
  45091. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  45092. if (!this._effect.isReady()) {
  45093. return false;
  45094. }
  45095. if (previousEffect !== this._effect) {
  45096. scene.resetCachedMaterial();
  45097. }
  45098. this._renderId = scene.getRenderId();
  45099. return true;
  45100. };
  45101. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45102. var scene = this.getScene();
  45103. if (this._options.uniforms.indexOf("world") !== -1) {
  45104. this._effect.setMatrix("world", world);
  45105. }
  45106. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45107. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45108. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45109. }
  45110. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45111. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45112. }
  45113. };
  45114. ShaderMaterial.prototype.bind = function (world, mesh) {
  45115. // Std values
  45116. this.bindOnlyWorldMatrix(world);
  45117. if (this.getScene().getCachedMaterial() !== this) {
  45118. if (this._options.uniforms.indexOf("view") !== -1) {
  45119. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45120. }
  45121. if (this._options.uniforms.indexOf("projection") !== -1) {
  45122. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45123. }
  45124. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45125. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45126. }
  45127. // Bones
  45128. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45129. var name;
  45130. // Texture
  45131. for (name in this._textures) {
  45132. this._effect.setTexture(name, this._textures[name]);
  45133. }
  45134. // Texture arrays
  45135. for (name in this._textureArrays) {
  45136. this._effect.setTextureArray(name, this._textureArrays[name]);
  45137. }
  45138. // Float
  45139. for (name in this._floats) {
  45140. this._effect.setFloat(name, this._floats[name]);
  45141. }
  45142. // Float s
  45143. for (name in this._floatsArrays) {
  45144. this._effect.setArray(name, this._floatsArrays[name]);
  45145. }
  45146. // Color3
  45147. for (name in this._colors3) {
  45148. this._effect.setColor3(name, this._colors3[name]);
  45149. }
  45150. // Color4
  45151. for (name in this._colors4) {
  45152. var color = this._colors4[name];
  45153. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45154. }
  45155. // Vector2
  45156. for (name in this._vectors2) {
  45157. this._effect.setVector2(name, this._vectors2[name]);
  45158. }
  45159. // Vector3
  45160. for (name in this._vectors3) {
  45161. this._effect.setVector3(name, this._vectors3[name]);
  45162. }
  45163. // Vector4
  45164. for (name in this._vectors4) {
  45165. this._effect.setVector4(name, this._vectors4[name]);
  45166. }
  45167. // Matrix
  45168. for (name in this._matrices) {
  45169. this._effect.setMatrix(name, this._matrices[name]);
  45170. }
  45171. // Matrix 3x3
  45172. for (name in this._matrices3x3) {
  45173. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45174. }
  45175. // Matrix 2x2
  45176. for (name in this._matrices2x2) {
  45177. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45178. }
  45179. // Vector3Array
  45180. for (name in this._vectors3Arrays) {
  45181. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45182. }
  45183. }
  45184. _super.prototype.bind.call(this, world, mesh);
  45185. };
  45186. ShaderMaterial.prototype.clone = function (name) {
  45187. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45188. return newShaderMaterial;
  45189. };
  45190. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45191. if (forceDisposeTextures) {
  45192. var name;
  45193. for (name in this._textures) {
  45194. this._textures[name].dispose();
  45195. }
  45196. for (name in this._textureArrays) {
  45197. var array = this._textureArrays[name];
  45198. for (var index = 0; index < array.length; index++) {
  45199. array[index].dispose();
  45200. }
  45201. }
  45202. }
  45203. this._textures = {};
  45204. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45205. };
  45206. ShaderMaterial.prototype.serialize = function () {
  45207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45208. serializationObject.customType = "BABYLON.ShaderMaterial";
  45209. serializationObject.options = this._options;
  45210. serializationObject.shaderPath = this._shaderPath;
  45211. var name;
  45212. // Texture
  45213. serializationObject.textures = {};
  45214. for (name in this._textures) {
  45215. serializationObject.textures[name] = this._textures[name].serialize();
  45216. }
  45217. // Texture arrays
  45218. serializationObject.textureArrays = {};
  45219. for (name in this._textureArrays) {
  45220. serializationObject.textureArrays[name] = [];
  45221. var array = this._textureArrays[name];
  45222. for (var index = 0; index < array.length; index++) {
  45223. serializationObject.textureArrays[name].push(array[index].serialize());
  45224. }
  45225. }
  45226. // Float
  45227. serializationObject.floats = {};
  45228. for (name in this._floats) {
  45229. serializationObject.floats[name] = this._floats[name];
  45230. }
  45231. // Float s
  45232. serializationObject.floatArrays = {};
  45233. for (name in this._floatsArrays) {
  45234. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45235. }
  45236. // Color3
  45237. serializationObject.colors3 = {};
  45238. for (name in this._colors3) {
  45239. serializationObject.colors3[name] = this._colors3[name].asArray();
  45240. }
  45241. // Color4
  45242. serializationObject.colors4 = {};
  45243. for (name in this._colors4) {
  45244. serializationObject.colors4[name] = this._colors4[name].asArray();
  45245. }
  45246. // Vector2
  45247. serializationObject.vectors2 = {};
  45248. for (name in this._vectors2) {
  45249. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45250. }
  45251. // Vector3
  45252. serializationObject.vectors3 = {};
  45253. for (name in this._vectors3) {
  45254. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45255. }
  45256. // Vector4
  45257. serializationObject.vectors4 = {};
  45258. for (name in this._vectors4) {
  45259. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45260. }
  45261. // Matrix
  45262. serializationObject.matrices = {};
  45263. for (name in this._matrices) {
  45264. serializationObject.matrices[name] = this._matrices[name].asArray();
  45265. }
  45266. // Matrix 3x3
  45267. serializationObject.matrices3x3 = {};
  45268. for (name in this._matrices3x3) {
  45269. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45270. }
  45271. // Matrix 2x2
  45272. serializationObject.matrices2x2 = {};
  45273. for (name in this._matrices2x2) {
  45274. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45275. }
  45276. // Vector3Array
  45277. serializationObject.vectors3Arrays = {};
  45278. for (name in this._vectors3Arrays) {
  45279. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45280. }
  45281. return serializationObject;
  45282. };
  45283. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45284. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45285. var name;
  45286. // Texture
  45287. for (name in source.textures) {
  45288. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45289. }
  45290. // Texture arrays
  45291. for (name in source.textureArrays) {
  45292. var array = source.textureArrays[name];
  45293. var textureArray = new Array();
  45294. for (var index = 0; index < array.length; index++) {
  45295. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45296. }
  45297. material.setTextureArray(name, textureArray);
  45298. }
  45299. // Float
  45300. for (name in source.floats) {
  45301. material.setFloat(name, source.floats[name]);
  45302. }
  45303. // Float s
  45304. for (name in source.floatsArrays) {
  45305. material.setFloats(name, source.floatsArrays[name]);
  45306. }
  45307. // Color3
  45308. for (name in source.colors3) {
  45309. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45310. }
  45311. // Color4
  45312. for (name in source.colors4) {
  45313. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45314. }
  45315. // Vector2
  45316. for (name in source.vectors2) {
  45317. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45318. }
  45319. // Vector3
  45320. for (name in source.vectors3) {
  45321. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45322. }
  45323. // Vector4
  45324. for (name in source.vectors4) {
  45325. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45326. }
  45327. // Matrix
  45328. for (name in source.matrices) {
  45329. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45330. }
  45331. // Matrix 3x3
  45332. for (name in source.matrices3x3) {
  45333. material.setMatrix3x3(name, source.matrices3x3[name]);
  45334. }
  45335. // Matrix 2x2
  45336. for (name in source.matrices2x2) {
  45337. material.setMatrix2x2(name, source.matrices2x2[name]);
  45338. }
  45339. // Vector3Array
  45340. for (name in source.vectors3Arrays) {
  45341. material.setArray3(name, source.vectors3Arrays[name]);
  45342. }
  45343. return material;
  45344. };
  45345. return ShaderMaterial;
  45346. }(BABYLON.Material));
  45347. BABYLON.ShaderMaterial = ShaderMaterial;
  45348. })(BABYLON || (BABYLON = {}));
  45349. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45350. var BABYLON;
  45351. (function (BABYLON) {
  45352. var Internals;
  45353. (function (Internals) {
  45354. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45355. // All values and structures referenced from:
  45356. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45357. var DDS_MAGIC = 0x20534444;
  45358. 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;
  45359. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45360. 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;
  45361. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45362. function FourCCToInt32(value) {
  45363. return value.charCodeAt(0) +
  45364. (value.charCodeAt(1) << 8) +
  45365. (value.charCodeAt(2) << 16) +
  45366. (value.charCodeAt(3) << 24);
  45367. }
  45368. function Int32ToFourCC(value) {
  45369. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45370. }
  45371. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45372. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45373. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45374. var headerLengthInt = 31; // The header length in 32 bit ints
  45375. // Offsets into the header array
  45376. var off_magic = 0;
  45377. var off_size = 1;
  45378. var off_flags = 2;
  45379. var off_height = 3;
  45380. var off_width = 4;
  45381. var off_mipmapCount = 7;
  45382. var off_pfFlags = 20;
  45383. var off_pfFourCC = 21;
  45384. var off_RGBbpp = 22;
  45385. var off_RMask = 23;
  45386. var off_GMask = 24;
  45387. var off_BMask = 25;
  45388. var off_AMask = 26;
  45389. var off_caps1 = 27;
  45390. var off_caps2 = 28;
  45391. ;
  45392. var DDSTools = (function () {
  45393. function DDSTools() {
  45394. }
  45395. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45396. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45397. var mipmapCount = 1;
  45398. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45399. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45400. }
  45401. return {
  45402. width: header[off_width],
  45403. height: header[off_height],
  45404. mipmapCount: mipmapCount,
  45405. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45406. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45407. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45408. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45409. };
  45410. };
  45411. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45412. var byteArray = new Uint8Array(dataLength);
  45413. var srcData = new Uint8Array(arrayBuffer);
  45414. var index = 0;
  45415. for (var y = height - 1; y >= 0; y--) {
  45416. for (var x = 0; x < width; x++) {
  45417. var srcPos = dataOffset + (x + y * width) * 4;
  45418. byteArray[index + 2] = srcData[srcPos];
  45419. byteArray[index + 1] = srcData[srcPos + 1];
  45420. byteArray[index] = srcData[srcPos + 2];
  45421. byteArray[index + 3] = srcData[srcPos + 3];
  45422. index += 4;
  45423. }
  45424. }
  45425. return byteArray;
  45426. };
  45427. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45428. var byteArray = new Uint8Array(dataLength);
  45429. var srcData = new Uint8Array(arrayBuffer);
  45430. var index = 0;
  45431. for (var y = height - 1; y >= 0; y--) {
  45432. for (var x = 0; x < width; x++) {
  45433. var srcPos = dataOffset + (x + y * width) * 3;
  45434. byteArray[index + 2] = srcData[srcPos];
  45435. byteArray[index + 1] = srcData[srcPos + 1];
  45436. byteArray[index] = srcData[srcPos + 2];
  45437. index += 3;
  45438. }
  45439. }
  45440. return byteArray;
  45441. };
  45442. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45443. var byteArray = new Uint8Array(dataLength);
  45444. var srcData = new Uint8Array(arrayBuffer);
  45445. var index = 0;
  45446. for (var y = height - 1; y >= 0; y--) {
  45447. for (var x = 0; x < width; x++) {
  45448. var srcPos = dataOffset + (x + y * width);
  45449. byteArray[index] = srcData[srcPos];
  45450. index++;
  45451. }
  45452. }
  45453. return byteArray;
  45454. };
  45455. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45456. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45457. if (header[off_magic] != DDS_MAGIC) {
  45458. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45459. return;
  45460. }
  45461. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45462. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45463. return;
  45464. }
  45465. if (info.isFourCC) {
  45466. fourCC = header[off_pfFourCC];
  45467. switch (fourCC) {
  45468. case FOURCC_DXT1:
  45469. blockBytes = 8;
  45470. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45471. break;
  45472. case FOURCC_DXT3:
  45473. blockBytes = 16;
  45474. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45475. break;
  45476. case FOURCC_DXT5:
  45477. blockBytes = 16;
  45478. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45479. break;
  45480. default:
  45481. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45482. return;
  45483. }
  45484. }
  45485. mipmapCount = 1;
  45486. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45487. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45488. }
  45489. var bpp = header[off_RGBbpp];
  45490. for (var face = 0; face < faces; face++) {
  45491. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45492. width = header[off_width];
  45493. height = header[off_height];
  45494. dataOffset = header[off_size] + 4;
  45495. for (i = 0; i < mipmapCount; ++i) {
  45496. if (info.isRGB) {
  45497. if (bpp === 24) {
  45498. dataLength = width * height * 3;
  45499. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45500. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45501. }
  45502. else {
  45503. dataLength = width * height * 4;
  45504. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45505. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45506. }
  45507. }
  45508. else if (info.isLuminance) {
  45509. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45510. var unpaddedRowSize = width;
  45511. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45512. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45513. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45514. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45515. }
  45516. else {
  45517. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45518. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45519. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45520. }
  45521. dataOffset += dataLength;
  45522. width *= 0.5;
  45523. height *= 0.5;
  45524. width = Math.max(1.0, width);
  45525. height = Math.max(1.0, height);
  45526. }
  45527. }
  45528. };
  45529. return DDSTools;
  45530. }());
  45531. Internals.DDSTools = DDSTools;
  45532. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45533. })(BABYLON || (BABYLON = {}));
  45534. //# sourceMappingURL=babylon.tools.dds.js.map
  45535. var BABYLON;
  45536. (function (BABYLON) {
  45537. var Internals;
  45538. (function (Internals) {
  45539. /**
  45540. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  45541. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  45542. */
  45543. var KhronosTextureContainer = (function () {
  45544. /**
  45545. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  45546. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  45547. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  45548. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  45549. */
  45550. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  45551. this.arrayBuffer = arrayBuffer;
  45552. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  45553. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  45554. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  45555. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  45556. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  45557. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  45558. BABYLON.Tools.Error("texture missing KTX identifier");
  45559. return;
  45560. }
  45561. // load the reset of the header in native 32 bit int
  45562. var header = new Int32Array(this.arrayBuffer, 12, 13);
  45563. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  45564. var oppositeEndianess = header[0] === 0x01020304;
  45565. // read all the header elements in order they exist in the file, without modification (sans endainness)
  45566. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  45567. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  45568. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  45569. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  45570. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  45571. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  45572. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  45573. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  45574. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  45575. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  45576. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  45577. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  45578. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  45579. if (this.glType !== 0) {
  45580. BABYLON.Tools.Error("only compressed formats currently supported");
  45581. return;
  45582. }
  45583. else {
  45584. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  45585. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  45586. }
  45587. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  45588. BABYLON.Tools.Error("only 2D textures currently supported");
  45589. return;
  45590. }
  45591. if (this.numberOfArrayElements !== 0) {
  45592. BABYLON.Tools.Error("texture arrays not currently supported");
  45593. return;
  45594. }
  45595. if (this.numberOfFaces !== facesExpected) {
  45596. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  45597. return;
  45598. }
  45599. // we now have a completely validated file, so could use existence of loadType as success
  45600. // would need to make this more elaborate & adjust checks above to support more than one load type
  45601. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  45602. }
  45603. // not as fast hardware based, but will probably never need to use
  45604. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  45605. return ((val & 0xFF) << 24)
  45606. | ((val & 0xFF00) << 8)
  45607. | ((val >> 8) & 0xFF00)
  45608. | ((val >> 24) & 0xFF);
  45609. };
  45610. /**
  45611. * It is assumed that the texture has already been created & is currently bound
  45612. */
  45613. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  45614. switch (this.loadType) {
  45615. case KhronosTextureContainer.COMPRESSED_2D:
  45616. this._upload2DCompressedLevels(gl, loadMipmaps);
  45617. break;
  45618. case KhronosTextureContainer.TEX_2D:
  45619. case KhronosTextureContainer.COMPRESSED_3D:
  45620. case KhronosTextureContainer.TEX_3D:
  45621. }
  45622. };
  45623. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  45624. // initialize width & height for level 1
  45625. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  45626. var width = this.pixelWidth;
  45627. var height = this.pixelHeight;
  45628. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  45629. for (var level = 0; level < mipmapCount; level++) {
  45630. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  45631. for (var face = 0; face < this.numberOfFaces; face++) {
  45632. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45633. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  45634. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  45635. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  45636. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  45637. }
  45638. width = Math.max(1.0, width * 0.5);
  45639. height = Math.max(1.0, height * 0.5);
  45640. }
  45641. };
  45642. return KhronosTextureContainer;
  45643. }());
  45644. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  45645. // load types
  45646. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  45647. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  45648. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  45649. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  45650. Internals.KhronosTextureContainer = KhronosTextureContainer;
  45651. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45652. })(BABYLON || (BABYLON = {}));
  45653. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  45654. var BABYLON;
  45655. (function (BABYLON) {
  45656. var CannonJSPlugin = (function () {
  45657. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45658. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45659. if (iterations === void 0) { iterations = 10; }
  45660. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45661. this.name = "CannonJSPlugin";
  45662. this._physicsMaterials = [];
  45663. this._fixedTimeStep = 1 / 60;
  45664. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45665. this._currentCollisionGroup = 2;
  45666. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45667. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45668. this._tmpPosition = BABYLON.Vector3.Zero();
  45669. this._tmpQuaternion = new BABYLON.Quaternion();
  45670. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45671. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45672. this._tmpUnityRotation = new BABYLON.Quaternion();
  45673. if (!this.isSupported()) {
  45674. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45675. return;
  45676. }
  45677. this.world = new CANNON.World();
  45678. this.world.broadphase = new CANNON.NaiveBroadphase();
  45679. this.world.solver.iterations = iterations;
  45680. }
  45681. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45682. this.world.gravity.copy(gravity);
  45683. };
  45684. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45685. this._fixedTimeStep = timeStep;
  45686. };
  45687. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45688. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45689. };
  45690. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45691. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45692. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45693. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45694. };
  45695. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45696. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45697. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45698. impostor.physicsBody.applyForce(impulse, worldPoint);
  45699. };
  45700. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45701. //parent-child relationship. Does this impostor has a parent impostor?
  45702. if (impostor.parent) {
  45703. if (impostor.physicsBody) {
  45704. this.removePhysicsBody(impostor);
  45705. //TODO is that needed?
  45706. impostor.forceUpdate();
  45707. }
  45708. return;
  45709. }
  45710. //should a new body be created for this impostor?
  45711. if (impostor.isBodyInitRequired()) {
  45712. var shape = this._createShape(impostor);
  45713. //unregister events, if body is being changed
  45714. var oldBody = impostor.physicsBody;
  45715. if (oldBody) {
  45716. this.removePhysicsBody(impostor);
  45717. }
  45718. //create the body and material
  45719. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45720. var bodyCreationObject = {
  45721. mass: impostor.getParam("mass"),
  45722. material: material
  45723. };
  45724. // A simple extend, in case native options were used.
  45725. var nativeOptions = impostor.getParam("nativeOptions");
  45726. for (var key in nativeOptions) {
  45727. if (nativeOptions.hasOwnProperty(key)) {
  45728. bodyCreationObject[key] = nativeOptions[key];
  45729. }
  45730. }
  45731. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45732. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45733. this.world.addEventListener("preStep", impostor.beforeStep);
  45734. this.world.addEventListener("postStep", impostor.afterStep);
  45735. impostor.physicsBody.addShape(shape);
  45736. this.world.add(impostor.physicsBody);
  45737. //try to keep the body moving in the right direction by taking old properties.
  45738. //Should be tested!
  45739. if (oldBody) {
  45740. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45741. impostor.physicsBody[param].copy(oldBody[param]);
  45742. });
  45743. }
  45744. this._processChildMeshes(impostor);
  45745. }
  45746. //now update the body's transformation
  45747. this._updatePhysicsBodyTransformation(impostor);
  45748. };
  45749. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45750. var _this = this;
  45751. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45752. if (meshChildren.length) {
  45753. var processMesh = function (localPosition, mesh) {
  45754. var childImpostor = mesh.getPhysicsImpostor();
  45755. if (childImpostor) {
  45756. var parent = childImpostor.parent;
  45757. if (parent !== mainImpostor) {
  45758. var localPosition = mesh.position;
  45759. if (childImpostor.physicsBody) {
  45760. _this.removePhysicsBody(childImpostor);
  45761. childImpostor.physicsBody = null;
  45762. }
  45763. childImpostor.parent = mainImpostor;
  45764. childImpostor.resetUpdateFlags();
  45765. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45766. //Add the mass of the children.
  45767. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45768. }
  45769. }
  45770. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45771. };
  45772. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45773. }
  45774. };
  45775. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45776. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45777. this.world.removeEventListener("preStep", impostor.beforeStep);
  45778. this.world.removeEventListener("postStep", impostor.afterStep);
  45779. this.world.remove(impostor.physicsBody);
  45780. };
  45781. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45782. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45783. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45784. if (!mainBody || !connectedBody) {
  45785. return;
  45786. }
  45787. var constraint;
  45788. var jointData = impostorJoint.joint.jointData;
  45789. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45790. var constraintData = {
  45791. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45792. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45793. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45794. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45795. maxForce: jointData.nativeParams.maxForce,
  45796. collideConnected: !!jointData.collision
  45797. };
  45798. switch (impostorJoint.joint.type) {
  45799. case BABYLON.PhysicsJoint.HingeJoint:
  45800. case BABYLON.PhysicsJoint.Hinge2Joint:
  45801. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45802. break;
  45803. case BABYLON.PhysicsJoint.DistanceJoint:
  45804. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45805. break;
  45806. case BABYLON.PhysicsJoint.SpringJoint:
  45807. var springData = jointData;
  45808. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45809. restLength: springData.length,
  45810. stiffness: springData.stiffness,
  45811. damping: springData.damping,
  45812. localAnchorA: constraintData.pivotA,
  45813. localAnchorB: constraintData.pivotB
  45814. });
  45815. break;
  45816. case BABYLON.PhysicsJoint.LockJoint:
  45817. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45818. break;
  45819. case BABYLON.PhysicsJoint.PointToPointJoint:
  45820. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45821. default:
  45822. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45823. break;
  45824. }
  45825. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45826. constraint.collideConnected = !!jointData.collision;
  45827. impostorJoint.joint.physicsJoint = constraint;
  45828. //don't add spring as constraint, as it is not one.
  45829. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45830. this.world.addConstraint(constraint);
  45831. }
  45832. else {
  45833. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45834. constraint.applyForce();
  45835. });
  45836. }
  45837. };
  45838. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45839. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45840. };
  45841. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45842. var index;
  45843. var mat;
  45844. for (index = 0; index < this._physicsMaterials.length; index++) {
  45845. mat = this._physicsMaterials[index];
  45846. if (mat.friction === friction && mat.restitution === restitution) {
  45847. return mat;
  45848. }
  45849. }
  45850. var currentMat = new CANNON.Material(name);
  45851. currentMat.friction = friction;
  45852. currentMat.restitution = restitution;
  45853. this._physicsMaterials.push(currentMat);
  45854. return currentMat;
  45855. };
  45856. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45857. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45858. };
  45859. CannonJSPlugin.prototype._createShape = function (impostor) {
  45860. var object = impostor.object;
  45861. var returnValue;
  45862. var extendSize = impostor.getObjectExtendSize();
  45863. switch (impostor.type) {
  45864. case BABYLON.PhysicsImpostor.SphereImpostor:
  45865. var radiusX = extendSize.x;
  45866. var radiusY = extendSize.y;
  45867. var radiusZ = extendSize.z;
  45868. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45869. break;
  45870. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45871. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45872. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45873. break;
  45874. case BABYLON.PhysicsImpostor.BoxImpostor:
  45875. var box = extendSize.scale(0.5);
  45876. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45877. break;
  45878. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45879. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45880. returnValue = new CANNON.Plane();
  45881. break;
  45882. case BABYLON.PhysicsImpostor.MeshImpostor:
  45883. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45884. var rawFaces = object.getIndices ? object.getIndices() : [];
  45885. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45886. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45887. break;
  45888. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45889. returnValue = this._createHeightmap(object);
  45890. break;
  45891. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45892. returnValue = new CANNON.Particle();
  45893. break;
  45894. }
  45895. return returnValue;
  45896. };
  45897. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45898. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45899. var matrix = [];
  45900. //For now pointDepth will not be used and will be automatically calculated.
  45901. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45902. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45903. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45904. var elementSize = dim * 2 / arraySize;
  45905. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45906. for (var i = 0; i < pos.length; i = i + 3) {
  45907. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45908. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45909. var y = pos[i + 1] + minY;
  45910. if (!matrix[x]) {
  45911. matrix[x] = [];
  45912. }
  45913. if (!matrix[x][z]) {
  45914. matrix[x][z] = y;
  45915. }
  45916. matrix[x][z] = Math.max(y, matrix[x][z]);
  45917. }
  45918. for (var x = 0; x <= arraySize; ++x) {
  45919. if (!matrix[x]) {
  45920. var loc = 1;
  45921. while (!matrix[(x + loc) % arraySize]) {
  45922. loc++;
  45923. }
  45924. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45925. //console.log("missing x", x);
  45926. }
  45927. for (var z = 0; z <= arraySize; ++z) {
  45928. if (!matrix[x][z]) {
  45929. var loc = 1;
  45930. var newValue;
  45931. while (newValue === undefined) {
  45932. newValue = matrix[x][(z + loc++) % arraySize];
  45933. }
  45934. matrix[x][z] = newValue;
  45935. }
  45936. }
  45937. }
  45938. var shape = new CANNON.Heightfield(matrix, {
  45939. elementSize: elementSize
  45940. });
  45941. //For future reference, needed for body transformation
  45942. shape.minY = minY;
  45943. return shape;
  45944. };
  45945. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45946. var object = impostor.object;
  45947. //make sure it is updated...
  45948. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45949. // The delta between the mesh position and the mesh bounding box center
  45950. var center = impostor.getObjectCenter();
  45951. var extendSize = impostor.getObjectExtendSize();
  45952. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45953. this._tmpPosition.copyFrom(center);
  45954. var quaternion = object.rotationQuaternion;
  45955. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45956. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45957. //-90 DEG in X, precalculated
  45958. quaternion = quaternion.multiply(this._minus90X);
  45959. //Invert! (Precalculated, 90 deg in X)
  45960. //No need to clone. this will never change.
  45961. impostor.setDeltaRotation(this._plus90X);
  45962. }
  45963. //If it is a heightfield, if should be centered.
  45964. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45965. var mesh = object;
  45966. //calculate the correct body position:
  45967. var rotationQuaternion = mesh.rotationQuaternion;
  45968. mesh.rotationQuaternion = this._tmpUnityRotation;
  45969. mesh.computeWorldMatrix(true);
  45970. //get original center with no rotation
  45971. var c = center.clone();
  45972. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45973. //rotation is back
  45974. mesh.rotationQuaternion = rotationQuaternion;
  45975. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45976. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45977. mesh.setPivotMatrix(p);
  45978. mesh.computeWorldMatrix(true);
  45979. //calculate the translation
  45980. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45981. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45982. //add it inverted to the delta
  45983. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45984. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45985. mesh.setPivotMatrix(oldPivot);
  45986. mesh.computeWorldMatrix(true);
  45987. }
  45988. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45989. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45990. this._tmpPosition.copyFrom(object.position);
  45991. }
  45992. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45993. //Now update the impostor object
  45994. impostor.physicsBody.position.copy(this._tmpPosition);
  45995. impostor.physicsBody.quaternion.copy(quaternion);
  45996. };
  45997. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45998. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45999. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  46000. };
  46001. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46002. impostor.physicsBody.position.copy(newPosition);
  46003. impostor.physicsBody.quaternion.copy(newRotation);
  46004. };
  46005. CannonJSPlugin.prototype.isSupported = function () {
  46006. return window.CANNON !== undefined;
  46007. };
  46008. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46009. impostor.physicsBody.velocity.copy(velocity);
  46010. };
  46011. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46012. impostor.physicsBody.angularVelocity.copy(velocity);
  46013. };
  46014. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46015. var v = impostor.physicsBody.velocity;
  46016. if (!v)
  46017. return null;
  46018. return new BABYLON.Vector3(v.x, v.y, v.z);
  46019. };
  46020. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46021. var v = impostor.physicsBody.angularVelocity;
  46022. if (!v)
  46023. return null;
  46024. return new BABYLON.Vector3(v.x, v.y, v.z);
  46025. };
  46026. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46027. impostor.physicsBody.mass = mass;
  46028. impostor.physicsBody.updateMassProperties();
  46029. };
  46030. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  46031. impostor.physicsBody.sleep();
  46032. };
  46033. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  46034. impostor.physicsBody.wakeUp();
  46035. };
  46036. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46037. joint.physicsJoint.distance = maxDistance;
  46038. };
  46039. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  46040. if (!motorIndex) {
  46041. joint.physicsJoint.enableMotor();
  46042. }
  46043. };
  46044. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  46045. if (!motorIndex) {
  46046. joint.physicsJoint.disableMotor();
  46047. }
  46048. };
  46049. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46050. if (!motorIndex) {
  46051. joint.physicsJoint.enableMotor();
  46052. joint.physicsJoint.setMotorSpeed(speed);
  46053. if (maxForce) {
  46054. this.setLimit(joint, maxForce);
  46055. }
  46056. }
  46057. };
  46058. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  46059. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  46060. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  46061. };
  46062. CannonJSPlugin.prototype.dispose = function () {
  46063. //nothing to do, actually.
  46064. };
  46065. return CannonJSPlugin;
  46066. }());
  46067. BABYLON.CannonJSPlugin = CannonJSPlugin;
  46068. })(BABYLON || (BABYLON = {}));
  46069. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  46070. var BABYLON;
  46071. (function (BABYLON) {
  46072. var OimoJSPlugin = (function () {
  46073. function OimoJSPlugin(iterations) {
  46074. this.name = "OimoJSPlugin";
  46075. this._tmpImpostorsArray = [];
  46076. this._tmpPositionVector = BABYLON.Vector3.Zero();
  46077. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  46078. this.world.worldscale(1);
  46079. this.world.clear();
  46080. //making sure no stats are calculated
  46081. this.world.isNoStat = true;
  46082. }
  46083. OimoJSPlugin.prototype.setGravity = function (gravity) {
  46084. this.world.gravity.copy(gravity);
  46085. };
  46086. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  46087. this.world.timeStep = timeStep;
  46088. };
  46089. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  46090. var _this = this;
  46091. impostors.forEach(function (impostor) {
  46092. impostor.beforeStep();
  46093. });
  46094. this.world.step();
  46095. impostors.forEach(function (impostor) {
  46096. impostor.afterStep();
  46097. //update the ordered impostors array
  46098. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  46099. });
  46100. //check for collisions
  46101. var contact = this.world.contacts;
  46102. while (contact !== null) {
  46103. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  46104. contact = contact.next;
  46105. continue;
  46106. }
  46107. //is this body colliding with any other? get the impostor
  46108. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  46109. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  46110. if (!mainImpostor || !collidingImpostor) {
  46111. contact = contact.next;
  46112. continue;
  46113. }
  46114. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  46115. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46116. contact = contact.next;
  46117. }
  46118. };
  46119. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46120. var mass = impostor.physicsBody.massInfo.mass;
  46121. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  46122. };
  46123. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46124. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  46125. this.applyImpulse(impostor, force, contactPoint);
  46126. };
  46127. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46128. var _this = this;
  46129. //parent-child relationship. Does this impostor has a parent impostor?
  46130. if (impostor.parent) {
  46131. if (impostor.physicsBody) {
  46132. this.removePhysicsBody(impostor);
  46133. //TODO is that needed?
  46134. impostor.forceUpdate();
  46135. }
  46136. return;
  46137. }
  46138. if (impostor.isBodyInitRequired()) {
  46139. var bodyConfig = {
  46140. name: impostor.uniqueId,
  46141. //Oimo must have mass, also for static objects.
  46142. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  46143. size: [],
  46144. type: [],
  46145. pos: [],
  46146. rot: [],
  46147. move: impostor.getParam("mass") !== 0,
  46148. //Supporting older versions of Oimo
  46149. world: this.world
  46150. };
  46151. var impostors = [impostor];
  46152. var addToArray = function (parent) {
  46153. if (!parent.getChildMeshes)
  46154. return;
  46155. parent.getChildMeshes().forEach(function (m) {
  46156. if (m.physicsImpostor) {
  46157. impostors.push(m.physicsImpostor);
  46158. m.physicsImpostor._init();
  46159. }
  46160. });
  46161. };
  46162. addToArray(impostor.object);
  46163. var checkWithEpsilon_1 = function (value) {
  46164. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46165. };
  46166. impostors.forEach(function (i) {
  46167. //get the correct bounding box
  46168. var oldQuaternion = i.object.rotationQuaternion;
  46169. var rot = new OIMO.Euler().setFromQuaternion({
  46170. x: impostor.object.rotationQuaternion.x,
  46171. y: impostor.object.rotationQuaternion.y,
  46172. z: impostor.object.rotationQuaternion.z,
  46173. s: impostor.object.rotationQuaternion.w
  46174. });
  46175. var extendSize = i.getObjectExtendSize();
  46176. if (i === impostor) {
  46177. var center = impostor.getObjectCenter();
  46178. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46179. //Can also use Array.prototype.push.apply
  46180. bodyConfig.pos.push(center.x);
  46181. bodyConfig.pos.push(center.y);
  46182. bodyConfig.pos.push(center.z);
  46183. //tmp solution
  46184. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46185. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46186. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46187. }
  46188. else {
  46189. bodyConfig.pos.push(i.object.position.x);
  46190. bodyConfig.pos.push(i.object.position.y);
  46191. bodyConfig.pos.push(i.object.position.z);
  46192. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46193. bodyConfig.rot.push(0);
  46194. bodyConfig.rot.push(0);
  46195. bodyConfig.rot.push(0);
  46196. }
  46197. // register mesh
  46198. switch (i.type) {
  46199. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46200. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46201. case BABYLON.PhysicsImpostor.SphereImpostor:
  46202. var radiusX = extendSize.x;
  46203. var radiusY = extendSize.y;
  46204. var radiusZ = extendSize.z;
  46205. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  46206. bodyConfig.type.push('sphere');
  46207. //due to the way oimo works with compounds, add 3 times
  46208. bodyConfig.size.push(size);
  46209. bodyConfig.size.push(size);
  46210. bodyConfig.size.push(size);
  46211. break;
  46212. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46213. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  46214. var sizeY = checkWithEpsilon_1(extendSize.y);
  46215. bodyConfig.type.push('cylinder');
  46216. bodyConfig.size.push(sizeX);
  46217. bodyConfig.size.push(sizeY);
  46218. //due to the way oimo works with compounds, add one more value.
  46219. bodyConfig.size.push(sizeY);
  46220. break;
  46221. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46222. case BABYLON.PhysicsImpostor.BoxImpostor:
  46223. default:
  46224. var sizeX = checkWithEpsilon_1(extendSize.x);
  46225. var sizeY = checkWithEpsilon_1(extendSize.y);
  46226. var sizeZ = checkWithEpsilon_1(extendSize.z);
  46227. bodyConfig.type.push('box');
  46228. bodyConfig.size.push(sizeX);
  46229. bodyConfig.size.push(sizeY);
  46230. bodyConfig.size.push(sizeZ);
  46231. break;
  46232. }
  46233. //actually not needed, but hey...
  46234. i.object.rotationQuaternion = oldQuaternion;
  46235. });
  46236. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46237. }
  46238. else {
  46239. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46240. }
  46241. impostor.setDeltaPosition(this._tmpPositionVector);
  46242. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46243. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46244. };
  46245. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46246. //impostor.physicsBody.dispose();
  46247. //Same as : (older oimo versions)
  46248. this.world.removeRigidBody(impostor.physicsBody);
  46249. };
  46250. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46251. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46252. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46253. if (!mainBody || !connectedBody) {
  46254. return;
  46255. }
  46256. var jointData = impostorJoint.joint.jointData;
  46257. var options = jointData.nativeParams || {};
  46258. var type;
  46259. var nativeJointData = {
  46260. body1: mainBody,
  46261. body2: connectedBody,
  46262. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46263. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46264. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46265. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46266. min: options.min,
  46267. max: options.max,
  46268. collision: options.collision || jointData.collision,
  46269. spring: options.spring,
  46270. //supporting older version of Oimo
  46271. world: this.world
  46272. };
  46273. switch (impostorJoint.joint.type) {
  46274. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46275. type = "jointBall";
  46276. break;
  46277. case BABYLON.PhysicsJoint.SpringJoint:
  46278. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46279. var springData = jointData;
  46280. nativeJointData.min = springData.length || nativeJointData.min;
  46281. //Max should also be set, just make sure it is at least min
  46282. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46283. case BABYLON.PhysicsJoint.DistanceJoint:
  46284. type = "jointDistance";
  46285. nativeJointData.max = jointData.maxDistance;
  46286. break;
  46287. case BABYLON.PhysicsJoint.PrismaticJoint:
  46288. type = "jointPrisme";
  46289. break;
  46290. case BABYLON.PhysicsJoint.SliderJoint:
  46291. type = "jointSlide";
  46292. break;
  46293. case BABYLON.PhysicsJoint.WheelJoint:
  46294. type = "jointWheel";
  46295. break;
  46296. case BABYLON.PhysicsJoint.HingeJoint:
  46297. default:
  46298. type = "jointHinge";
  46299. break;
  46300. }
  46301. nativeJointData.type = type;
  46302. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46303. };
  46304. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46305. //Bug in Oimo prevents us from disposing a joint in the playground
  46306. //joint.joint.physicsJoint.dispose();
  46307. //So we will bruteforce it!
  46308. try {
  46309. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46310. }
  46311. catch (e) {
  46312. BABYLON.Tools.Warn(e);
  46313. }
  46314. };
  46315. OimoJSPlugin.prototype.isSupported = function () {
  46316. return OIMO !== undefined;
  46317. };
  46318. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46319. if (!impostor.physicsBody.sleeping) {
  46320. //TODO check that
  46321. if (impostor.physicsBody.shapes.next) {
  46322. var parentShape = this._getLastShape(impostor.physicsBody);
  46323. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46324. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46325. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46326. }
  46327. else {
  46328. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46329. }
  46330. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46331. impostor.object.rotationQuaternion.normalize();
  46332. }
  46333. };
  46334. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46335. var body = impostor.physicsBody;
  46336. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46337. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46338. body.syncShapes();
  46339. body.awake();
  46340. };
  46341. OimoJSPlugin.prototype._getLastShape = function (body) {
  46342. var lastShape = body.shapes;
  46343. while (lastShape.next) {
  46344. lastShape = lastShape.next;
  46345. }
  46346. return lastShape;
  46347. };
  46348. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46349. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46350. };
  46351. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46352. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46353. };
  46354. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46355. var v = impostor.physicsBody.linearVelocity;
  46356. if (!v)
  46357. return null;
  46358. return new BABYLON.Vector3(v.x, v.y, v.z);
  46359. };
  46360. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46361. var v = impostor.physicsBody.angularVelocity;
  46362. if (!v)
  46363. return null;
  46364. return new BABYLON.Vector3(v.x, v.y, v.z);
  46365. };
  46366. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46367. var staticBody = mass === 0;
  46368. //this will actually set the body's density and not its mass.
  46369. //But this is how oimo treats the mass variable.
  46370. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46371. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46372. };
  46373. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46374. impostor.physicsBody.sleep();
  46375. };
  46376. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46377. impostor.physicsBody.awake();
  46378. };
  46379. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46380. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  46381. if (minDistance !== void 0) {
  46382. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  46383. }
  46384. };
  46385. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46386. //TODO separate rotational and transational motors.
  46387. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46388. if (motor) {
  46389. motor.setMotor(speed, maxForce);
  46390. }
  46391. };
  46392. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46393. //TODO separate rotational and transational motors.
  46394. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46395. if (motor) {
  46396. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46397. }
  46398. };
  46399. OimoJSPlugin.prototype.dispose = function () {
  46400. this.world.clear();
  46401. };
  46402. return OimoJSPlugin;
  46403. }());
  46404. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46405. })(BABYLON || (BABYLON = {}));
  46406. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  46407. var BABYLON;
  46408. (function (BABYLON) {
  46409. var DisplayPassPostProcess = (function (_super) {
  46410. __extends(DisplayPassPostProcess, _super);
  46411. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46412. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  46413. }
  46414. return DisplayPassPostProcess;
  46415. }(BABYLON.PostProcess));
  46416. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46417. })(BABYLON || (BABYLON = {}));
  46418. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  46419. var BABYLON;
  46420. (function (BABYLON) {
  46421. var SimplificationSettings = (function () {
  46422. function SimplificationSettings(quality, distance, optimizeMesh) {
  46423. this.quality = quality;
  46424. this.distance = distance;
  46425. this.optimizeMesh = optimizeMesh;
  46426. }
  46427. return SimplificationSettings;
  46428. }());
  46429. BABYLON.SimplificationSettings = SimplificationSettings;
  46430. var SimplificationQueue = (function () {
  46431. function SimplificationQueue() {
  46432. this.running = false;
  46433. this._simplificationArray = [];
  46434. }
  46435. SimplificationQueue.prototype.addTask = function (task) {
  46436. this._simplificationArray.push(task);
  46437. };
  46438. SimplificationQueue.prototype.executeNext = function () {
  46439. var task = this._simplificationArray.pop();
  46440. if (task) {
  46441. this.running = true;
  46442. this.runSimplification(task);
  46443. }
  46444. else {
  46445. this.running = false;
  46446. }
  46447. };
  46448. SimplificationQueue.prototype.runSimplification = function (task) {
  46449. var _this = this;
  46450. if (task.parallelProcessing) {
  46451. //parallel simplifier
  46452. task.settings.forEach(function (setting) {
  46453. var simplifier = _this.getSimplifier(task);
  46454. simplifier.simplify(setting, function (newMesh) {
  46455. task.mesh.addLODLevel(setting.distance, newMesh);
  46456. newMesh.isVisible = true;
  46457. //check if it is the last
  46458. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46459. //all done, run the success callback.
  46460. task.successCallback();
  46461. }
  46462. _this.executeNext();
  46463. });
  46464. });
  46465. }
  46466. else {
  46467. //single simplifier.
  46468. var simplifier = this.getSimplifier(task);
  46469. var runDecimation = function (setting, callback) {
  46470. simplifier.simplify(setting, function (newMesh) {
  46471. task.mesh.addLODLevel(setting.distance, newMesh);
  46472. newMesh.isVisible = true;
  46473. //run the next quality level
  46474. callback();
  46475. });
  46476. };
  46477. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46478. runDecimation(task.settings[loop.index], function () {
  46479. loop.executeNext();
  46480. });
  46481. }, function () {
  46482. //execution ended, run the success callback.
  46483. if (task.successCallback) {
  46484. task.successCallback();
  46485. }
  46486. _this.executeNext();
  46487. });
  46488. }
  46489. };
  46490. SimplificationQueue.prototype.getSimplifier = function (task) {
  46491. switch (task.simplificationType) {
  46492. case SimplificationType.QUADRATIC:
  46493. default:
  46494. return new QuadraticErrorSimplification(task.mesh);
  46495. }
  46496. };
  46497. return SimplificationQueue;
  46498. }());
  46499. BABYLON.SimplificationQueue = SimplificationQueue;
  46500. /**
  46501. * The implemented types of simplification.
  46502. * At the moment only Quadratic Error Decimation is implemented.
  46503. */
  46504. var SimplificationType;
  46505. (function (SimplificationType) {
  46506. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46507. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46508. var DecimationTriangle = (function () {
  46509. function DecimationTriangle(vertices) {
  46510. this.vertices = vertices;
  46511. this.error = new Array(4);
  46512. this.deleted = false;
  46513. this.isDirty = false;
  46514. this.deletePending = false;
  46515. this.borderFactor = 0;
  46516. }
  46517. return DecimationTriangle;
  46518. }());
  46519. BABYLON.DecimationTriangle = DecimationTriangle;
  46520. var DecimationVertex = (function () {
  46521. function DecimationVertex(position, id) {
  46522. this.position = position;
  46523. this.id = id;
  46524. this.isBorder = true;
  46525. this.q = new QuadraticMatrix();
  46526. this.triangleCount = 0;
  46527. this.triangleStart = 0;
  46528. this.originalOffsets = [];
  46529. }
  46530. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46531. this.position.copyFrom(newPosition);
  46532. };
  46533. return DecimationVertex;
  46534. }());
  46535. BABYLON.DecimationVertex = DecimationVertex;
  46536. var QuadraticMatrix = (function () {
  46537. function QuadraticMatrix(data) {
  46538. this.data = new Array(10);
  46539. for (var i = 0; i < 10; ++i) {
  46540. if (data && data[i]) {
  46541. this.data[i] = data[i];
  46542. }
  46543. else {
  46544. this.data[i] = 0;
  46545. }
  46546. }
  46547. }
  46548. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46549. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46550. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46551. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46552. return det;
  46553. };
  46554. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46555. for (var i = 0; i < 10; ++i) {
  46556. this.data[i] += matrix.data[i];
  46557. }
  46558. };
  46559. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46560. for (var i = 0; i < 10; ++i) {
  46561. this.data[i] += data[i];
  46562. }
  46563. };
  46564. QuadraticMatrix.prototype.add = function (matrix) {
  46565. var m = new QuadraticMatrix();
  46566. for (var i = 0; i < 10; ++i) {
  46567. m.data[i] = this.data[i] + matrix.data[i];
  46568. }
  46569. return m;
  46570. };
  46571. QuadraticMatrix.FromData = function (a, b, c, d) {
  46572. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46573. };
  46574. //returning an array to avoid garbage collection
  46575. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46576. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46577. };
  46578. return QuadraticMatrix;
  46579. }());
  46580. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46581. var Reference = (function () {
  46582. function Reference(vertexId, triangleId) {
  46583. this.vertexId = vertexId;
  46584. this.triangleId = triangleId;
  46585. }
  46586. return Reference;
  46587. }());
  46588. BABYLON.Reference = Reference;
  46589. /**
  46590. * An implementation of the Quadratic Error simplification algorithm.
  46591. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46592. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46593. * @author RaananW
  46594. */
  46595. var QuadraticErrorSimplification = (function () {
  46596. function QuadraticErrorSimplification(_mesh) {
  46597. this._mesh = _mesh;
  46598. this.initialized = false;
  46599. this.syncIterations = 5000;
  46600. this.aggressiveness = 7;
  46601. this.decimationIterations = 100;
  46602. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46603. }
  46604. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46605. var _this = this;
  46606. this.initDecimatedMesh();
  46607. //iterating through the submeshes array, one after the other.
  46608. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46609. _this.initWithMesh(loop.index, function () {
  46610. _this.runDecimation(settings, loop.index, function () {
  46611. loop.executeNext();
  46612. });
  46613. }, settings.optimizeMesh);
  46614. }, function () {
  46615. setTimeout(function () {
  46616. successCallback(_this._reconstructedMesh);
  46617. }, 0);
  46618. });
  46619. };
  46620. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46621. var _this = this;
  46622. var gCount = 0;
  46623. triangle.vertices.forEach(function (vertex) {
  46624. var count = 0;
  46625. var vPos = vertex.position;
  46626. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46627. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46628. ++count;
  46629. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46630. ++count;
  46631. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46632. ++count;
  46633. if (count > 1) {
  46634. ++gCount;
  46635. }
  46636. ;
  46637. });
  46638. if (gCount > 1) {
  46639. console.log(triangle, gCount);
  46640. }
  46641. return gCount > 1;
  46642. };
  46643. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46644. var _this = this;
  46645. var targetCount = ~~(this.triangles.length * settings.quality);
  46646. var deletedTriangles = 0;
  46647. var triangleCount = this.triangles.length;
  46648. var iterationFunction = function (iteration, callback) {
  46649. setTimeout(function () {
  46650. if (iteration % 5 === 0) {
  46651. _this.updateMesh(iteration === 0);
  46652. }
  46653. for (var i = 0; i < _this.triangles.length; ++i) {
  46654. _this.triangles[i].isDirty = false;
  46655. }
  46656. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46657. var trianglesIterator = function (i) {
  46658. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46659. var t = _this.triangles[tIdx];
  46660. if (!t)
  46661. return;
  46662. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46663. return;
  46664. }
  46665. for (var j = 0; j < 3; ++j) {
  46666. if (t.error[j] < threshold) {
  46667. var deleted0 = [];
  46668. var deleted1 = [];
  46669. var v0 = t.vertices[j];
  46670. var v1 = t.vertices[(j + 1) % 3];
  46671. if (v0.isBorder || v1.isBorder)
  46672. continue;
  46673. var p = BABYLON.Vector3.Zero();
  46674. var n = BABYLON.Vector3.Zero();
  46675. var uv = BABYLON.Vector2.Zero();
  46676. var color = new BABYLON.Color4(0, 0, 0, 1);
  46677. _this.calculateError(v0, v1, p, n, uv, color);
  46678. var delTr = [];
  46679. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46680. continue;
  46681. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46682. continue;
  46683. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46684. continue;
  46685. var uniqueArray = [];
  46686. delTr.forEach(function (deletedT) {
  46687. if (uniqueArray.indexOf(deletedT) === -1) {
  46688. deletedT.deletePending = true;
  46689. uniqueArray.push(deletedT);
  46690. }
  46691. });
  46692. if (uniqueArray.length % 2 !== 0) {
  46693. continue;
  46694. }
  46695. v0.q = v1.q.add(v0.q);
  46696. v0.updatePosition(p);
  46697. var tStart = _this.references.length;
  46698. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46699. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46700. var tCount = _this.references.length - tStart;
  46701. if (tCount <= v0.triangleCount) {
  46702. if (tCount) {
  46703. for (var c = 0; c < tCount; c++) {
  46704. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46705. }
  46706. }
  46707. }
  46708. else {
  46709. v0.triangleStart = tStart;
  46710. }
  46711. v0.triangleCount = tCount;
  46712. break;
  46713. }
  46714. }
  46715. };
  46716. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46717. }, 0);
  46718. };
  46719. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46720. if (triangleCount - deletedTriangles <= targetCount)
  46721. loop.breakLoop();
  46722. else {
  46723. iterationFunction(loop.index, function () {
  46724. loop.executeNext();
  46725. });
  46726. }
  46727. }, function () {
  46728. setTimeout(function () {
  46729. //reconstruct this part of the mesh
  46730. _this.reconstructMesh(submeshIndex);
  46731. successCallback();
  46732. }, 0);
  46733. });
  46734. };
  46735. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46736. var _this = this;
  46737. this.vertices = [];
  46738. this.triangles = [];
  46739. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46740. var indices = this._mesh.getIndices();
  46741. var submesh = this._mesh.subMeshes[submeshIndex];
  46742. var findInVertices = function (positionToSearch) {
  46743. if (optimizeMesh) {
  46744. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46745. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46746. return _this.vertices[ii];
  46747. }
  46748. }
  46749. }
  46750. return null;
  46751. };
  46752. var vertexReferences = [];
  46753. var vertexInit = function (i) {
  46754. var offset = i + submesh.verticesStart;
  46755. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46756. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46757. vertex.originalOffsets.push(offset);
  46758. if (vertex.id === _this.vertices.length) {
  46759. _this.vertices.push(vertex);
  46760. }
  46761. vertexReferences.push(vertex.id);
  46762. };
  46763. //var totalVertices = mesh.getTotalVertices();
  46764. var totalVertices = submesh.verticesCount;
  46765. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46766. var indicesInit = function (i) {
  46767. var offset = (submesh.indexStart / 3) + i;
  46768. var pos = (offset * 3);
  46769. var i0 = indices[pos + 0];
  46770. var i1 = indices[pos + 1];
  46771. var i2 = indices[pos + 2];
  46772. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46773. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46774. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46775. var triangle = new DecimationTriangle([v0, v1, v2]);
  46776. triangle.originalOffset = pos;
  46777. _this.triangles.push(triangle);
  46778. };
  46779. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46780. _this.init(callback);
  46781. });
  46782. });
  46783. };
  46784. QuadraticErrorSimplification.prototype.init = function (callback) {
  46785. var _this = this;
  46786. var triangleInit1 = function (i) {
  46787. var t = _this.triangles[i];
  46788. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46789. for (var j = 0; j < 3; j++) {
  46790. 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))));
  46791. }
  46792. };
  46793. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46794. var triangleInit2 = function (i) {
  46795. var t = _this.triangles[i];
  46796. for (var j = 0; j < 3; ++j) {
  46797. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46798. }
  46799. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46800. };
  46801. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46802. _this.initialized = true;
  46803. callback();
  46804. });
  46805. });
  46806. };
  46807. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46808. var newTriangles = [];
  46809. var i;
  46810. for (i = 0; i < this.vertices.length; ++i) {
  46811. this.vertices[i].triangleCount = 0;
  46812. }
  46813. var t;
  46814. var j;
  46815. for (i = 0; i < this.triangles.length; ++i) {
  46816. if (!this.triangles[i].deleted) {
  46817. t = this.triangles[i];
  46818. for (j = 0; j < 3; ++j) {
  46819. t.vertices[j].triangleCount = 1;
  46820. }
  46821. newTriangles.push(t);
  46822. }
  46823. }
  46824. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46825. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46826. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46827. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46828. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46829. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46830. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46831. var vertexCount = 0;
  46832. for (i = 0; i < this.vertices.length; ++i) {
  46833. var vertex = this.vertices[i];
  46834. vertex.id = vertexCount;
  46835. if (vertex.triangleCount) {
  46836. vertex.originalOffsets.forEach(function (originalOffset) {
  46837. newPositionData.push(vertex.position.x);
  46838. newPositionData.push(vertex.position.y);
  46839. newPositionData.push(vertex.position.z);
  46840. newNormalData.push(normalData[originalOffset * 3]);
  46841. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46842. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46843. if (uvs && uvs.length) {
  46844. newUVsData.push(uvs[(originalOffset * 2)]);
  46845. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46846. }
  46847. else if (colorsData && colorsData.length) {
  46848. newColorsData.push(colorsData[(originalOffset * 4)]);
  46849. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46850. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46851. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46852. }
  46853. ++vertexCount;
  46854. });
  46855. }
  46856. }
  46857. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46858. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46859. var submeshesArray = this._reconstructedMesh.subMeshes;
  46860. this._reconstructedMesh.subMeshes = [];
  46861. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46862. var originalIndices = this._mesh.getIndices();
  46863. for (i = 0; i < newTriangles.length; ++i) {
  46864. t = newTriangles[i]; //now get the new referencing point for each vertex
  46865. [0, 1, 2].forEach(function (idx) {
  46866. var id = originalIndices[t.originalOffset + idx];
  46867. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46868. if (offset < 0)
  46869. offset = 0;
  46870. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46871. });
  46872. }
  46873. //overwriting the old vertex buffers and indices.
  46874. this._reconstructedMesh.setIndices(newIndicesArray);
  46875. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46876. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46877. if (newUVsData.length > 0)
  46878. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46879. if (newColorsData.length > 0)
  46880. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46881. //create submesh
  46882. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46883. if (submeshIndex > 0) {
  46884. this._reconstructedMesh.subMeshes = [];
  46885. submeshesArray.forEach(function (submesh) {
  46886. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46887. });
  46888. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46889. }
  46890. };
  46891. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46892. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46893. this._reconstructedMesh.material = this._mesh.material;
  46894. this._reconstructedMesh.parent = this._mesh.parent;
  46895. this._reconstructedMesh.isVisible = false;
  46896. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46897. };
  46898. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46899. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46900. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46901. if (t.deleted)
  46902. continue;
  46903. var s = this.references[vertex1.triangleStart + i].vertexId;
  46904. var v1 = t.vertices[(s + 1) % 3];
  46905. var v2 = t.vertices[(s + 2) % 3];
  46906. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46907. deletedArray[i] = true;
  46908. delTr.push(t);
  46909. continue;
  46910. }
  46911. var d1 = v1.position.subtract(point);
  46912. d1 = d1.normalize();
  46913. var d2 = v2.position.subtract(point);
  46914. d2 = d2.normalize();
  46915. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46916. return true;
  46917. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46918. deletedArray[i] = false;
  46919. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46920. return true;
  46921. }
  46922. return false;
  46923. };
  46924. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46925. var newDeleted = deletedTriangles;
  46926. for (var i = 0; i < vertex.triangleCount; ++i) {
  46927. var ref = this.references[vertex.triangleStart + i];
  46928. var t = this.triangles[ref.triangleId];
  46929. if (t.deleted)
  46930. continue;
  46931. if (deletedArray[i] && t.deletePending) {
  46932. t.deleted = true;
  46933. newDeleted++;
  46934. continue;
  46935. }
  46936. t.vertices[ref.vertexId] = origVertex;
  46937. t.isDirty = true;
  46938. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46939. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46940. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46941. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46942. this.references.push(ref);
  46943. }
  46944. return newDeleted;
  46945. };
  46946. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46947. for (var i = 0; i < this.vertices.length; ++i) {
  46948. var vCount = [];
  46949. var vId = [];
  46950. var v = this.vertices[i];
  46951. var j;
  46952. for (j = 0; j < v.triangleCount; ++j) {
  46953. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46954. for (var ii = 0; ii < 3; ii++) {
  46955. var ofs = 0;
  46956. var vv = triangle.vertices[ii];
  46957. while (ofs < vCount.length) {
  46958. if (vId[ofs] === vv.id)
  46959. break;
  46960. ++ofs;
  46961. }
  46962. if (ofs === vCount.length) {
  46963. vCount.push(1);
  46964. vId.push(vv.id);
  46965. }
  46966. else {
  46967. vCount[ofs]++;
  46968. }
  46969. }
  46970. }
  46971. for (j = 0; j < vCount.length; ++j) {
  46972. if (vCount[j] === 1) {
  46973. this.vertices[vId[j]].isBorder = true;
  46974. }
  46975. else {
  46976. this.vertices[vId[j]].isBorder = false;
  46977. }
  46978. }
  46979. }
  46980. };
  46981. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46982. if (identifyBorders === void 0) { identifyBorders = false; }
  46983. var i;
  46984. if (!identifyBorders) {
  46985. var newTrianglesVector = [];
  46986. for (i = 0; i < this.triangles.length; ++i) {
  46987. if (!this.triangles[i].deleted) {
  46988. newTrianglesVector.push(this.triangles[i]);
  46989. }
  46990. }
  46991. this.triangles = newTrianglesVector;
  46992. }
  46993. for (i = 0; i < this.vertices.length; ++i) {
  46994. this.vertices[i].triangleCount = 0;
  46995. this.vertices[i].triangleStart = 0;
  46996. }
  46997. var t;
  46998. var j;
  46999. var v;
  47000. for (i = 0; i < this.triangles.length; ++i) {
  47001. t = this.triangles[i];
  47002. for (j = 0; j < 3; ++j) {
  47003. v = t.vertices[j];
  47004. v.triangleCount++;
  47005. }
  47006. }
  47007. var tStart = 0;
  47008. for (i = 0; i < this.vertices.length; ++i) {
  47009. this.vertices[i].triangleStart = tStart;
  47010. tStart += this.vertices[i].triangleCount;
  47011. this.vertices[i].triangleCount = 0;
  47012. }
  47013. var newReferences = new Array(this.triangles.length * 3);
  47014. for (i = 0; i < this.triangles.length; ++i) {
  47015. t = this.triangles[i];
  47016. for (j = 0; j < 3; ++j) {
  47017. v = t.vertices[j];
  47018. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  47019. v.triangleCount++;
  47020. }
  47021. }
  47022. this.references = newReferences;
  47023. if (identifyBorders) {
  47024. this.identifyBorder();
  47025. }
  47026. };
  47027. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  47028. var x = point.x;
  47029. var y = point.y;
  47030. var z = point.z;
  47031. 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
  47032. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  47033. };
  47034. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  47035. var q = vertex1.q.add(vertex2.q);
  47036. var border = vertex1.isBorder && vertex2.isBorder;
  47037. var error = 0;
  47038. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  47039. if (qDet !== 0 && !border) {
  47040. if (!pointResult) {
  47041. pointResult = BABYLON.Vector3.Zero();
  47042. }
  47043. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  47044. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  47045. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  47046. error = this.vertexError(q, pointResult);
  47047. }
  47048. else {
  47049. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  47050. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  47051. var error1 = this.vertexError(q, vertex1.position);
  47052. var error2 = this.vertexError(q, vertex2.position);
  47053. var error3 = this.vertexError(q, p3);
  47054. error = Math.min(error1, error2, error3);
  47055. if (error === error1) {
  47056. if (pointResult) {
  47057. pointResult.copyFrom(vertex1.position);
  47058. }
  47059. }
  47060. else if (error === error2) {
  47061. if (pointResult) {
  47062. pointResult.copyFrom(vertex2.position);
  47063. }
  47064. }
  47065. else {
  47066. if (pointResult) {
  47067. pointResult.copyFrom(p3);
  47068. }
  47069. }
  47070. }
  47071. return error;
  47072. };
  47073. return QuadraticErrorSimplification;
  47074. }());
  47075. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  47076. })(BABYLON || (BABYLON = {}));
  47077. //# sourceMappingURL=babylon.meshSimplification.js.map
  47078. var BABYLON;
  47079. (function (BABYLON) {
  47080. var serializedGeometries = [];
  47081. var serializeGeometry = function (geometry, serializationGeometries) {
  47082. if (serializedGeometries[geometry.id]) {
  47083. return;
  47084. }
  47085. if (geometry.doNotSerialize) {
  47086. return;
  47087. }
  47088. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  47089. serializationGeometries.boxes.push(geometry.serialize());
  47090. }
  47091. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  47092. serializationGeometries.spheres.push(geometry.serialize());
  47093. }
  47094. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  47095. serializationGeometries.cylinders.push(geometry.serialize());
  47096. }
  47097. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  47098. serializationGeometries.toruses.push(geometry.serialize());
  47099. }
  47100. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  47101. serializationGeometries.grounds.push(geometry.serialize());
  47102. }
  47103. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  47104. serializationGeometries.planes.push(geometry.serialize());
  47105. }
  47106. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  47107. serializationGeometries.torusKnots.push(geometry.serialize());
  47108. }
  47109. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  47110. throw new Error("Unknown primitive type");
  47111. }
  47112. else {
  47113. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  47114. }
  47115. serializedGeometries[geometry.id] = true;
  47116. };
  47117. var serializeMesh = function (mesh, serializationScene) {
  47118. var serializationObject = {};
  47119. // Geometry
  47120. var geometry = mesh._geometry;
  47121. if (geometry) {
  47122. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  47123. // 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
  47124. serializeGeometry(geometry, serializationScene.geometries);
  47125. }
  47126. }
  47127. // Custom
  47128. if (mesh.serialize) {
  47129. mesh.serialize(serializationObject);
  47130. }
  47131. return serializationObject;
  47132. };
  47133. var finalizeSingleMesh = function (mesh, serializationObject) {
  47134. //only works if the mesh is already loaded
  47135. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47136. //serialize material
  47137. if (mesh.material) {
  47138. if (mesh.material instanceof BABYLON.StandardMaterial) {
  47139. serializationObject.materials = serializationObject.materials || [];
  47140. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47141. serializationObject.materials.push(mesh.material.serialize());
  47142. }
  47143. }
  47144. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  47145. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  47146. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47147. serializationObject.multiMaterials.push(mesh.material.serialize());
  47148. }
  47149. }
  47150. }
  47151. //serialize geometry
  47152. var geometry = mesh._geometry;
  47153. if (geometry) {
  47154. if (!serializationObject.geometries) {
  47155. serializationObject.geometries = {};
  47156. serializationObject.geometries.boxes = [];
  47157. serializationObject.geometries.spheres = [];
  47158. serializationObject.geometries.cylinders = [];
  47159. serializationObject.geometries.toruses = [];
  47160. serializationObject.geometries.grounds = [];
  47161. serializationObject.geometries.planes = [];
  47162. serializationObject.geometries.torusKnots = [];
  47163. serializationObject.geometries.vertexData = [];
  47164. }
  47165. serializeGeometry(geometry, serializationObject.geometries);
  47166. }
  47167. // Skeletons
  47168. if (mesh.skeleton) {
  47169. serializationObject.skeletons = serializationObject.skeletons || [];
  47170. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47171. }
  47172. //serialize the actual mesh
  47173. serializationObject.meshes = serializationObject.meshes || [];
  47174. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47175. }
  47176. };
  47177. var SceneSerializer = (function () {
  47178. function SceneSerializer() {
  47179. }
  47180. SceneSerializer.ClearCache = function () {
  47181. serializedGeometries = [];
  47182. };
  47183. SceneSerializer.Serialize = function (scene) {
  47184. var serializationObject = {};
  47185. SceneSerializer.ClearCache();
  47186. // Scene
  47187. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47188. serializationObject.autoClear = scene.autoClear;
  47189. serializationObject.clearColor = scene.clearColor.asArray();
  47190. serializationObject.ambientColor = scene.ambientColor.asArray();
  47191. serializationObject.gravity = scene.gravity.asArray();
  47192. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47193. serializationObject.workerCollisions = scene.workerCollisions;
  47194. // Fog
  47195. if (scene.fogMode && scene.fogMode !== 0) {
  47196. serializationObject.fogMode = scene.fogMode;
  47197. serializationObject.fogColor = scene.fogColor.asArray();
  47198. serializationObject.fogStart = scene.fogStart;
  47199. serializationObject.fogEnd = scene.fogEnd;
  47200. serializationObject.fogDensity = scene.fogDensity;
  47201. }
  47202. //Physics
  47203. if (scene.isPhysicsEnabled()) {
  47204. serializationObject.physicsEnabled = true;
  47205. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47206. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47207. }
  47208. // Metadata
  47209. if (scene.metadata) {
  47210. serializationObject.metadata = scene.metadata;
  47211. }
  47212. // Lights
  47213. serializationObject.lights = [];
  47214. var index;
  47215. var light;
  47216. for (index = 0; index < scene.lights.length; index++) {
  47217. light = scene.lights[index];
  47218. if (!light.doNotSerialize) {
  47219. serializationObject.lights.push(light.serialize());
  47220. }
  47221. }
  47222. // Cameras
  47223. serializationObject.cameras = [];
  47224. for (index = 0; index < scene.cameras.length; index++) {
  47225. var camera = scene.cameras[index];
  47226. if (!camera.doNotSerialize) {
  47227. serializationObject.cameras.push(camera.serialize());
  47228. }
  47229. }
  47230. if (scene.activeCamera) {
  47231. serializationObject.activeCameraID = scene.activeCamera.id;
  47232. }
  47233. // Animations
  47234. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47235. // Materials
  47236. serializationObject.materials = [];
  47237. serializationObject.multiMaterials = [];
  47238. var material;
  47239. for (index = 0; index < scene.materials.length; index++) {
  47240. material = scene.materials[index];
  47241. if (!material.doNotSerialize) {
  47242. serializationObject.materials.push(material.serialize());
  47243. }
  47244. }
  47245. // MultiMaterials
  47246. serializationObject.multiMaterials = [];
  47247. for (index = 0; index < scene.multiMaterials.length; index++) {
  47248. var multiMaterial = scene.multiMaterials[index];
  47249. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47250. }
  47251. // Skeletons
  47252. serializationObject.skeletons = [];
  47253. for (index = 0; index < scene.skeletons.length; index++) {
  47254. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47255. }
  47256. // Geometries
  47257. serializationObject.geometries = {};
  47258. serializationObject.geometries.boxes = [];
  47259. serializationObject.geometries.spheres = [];
  47260. serializationObject.geometries.cylinders = [];
  47261. serializationObject.geometries.toruses = [];
  47262. serializationObject.geometries.grounds = [];
  47263. serializationObject.geometries.planes = [];
  47264. serializationObject.geometries.torusKnots = [];
  47265. serializationObject.geometries.vertexData = [];
  47266. serializedGeometries = [];
  47267. var geometries = scene.getGeometries();
  47268. for (index = 0; index < geometries.length; index++) {
  47269. var geometry = geometries[index];
  47270. if (geometry.isReady()) {
  47271. serializeGeometry(geometry, serializationObject.geometries);
  47272. }
  47273. }
  47274. // Meshes
  47275. serializationObject.meshes = [];
  47276. for (index = 0; index < scene.meshes.length; index++) {
  47277. var abstractMesh = scene.meshes[index];
  47278. if (abstractMesh instanceof BABYLON.Mesh) {
  47279. var mesh = abstractMesh;
  47280. if (!mesh.doNotSerialize) {
  47281. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47282. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47283. }
  47284. }
  47285. }
  47286. }
  47287. // Particles Systems
  47288. serializationObject.particleSystems = [];
  47289. for (index = 0; index < scene.particleSystems.length; index++) {
  47290. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47291. }
  47292. // Lens flares
  47293. serializationObject.lensFlareSystems = [];
  47294. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47295. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47296. }
  47297. // Shadows
  47298. serializationObject.shadowGenerators = [];
  47299. for (index = 0; index < scene.lights.length; index++) {
  47300. light = scene.lights[index];
  47301. var shadowGenerator = light.getShadowGenerator();
  47302. // Only support serialization for official generator so far.
  47303. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  47304. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  47305. }
  47306. }
  47307. // Action Manager
  47308. if (scene.actionManager) {
  47309. serializationObject.actions = scene.actionManager.serialize("scene");
  47310. }
  47311. // Audio
  47312. serializationObject.sounds = [];
  47313. for (index = 0; index < scene.soundTracks.length; index++) {
  47314. var soundtrack = scene.soundTracks[index];
  47315. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  47316. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  47317. }
  47318. }
  47319. return serializationObject;
  47320. };
  47321. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47322. if (withParents === void 0) { withParents = false; }
  47323. if (withChildren === void 0) { withChildren = false; }
  47324. var serializationObject = {};
  47325. SceneSerializer.ClearCache();
  47326. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47327. if (withParents || withChildren) {
  47328. //deliberate for loop! not for each, appended should be processed as well.
  47329. for (var i = 0; i < toSerialize.length; ++i) {
  47330. if (withChildren) {
  47331. toSerialize[i].getDescendants().forEach(function (node) {
  47332. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47333. toSerialize.push(node);
  47334. }
  47335. });
  47336. }
  47337. //make sure the array doesn't contain the object already
  47338. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47339. toSerialize.push(toSerialize[i].parent);
  47340. }
  47341. }
  47342. }
  47343. toSerialize.forEach(function (mesh) {
  47344. finalizeSingleMesh(mesh, serializationObject);
  47345. });
  47346. return serializationObject;
  47347. };
  47348. return SceneSerializer;
  47349. }());
  47350. BABYLON.SceneSerializer = SceneSerializer;
  47351. })(BABYLON || (BABYLON = {}));
  47352. //# sourceMappingURL=babylon.sceneSerializer.js.map
  47353. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47354. // Huge respect for a such great lib.
  47355. // Earcut license:
  47356. // Copyright (c) 2016, Mapbox
  47357. //
  47358. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47359. // with or without fee is hereby granted, provided that the above copyright notice
  47360. // and this permission notice appear in all copies.
  47361. //
  47362. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47363. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47364. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47365. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47366. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47367. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47368. // THIS SOFTWARE.
  47369. var Earcut;
  47370. (function (Earcut) {
  47371. /**
  47372. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47373. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47374. * @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).
  47375. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47376. */
  47377. function earcut(data, holeIndices, dim) {
  47378. dim = dim || 2;
  47379. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47380. if (!outerNode)
  47381. return triangles;
  47382. var minX, minY, maxX, maxY, x, y, size;
  47383. if (hasHoles)
  47384. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47385. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47386. if (data.length > 80 * dim) {
  47387. minX = maxX = data[0];
  47388. minY = maxY = data[1];
  47389. for (var i = dim; i < outerLen; i += dim) {
  47390. x = data[i];
  47391. y = data[i + 1];
  47392. if (x < minX)
  47393. minX = x;
  47394. if (y < minY)
  47395. minY = y;
  47396. if (x > maxX)
  47397. maxX = x;
  47398. if (y > maxY)
  47399. maxY = y;
  47400. }
  47401. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47402. size = Math.max(maxX - minX, maxY - minY);
  47403. }
  47404. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47405. return triangles;
  47406. }
  47407. Earcut.earcut = earcut;
  47408. // create a circular doubly linked list from polygon points in the specified winding order
  47409. function linkedList(data, start, end, dim, clockwise) {
  47410. var i, last;
  47411. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47412. for (i = start; i < end; i += dim)
  47413. last = insertNode(i, data[i], data[i + 1], last);
  47414. }
  47415. else {
  47416. for (i = end - dim; i >= start; i -= dim)
  47417. last = insertNode(i, data[i], data[i + 1], last);
  47418. }
  47419. if (last && equals(last, last.next)) {
  47420. removeNode(last);
  47421. last = last.next;
  47422. }
  47423. return last;
  47424. }
  47425. // eliminate colinear or duplicate points
  47426. function filterPoints(start, end) {
  47427. if (!start)
  47428. return start;
  47429. if (!end)
  47430. end = start;
  47431. var p = start, again;
  47432. do {
  47433. again = false;
  47434. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47435. removeNode(p);
  47436. p = end = p.prev;
  47437. if (p === p.next)
  47438. return null;
  47439. again = true;
  47440. }
  47441. else {
  47442. p = p.next;
  47443. }
  47444. } while (again || p !== end);
  47445. return end;
  47446. }
  47447. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47448. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47449. if (!ear)
  47450. return;
  47451. // interlink polygon nodes in z-order
  47452. if (!pass && size)
  47453. indexCurve(ear, minX, minY, size);
  47454. var stop = ear, prev, next;
  47455. // iterate through ears, slicing them one by one
  47456. while (ear.prev !== ear.next) {
  47457. prev = ear.prev;
  47458. next = ear.next;
  47459. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47460. // cut off the triangle
  47461. triangles.push(prev.i / dim);
  47462. triangles.push(ear.i / dim);
  47463. triangles.push(next.i / dim);
  47464. removeNode(ear);
  47465. // skipping the next vertice leads to less sliver triangles
  47466. ear = next.next;
  47467. stop = next.next;
  47468. continue;
  47469. }
  47470. ear = next;
  47471. // if we looped through the whole remaining polygon and can't find any more ears
  47472. if (ear === stop) {
  47473. // try filtering points and slicing again
  47474. if (!pass) {
  47475. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47476. // if this didn't work, try curing all small self-intersections locally
  47477. }
  47478. else if (pass === 1) {
  47479. ear = cureLocalIntersections(ear, triangles, dim);
  47480. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47481. // as a last resort, try splitting the remaining polygon into two
  47482. }
  47483. else if (pass === 2) {
  47484. splitEarcut(ear, triangles, dim, minX, minY, size);
  47485. }
  47486. break;
  47487. }
  47488. }
  47489. }
  47490. // check whether a polygon node forms a valid ear with adjacent nodes
  47491. function isEar(ear) {
  47492. var a = ear.prev, b = ear, c = ear.next;
  47493. if (area(a, b, c) >= 0)
  47494. return false; // reflex, can't be an ear
  47495. // now make sure we don't have other points inside the potential ear
  47496. var p = ear.next.next;
  47497. while (p !== ear.prev) {
  47498. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47499. area(p.prev, p, p.next) >= 0)
  47500. return false;
  47501. p = p.next;
  47502. }
  47503. return true;
  47504. }
  47505. function isEarHashed(ear, minX, minY, size) {
  47506. var a = ear.prev, b = ear, c = ear.next;
  47507. if (area(a, b, c) >= 0)
  47508. return false; // reflex, can't be an ear
  47509. // triangle bbox; min & max are calculated like this for speed
  47510. 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);
  47511. // z-order range for the current triangle bbox;
  47512. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47513. // first look for points inside the triangle in increasing z-order
  47514. var p = ear.nextZ;
  47515. while (p && p.z <= maxZ) {
  47516. if (p !== ear.prev &&
  47517. p !== ear.next &&
  47518. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47519. area(p.prev, p, p.next) >= 0)
  47520. return false;
  47521. p = p.nextZ;
  47522. }
  47523. // then look for points in decreasing z-order
  47524. p = ear.prevZ;
  47525. while (p && p.z >= minZ) {
  47526. if (p !== ear.prev &&
  47527. p !== ear.next &&
  47528. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47529. area(p.prev, p, p.next) >= 0)
  47530. return false;
  47531. p = p.prevZ;
  47532. }
  47533. return true;
  47534. }
  47535. // go through all polygon nodes and cure small local self-intersections
  47536. function cureLocalIntersections(start, triangles, dim) {
  47537. var p = start;
  47538. do {
  47539. var a = p.prev, b = p.next.next;
  47540. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47541. triangles.push(a.i / dim);
  47542. triangles.push(p.i / dim);
  47543. triangles.push(b.i / dim);
  47544. // remove two nodes involved
  47545. removeNode(p);
  47546. removeNode(p.next);
  47547. p = start = b;
  47548. }
  47549. p = p.next;
  47550. } while (p !== start);
  47551. return p;
  47552. }
  47553. // try splitting polygon into two and triangulate them independently
  47554. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47555. // look for a valid diagonal that divides the polygon into two
  47556. var a = start;
  47557. do {
  47558. var b = a.next.next;
  47559. while (b !== a.prev) {
  47560. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47561. // split the polygon in two by the diagonal
  47562. var c = splitPolygon(a, b);
  47563. // filter colinear points around the cuts
  47564. a = filterPoints(a, a.next);
  47565. c = filterPoints(c, c.next);
  47566. // run earcut on each half
  47567. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47568. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47569. return;
  47570. }
  47571. b = b.next;
  47572. }
  47573. a = a.next;
  47574. } while (a !== start);
  47575. }
  47576. // link every hole into the outer loop, producing a single-ring polygon without holes
  47577. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47578. var queue = [], i, len, start, end, list;
  47579. for (i = 0, len = holeIndices.length; i < len; i++) {
  47580. start = holeIndices[i] * dim;
  47581. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47582. list = linkedList(data, start, end, dim, false);
  47583. if (list === list.next)
  47584. list.steiner = true;
  47585. queue.push(getLeftmost(list));
  47586. }
  47587. queue.sort(compareX);
  47588. // process holes from left to right
  47589. for (i = 0; i < queue.length; i++) {
  47590. eliminateHole(queue[i], outerNode);
  47591. outerNode = filterPoints(outerNode, outerNode.next);
  47592. }
  47593. return outerNode;
  47594. }
  47595. function compareX(a, b) {
  47596. return a.x - b.x;
  47597. }
  47598. // find a bridge between vertices that connects hole with an outer ring and and link it
  47599. function eliminateHole(hole, outerNode) {
  47600. outerNode = findHoleBridge(hole, outerNode);
  47601. if (outerNode) {
  47602. var b = splitPolygon(outerNode, hole);
  47603. filterPoints(b, b.next);
  47604. }
  47605. }
  47606. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47607. function findHoleBridge(hole, outerNode) {
  47608. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47609. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47610. // segment's endpoint with lesser x will be potential connection point
  47611. do {
  47612. if (hy <= p.y && hy >= p.next.y) {
  47613. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47614. if (x <= hx && x > qx) {
  47615. qx = x;
  47616. if (x === hx) {
  47617. if (hy === p.y)
  47618. return p;
  47619. if (hy === p.next.y)
  47620. return p.next;
  47621. }
  47622. m = p.x < p.next.x ? p : p.next;
  47623. }
  47624. }
  47625. p = p.next;
  47626. } while (p !== outerNode);
  47627. if (!m)
  47628. return null;
  47629. if (hx === qx)
  47630. return m.prev; // hole touches outer segment; pick lower endpoint
  47631. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47632. // if there are no points found, we have a valid connection;
  47633. // otherwise choose the point of the minimum angle with the ray as connection point
  47634. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47635. p = m.next;
  47636. while (p !== stop) {
  47637. if (hx >= p.x &&
  47638. p.x >= mx &&
  47639. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47640. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47641. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47642. m = p;
  47643. tanMin = tan;
  47644. }
  47645. }
  47646. p = p.next;
  47647. }
  47648. return m;
  47649. }
  47650. // interlink polygon nodes in z-order
  47651. function indexCurve(start, minX, minY, size) {
  47652. var p = start;
  47653. do {
  47654. if (p.z === null)
  47655. p.z = zOrder(p.x, p.y, minX, minY, size);
  47656. p.prevZ = p.prev;
  47657. p.nextZ = p.next;
  47658. p = p.next;
  47659. } while (p !== start);
  47660. p.prevZ.nextZ = null;
  47661. p.prevZ = null;
  47662. sortLinked(p);
  47663. }
  47664. // Simon Tatham's linked list merge sort algorithm
  47665. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47666. function sortLinked(list) {
  47667. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47668. do {
  47669. p = list;
  47670. list = null;
  47671. tail = null;
  47672. numMerges = 0;
  47673. while (p) {
  47674. numMerges++;
  47675. q = p;
  47676. pSize = 0;
  47677. for (i = 0; i < inSize; i++) {
  47678. pSize++;
  47679. q = q.nextZ;
  47680. if (!q)
  47681. break;
  47682. }
  47683. qSize = inSize;
  47684. while (pSize > 0 || (qSize > 0 && q)) {
  47685. if (pSize === 0) {
  47686. e = q;
  47687. q = q.nextZ;
  47688. qSize--;
  47689. }
  47690. else if (qSize === 0 || !q) {
  47691. e = p;
  47692. p = p.nextZ;
  47693. pSize--;
  47694. }
  47695. else if (p.z <= q.z) {
  47696. e = p;
  47697. p = p.nextZ;
  47698. pSize--;
  47699. }
  47700. else {
  47701. e = q;
  47702. q = q.nextZ;
  47703. qSize--;
  47704. }
  47705. if (tail)
  47706. tail.nextZ = e;
  47707. else
  47708. list = e;
  47709. e.prevZ = tail;
  47710. tail = e;
  47711. }
  47712. p = q;
  47713. }
  47714. tail.nextZ = null;
  47715. inSize *= 2;
  47716. } while (numMerges > 1);
  47717. return list;
  47718. }
  47719. // z-order of a point given coords and size of the data bounding box
  47720. function zOrder(x, y, minX, minY, size) {
  47721. // coords are transformed into non-negative 15-bit integer range
  47722. x = 32767 * (x - minX) / size;
  47723. y = 32767 * (y - minY) / size;
  47724. x = (x | (x << 8)) & 0x00FF00FF;
  47725. x = (x | (x << 4)) & 0x0F0F0F0F;
  47726. x = (x | (x << 2)) & 0x33333333;
  47727. x = (x | (x << 1)) & 0x55555555;
  47728. y = (y | (y << 8)) & 0x00FF00FF;
  47729. y = (y | (y << 4)) & 0x0F0F0F0F;
  47730. y = (y | (y << 2)) & 0x33333333;
  47731. y = (y | (y << 1)) & 0x55555555;
  47732. return x | (y << 1);
  47733. }
  47734. // find the leftmost node of a polygon ring
  47735. function getLeftmost(start) {
  47736. var p = start, leftmost = start;
  47737. do {
  47738. if (p.x < leftmost.x)
  47739. leftmost = p;
  47740. p = p.next;
  47741. } while (p !== start);
  47742. return leftmost;
  47743. }
  47744. // check if a point lies within a convex triangle
  47745. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47746. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47747. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47748. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47749. }
  47750. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47751. function isValidDiagonal(a, b) {
  47752. return a.next.i !== b.i &&
  47753. a.prev.i !== b.i &&
  47754. !intersectsPolygon(a, b) &&
  47755. locallyInside(a, b) &&
  47756. locallyInside(b, a) &&
  47757. middleInside(a, b);
  47758. }
  47759. // signed area of a triangle
  47760. function area(p, q, r) {
  47761. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47762. }
  47763. // check if two points are equal
  47764. function equals(p1, p2) {
  47765. return p1.x === p2.x && p1.y === p2.y;
  47766. }
  47767. // check if two segments intersect
  47768. function intersects(p1, q1, p2, q2) {
  47769. if ((equals(p1, q1) && equals(p2, q2)) ||
  47770. (equals(p1, q2) && equals(p2, q1)))
  47771. return true;
  47772. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47773. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47774. }
  47775. // check if a polygon diagonal intersects any polygon segments
  47776. function intersectsPolygon(a, b) {
  47777. var p = a;
  47778. do {
  47779. if (p.i !== a.i &&
  47780. p.next.i !== a.i &&
  47781. p.i !== b.i &&
  47782. p.next.i !== b.i &&
  47783. intersects(p, p.next, a, b))
  47784. return true;
  47785. p = p.next;
  47786. } while (p !== a);
  47787. return false;
  47788. }
  47789. // check if a polygon diagonal is locally inside the polygon
  47790. function locallyInside(a, b) {
  47791. return area(a.prev, a, a.next) < 0
  47792. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47793. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47794. }
  47795. // check if the middle point of a polygon diagonal is inside the polygon
  47796. function middleInside(a, b) {
  47797. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47798. do {
  47799. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47800. inside = !inside;
  47801. p = p.next;
  47802. } while (p !== a);
  47803. return inside;
  47804. }
  47805. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47806. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47807. function splitPolygon(a, b) {
  47808. 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;
  47809. a.next = b;
  47810. b.prev = a;
  47811. a2.next = an;
  47812. an.prev = a2;
  47813. b2.next = a2;
  47814. a2.prev = b2;
  47815. bp.next = b2;
  47816. b2.prev = bp;
  47817. return b2;
  47818. }
  47819. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47820. function insertNode(i, x, y, last) {
  47821. var p = new Node(i, x, y);
  47822. if (!last) {
  47823. p.prev = p;
  47824. p.next = p;
  47825. }
  47826. else {
  47827. p.next = last.next;
  47828. p.prev = last;
  47829. last.next.prev = p;
  47830. last.next = p;
  47831. }
  47832. return p;
  47833. }
  47834. function removeNode(p) {
  47835. p.next.prev = p.prev;
  47836. p.prev.next = p.next;
  47837. if (p.prevZ)
  47838. p.prevZ.nextZ = p.nextZ;
  47839. if (p.nextZ)
  47840. p.nextZ.prevZ = p.prevZ;
  47841. }
  47842. function Node(i, x, y) {
  47843. // vertice index in coordinates array
  47844. this.i = i;
  47845. // vertex coordinates
  47846. this.x = x;
  47847. this.y = y;
  47848. // previous and next vertice nodes in a polygon ring
  47849. this.prev = null;
  47850. this.next = null;
  47851. // z-order curve value
  47852. this.z = null;
  47853. // previous and next nodes in z-order
  47854. this.prevZ = null;
  47855. this.nextZ = null;
  47856. // indicates whether this is a steiner point
  47857. this.steiner = false;
  47858. }
  47859. /**
  47860. * return a percentage difference between the polygon area and its triangulation area;
  47861. * used to verify correctness of triangulation
  47862. */
  47863. function deviation(data, holeIndices, dim, triangles) {
  47864. var hasHoles = holeIndices && holeIndices.length;
  47865. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47866. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47867. if (hasHoles) {
  47868. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47869. var start = holeIndices[i] * dim;
  47870. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47871. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47872. }
  47873. }
  47874. var trianglesArea = 0;
  47875. for (i = 0; i < triangles.length; i += 3) {
  47876. var a = triangles[i] * dim;
  47877. var b = triangles[i + 1] * dim;
  47878. var c = triangles[i + 2] * dim;
  47879. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47880. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47881. }
  47882. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47883. }
  47884. Earcut.deviation = deviation;
  47885. ;
  47886. function signedArea(data, start, end, dim) {
  47887. var sum = 0;
  47888. for (var i = start, j = end - dim; i < end; i += dim) {
  47889. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47890. j = i;
  47891. }
  47892. return sum;
  47893. }
  47894. /**
  47895. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47896. */
  47897. function flatten(data) {
  47898. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47899. for (var i = 0; i < data.length; i++) {
  47900. for (var j = 0; j < data[i].length; j++) {
  47901. for (var d = 0; d < dim; d++)
  47902. result.vertices.push(data[i][j][d]);
  47903. }
  47904. if (i > 0) {
  47905. holeIndex += data[i - 1].length;
  47906. result.holes.push(holeIndex);
  47907. }
  47908. }
  47909. return result;
  47910. }
  47911. Earcut.flatten = flatten;
  47912. ;
  47913. })(Earcut || (Earcut = {}));
  47914. //# sourceMappingURL=babylon.earcut.js.map
  47915. var BABYLON;
  47916. (function (BABYLON) {
  47917. // Unique ID when we import meshes from Babylon to CSG
  47918. var currentCSGMeshId = 0;
  47919. // # class Vertex
  47920. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47921. // one to provide additional features like texture coordinates and vertex
  47922. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47923. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47924. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47925. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47926. // is not used anywhere else.
  47927. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47928. var Vertex = (function () {
  47929. function Vertex(pos, normal, uv) {
  47930. this.pos = pos;
  47931. this.normal = normal;
  47932. this.uv = uv;
  47933. }
  47934. Vertex.prototype.clone = function () {
  47935. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47936. };
  47937. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47938. // orientation of a polygon is flipped.
  47939. Vertex.prototype.flip = function () {
  47940. this.normal = this.normal.scale(-1);
  47941. };
  47942. // Create a new vertex between this vertex and `other` by linearly
  47943. // interpolating all properties using a parameter of `t`. Subclasses should
  47944. // override this to interpolate additional properties.
  47945. Vertex.prototype.interpolate = function (other, t) {
  47946. 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));
  47947. };
  47948. return Vertex;
  47949. }());
  47950. // # class Plane
  47951. // Represents a plane in 3D space.
  47952. var Plane = (function () {
  47953. function Plane(normal, w) {
  47954. this.normal = normal;
  47955. this.w = w;
  47956. }
  47957. Plane.FromPoints = function (a, b, c) {
  47958. var v0 = c.subtract(a);
  47959. var v1 = b.subtract(a);
  47960. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47961. return null;
  47962. }
  47963. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47964. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47965. };
  47966. Plane.prototype.clone = function () {
  47967. return new Plane(this.normal.clone(), this.w);
  47968. };
  47969. Plane.prototype.flip = function () {
  47970. this.normal.scaleInPlace(-1);
  47971. this.w = -this.w;
  47972. };
  47973. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47974. // fragments in the appropriate lists. Coplanar polygons go into either
  47975. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47976. // respect to this plane. Polygons in front or in back of this plane go into
  47977. // either `front` or `back`.
  47978. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47979. var COPLANAR = 0;
  47980. var FRONT = 1;
  47981. var BACK = 2;
  47982. var SPANNING = 3;
  47983. // Classify each point as well as the entire polygon into one of the above
  47984. // four classes.
  47985. var polygonType = 0;
  47986. var types = [];
  47987. var i;
  47988. var t;
  47989. for (i = 0; i < polygon.vertices.length; i++) {
  47990. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47991. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47992. polygonType |= type;
  47993. types.push(type);
  47994. }
  47995. // Put the polygon in the correct list, splitting it when necessary.
  47996. switch (polygonType) {
  47997. case COPLANAR:
  47998. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47999. break;
  48000. case FRONT:
  48001. front.push(polygon);
  48002. break;
  48003. case BACK:
  48004. back.push(polygon);
  48005. break;
  48006. case SPANNING:
  48007. var f = [], b = [];
  48008. for (i = 0; i < polygon.vertices.length; i++) {
  48009. var j = (i + 1) % polygon.vertices.length;
  48010. var ti = types[i], tj = types[j];
  48011. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  48012. if (ti !== BACK)
  48013. f.push(vi);
  48014. if (ti !== FRONT)
  48015. b.push(ti !== BACK ? vi.clone() : vi);
  48016. if ((ti | tj) === SPANNING) {
  48017. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  48018. var v = vi.interpolate(vj, t);
  48019. f.push(v);
  48020. b.push(v.clone());
  48021. }
  48022. }
  48023. var poly;
  48024. if (f.length >= 3) {
  48025. poly = new Polygon(f, polygon.shared);
  48026. if (poly.plane)
  48027. front.push(poly);
  48028. }
  48029. if (b.length >= 3) {
  48030. poly = new Polygon(b, polygon.shared);
  48031. if (poly.plane)
  48032. back.push(poly);
  48033. }
  48034. break;
  48035. }
  48036. };
  48037. return Plane;
  48038. }());
  48039. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  48040. // point is on the plane.
  48041. Plane.EPSILON = 1e-5;
  48042. // # class Polygon
  48043. // Represents a convex polygon. The vertices used to initialize a polygon must
  48044. // be coplanar and form a convex loop.
  48045. //
  48046. // Each convex polygon has a `shared` property, which is shared between all
  48047. // polygons that are clones of each other or were split from the same polygon.
  48048. // This can be used to define per-polygon properties (such as surface color).
  48049. var Polygon = (function () {
  48050. function Polygon(vertices, shared) {
  48051. this.vertices = vertices;
  48052. this.shared = shared;
  48053. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  48054. }
  48055. Polygon.prototype.clone = function () {
  48056. var vertices = this.vertices.map(function (v) { return v.clone(); });
  48057. return new Polygon(vertices, this.shared);
  48058. };
  48059. Polygon.prototype.flip = function () {
  48060. this.vertices.reverse().map(function (v) { v.flip(); });
  48061. this.plane.flip();
  48062. };
  48063. return Polygon;
  48064. }());
  48065. // # class Node
  48066. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  48067. // by picking a polygon to split along. That polygon (and all other coplanar
  48068. // polygons) are added directly to that node and the other polygons are added to
  48069. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  48070. // no distinction between internal and leaf nodes.
  48071. var Node = (function () {
  48072. function Node(polygons) {
  48073. this.plane = null;
  48074. this.front = null;
  48075. this.back = null;
  48076. this.polygons = [];
  48077. if (polygons) {
  48078. this.build(polygons);
  48079. }
  48080. }
  48081. Node.prototype.clone = function () {
  48082. var node = new Node();
  48083. node.plane = this.plane && this.plane.clone();
  48084. node.front = this.front && this.front.clone();
  48085. node.back = this.back && this.back.clone();
  48086. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  48087. return node;
  48088. };
  48089. // Convert solid space to empty space and empty space to solid space.
  48090. Node.prototype.invert = function () {
  48091. for (var i = 0; i < this.polygons.length; i++) {
  48092. this.polygons[i].flip();
  48093. }
  48094. if (this.plane) {
  48095. this.plane.flip();
  48096. }
  48097. if (this.front) {
  48098. this.front.invert();
  48099. }
  48100. if (this.back) {
  48101. this.back.invert();
  48102. }
  48103. var temp = this.front;
  48104. this.front = this.back;
  48105. this.back = temp;
  48106. };
  48107. // Recursively remove all polygons in `polygons` that are inside this BSP
  48108. // tree.
  48109. Node.prototype.clipPolygons = function (polygons) {
  48110. if (!this.plane)
  48111. return polygons.slice();
  48112. var front = [], back = [];
  48113. for (var i = 0; i < polygons.length; i++) {
  48114. this.plane.splitPolygon(polygons[i], front, back, front, back);
  48115. }
  48116. if (this.front) {
  48117. front = this.front.clipPolygons(front);
  48118. }
  48119. if (this.back) {
  48120. back = this.back.clipPolygons(back);
  48121. }
  48122. else {
  48123. back = [];
  48124. }
  48125. return front.concat(back);
  48126. };
  48127. // Remove all polygons in this BSP tree that are inside the other BSP tree
  48128. // `bsp`.
  48129. Node.prototype.clipTo = function (bsp) {
  48130. this.polygons = bsp.clipPolygons(this.polygons);
  48131. if (this.front)
  48132. this.front.clipTo(bsp);
  48133. if (this.back)
  48134. this.back.clipTo(bsp);
  48135. };
  48136. // Return a list of all polygons in this BSP tree.
  48137. Node.prototype.allPolygons = function () {
  48138. var polygons = this.polygons.slice();
  48139. if (this.front)
  48140. polygons = polygons.concat(this.front.allPolygons());
  48141. if (this.back)
  48142. polygons = polygons.concat(this.back.allPolygons());
  48143. return polygons;
  48144. };
  48145. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  48146. // new polygons are filtered down to the bottom of the tree and become new
  48147. // nodes there. Each set of polygons is partitioned using the first polygon
  48148. // (no heuristic is used to pick a good split).
  48149. Node.prototype.build = function (polygons) {
  48150. if (!polygons.length)
  48151. return;
  48152. if (!this.plane)
  48153. this.plane = polygons[0].plane.clone();
  48154. var front = [], back = [];
  48155. for (var i = 0; i < polygons.length; i++) {
  48156. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48157. }
  48158. if (front.length) {
  48159. if (!this.front)
  48160. this.front = new Node();
  48161. this.front.build(front);
  48162. }
  48163. if (back.length) {
  48164. if (!this.back)
  48165. this.back = new Node();
  48166. this.back.build(back);
  48167. }
  48168. };
  48169. return Node;
  48170. }());
  48171. var CSG = (function () {
  48172. function CSG() {
  48173. this.polygons = new Array();
  48174. }
  48175. // Convert BABYLON.Mesh to BABYLON.CSG
  48176. CSG.FromMesh = function (mesh) {
  48177. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48178. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48179. if (mesh instanceof BABYLON.Mesh) {
  48180. mesh.computeWorldMatrix(true);
  48181. matrix = mesh.getWorldMatrix();
  48182. meshPosition = mesh.position.clone();
  48183. meshRotation = mesh.rotation.clone();
  48184. if (mesh.rotationQuaternion) {
  48185. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48186. }
  48187. meshScaling = mesh.scaling.clone();
  48188. }
  48189. else {
  48190. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48191. }
  48192. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48193. var subMeshes = mesh.subMeshes;
  48194. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48195. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48196. vertices = [];
  48197. for (var j = 0; j < 3; j++) {
  48198. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48199. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48200. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48201. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48202. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48203. vertex = new Vertex(position, normal, uv);
  48204. vertices.push(vertex);
  48205. }
  48206. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48207. // To handle the case of degenerated triangle
  48208. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48209. if (polygon.plane)
  48210. polygons.push(polygon);
  48211. }
  48212. }
  48213. var csg = CSG.FromPolygons(polygons);
  48214. csg.matrix = matrix;
  48215. csg.position = meshPosition;
  48216. csg.rotation = meshRotation;
  48217. csg.scaling = meshScaling;
  48218. csg.rotationQuaternion = meshRotationQuaternion;
  48219. currentCSGMeshId++;
  48220. return csg;
  48221. };
  48222. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48223. CSG.FromPolygons = function (polygons) {
  48224. var csg = new CSG();
  48225. csg.polygons = polygons;
  48226. return csg;
  48227. };
  48228. CSG.prototype.clone = function () {
  48229. var csg = new CSG();
  48230. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48231. csg.copyTransformAttributes(this);
  48232. return csg;
  48233. };
  48234. CSG.prototype.toPolygons = function () {
  48235. return this.polygons;
  48236. };
  48237. CSG.prototype.union = function (csg) {
  48238. var a = new Node(this.clone().polygons);
  48239. var b = new Node(csg.clone().polygons);
  48240. a.clipTo(b);
  48241. b.clipTo(a);
  48242. b.invert();
  48243. b.clipTo(a);
  48244. b.invert();
  48245. a.build(b.allPolygons());
  48246. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48247. };
  48248. CSG.prototype.unionInPlace = function (csg) {
  48249. var a = new Node(this.polygons);
  48250. var b = new Node(csg.polygons);
  48251. a.clipTo(b);
  48252. b.clipTo(a);
  48253. b.invert();
  48254. b.clipTo(a);
  48255. b.invert();
  48256. a.build(b.allPolygons());
  48257. this.polygons = a.allPolygons();
  48258. };
  48259. CSG.prototype.subtract = function (csg) {
  48260. var a = new Node(this.clone().polygons);
  48261. var b = new Node(csg.clone().polygons);
  48262. a.invert();
  48263. a.clipTo(b);
  48264. b.clipTo(a);
  48265. b.invert();
  48266. b.clipTo(a);
  48267. b.invert();
  48268. a.build(b.allPolygons());
  48269. a.invert();
  48270. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48271. };
  48272. CSG.prototype.subtractInPlace = function (csg) {
  48273. var a = new Node(this.polygons);
  48274. var b = new Node(csg.polygons);
  48275. a.invert();
  48276. a.clipTo(b);
  48277. b.clipTo(a);
  48278. b.invert();
  48279. b.clipTo(a);
  48280. b.invert();
  48281. a.build(b.allPolygons());
  48282. a.invert();
  48283. this.polygons = a.allPolygons();
  48284. };
  48285. CSG.prototype.intersect = function (csg) {
  48286. var a = new Node(this.clone().polygons);
  48287. var b = new Node(csg.clone().polygons);
  48288. a.invert();
  48289. b.clipTo(a);
  48290. b.invert();
  48291. a.clipTo(b);
  48292. b.clipTo(a);
  48293. a.build(b.allPolygons());
  48294. a.invert();
  48295. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48296. };
  48297. CSG.prototype.intersectInPlace = function (csg) {
  48298. var a = new Node(this.polygons);
  48299. var b = new Node(csg.polygons);
  48300. a.invert();
  48301. b.clipTo(a);
  48302. b.invert();
  48303. a.clipTo(b);
  48304. b.clipTo(a);
  48305. a.build(b.allPolygons());
  48306. a.invert();
  48307. this.polygons = a.allPolygons();
  48308. };
  48309. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48310. // not modified.
  48311. CSG.prototype.inverse = function () {
  48312. var csg = this.clone();
  48313. csg.inverseInPlace();
  48314. return csg;
  48315. };
  48316. CSG.prototype.inverseInPlace = function () {
  48317. this.polygons.map(function (p) { p.flip(); });
  48318. };
  48319. // This is used to keep meshes transformations so they can be restored
  48320. // when we build back a Babylon Mesh
  48321. // NB : All CSG operations are performed in world coordinates
  48322. CSG.prototype.copyTransformAttributes = function (csg) {
  48323. this.matrix = csg.matrix;
  48324. this.position = csg.position;
  48325. this.rotation = csg.rotation;
  48326. this.scaling = csg.scaling;
  48327. this.rotationQuaternion = csg.rotationQuaternion;
  48328. return this;
  48329. };
  48330. // Build Raw mesh from CSG
  48331. // Coordinates here are in world space
  48332. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48333. var matrix = this.matrix.clone();
  48334. matrix.invert();
  48335. 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;
  48336. if (keepSubMeshes) {
  48337. // Sort Polygons, since subMeshes are indices range
  48338. polygons.sort(function (a, b) {
  48339. if (a.shared.meshId === b.shared.meshId) {
  48340. return a.shared.subMeshId - b.shared.subMeshId;
  48341. }
  48342. else {
  48343. return a.shared.meshId - b.shared.meshId;
  48344. }
  48345. });
  48346. }
  48347. for (var i = 0, il = polygons.length; i < il; i++) {
  48348. polygon = polygons[i];
  48349. // Building SubMeshes
  48350. if (!subMesh_dict[polygon.shared.meshId]) {
  48351. subMesh_dict[polygon.shared.meshId] = {};
  48352. }
  48353. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48354. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48355. indexStart: +Infinity,
  48356. indexEnd: -Infinity,
  48357. materialIndex: polygon.shared.materialIndex
  48358. };
  48359. }
  48360. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48361. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48362. polygonIndices[0] = 0;
  48363. polygonIndices[1] = j - 1;
  48364. polygonIndices[2] = j;
  48365. for (var k = 0; k < 3; k++) {
  48366. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48367. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48368. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48369. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48370. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48371. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48372. // Check if 2 points can be merged
  48373. if (!(typeof vertex_idx !== 'undefined' &&
  48374. normals[vertex_idx * 3] === localNormal.x &&
  48375. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48376. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48377. uvs[vertex_idx * 2] === uv.x &&
  48378. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48379. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48380. uvs.push(uv.x, uv.y);
  48381. normals.push(normal.x, normal.y, normal.z);
  48382. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48383. }
  48384. indices.push(vertex_idx);
  48385. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48386. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48387. currentIndex++;
  48388. }
  48389. }
  48390. }
  48391. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48392. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48393. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48394. mesh.setIndices(indices);
  48395. if (keepSubMeshes) {
  48396. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48397. var materialIndexOffset = 0, materialMaxIndex;
  48398. mesh.subMeshes = new Array();
  48399. for (var m in subMesh_dict) {
  48400. materialMaxIndex = -1;
  48401. for (var sm in subMesh_dict[m]) {
  48402. subMesh_obj = subMesh_dict[m][sm];
  48403. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48404. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48405. }
  48406. materialIndexOffset += ++materialMaxIndex;
  48407. }
  48408. }
  48409. return mesh;
  48410. };
  48411. // Build Mesh from CSG taking material and transforms into account
  48412. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48413. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48414. mesh.material = material;
  48415. mesh.position.copyFrom(this.position);
  48416. mesh.rotation.copyFrom(this.rotation);
  48417. if (this.rotationQuaternion) {
  48418. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48419. }
  48420. mesh.scaling.copyFrom(this.scaling);
  48421. mesh.computeWorldMatrix(true);
  48422. return mesh;
  48423. };
  48424. return CSG;
  48425. }());
  48426. BABYLON.CSG = CSG;
  48427. })(BABYLON || (BABYLON = {}));
  48428. //# sourceMappingURL=babylon.csg.js.map
  48429. var BABYLON;
  48430. (function (BABYLON) {
  48431. var VRDistortionCorrectionPostProcess = (function (_super) {
  48432. __extends(VRDistortionCorrectionPostProcess, _super);
  48433. //ANY
  48434. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48435. var _this = _super.call(this, name, "vrDistortionCorrection", [
  48436. 'LensCenter',
  48437. 'Scale',
  48438. 'ScaleIn',
  48439. 'HmdWarpParam'
  48440. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  48441. _this._isRightEye = isRightEye;
  48442. _this._distortionFactors = vrMetrics.distortionK;
  48443. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48444. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48445. _this.onSizeChangedObservable.add(function () {
  48446. _this.aspectRatio = _this.width * .5 / _this.height;
  48447. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48448. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48449. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48450. });
  48451. _this.onApplyObservable.add(function (effect) {
  48452. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48453. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48454. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48455. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48456. });
  48457. return _this;
  48458. }
  48459. return VRDistortionCorrectionPostProcess;
  48460. }(BABYLON.PostProcess));
  48461. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48462. })(BABYLON || (BABYLON = {}));
  48463. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  48464. // Mainly based on these 2 articles :
  48465. // 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
  48466. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48467. var BABYLON;
  48468. (function (BABYLON) {
  48469. var JoystickAxis;
  48470. (function (JoystickAxis) {
  48471. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48472. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48473. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48474. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48475. var VirtualJoystick = (function () {
  48476. function VirtualJoystick(leftJoystick) {
  48477. var _this = this;
  48478. if (leftJoystick) {
  48479. this._leftJoystick = true;
  48480. }
  48481. else {
  48482. this._leftJoystick = false;
  48483. }
  48484. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48485. VirtualJoystick._globalJoystickIndex++;
  48486. // By default left & right arrow keys are moving the X
  48487. // and up & down keys are moving the Y
  48488. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48489. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48490. this.reverseLeftRight = false;
  48491. this.reverseUpDown = false;
  48492. // collections of pointers
  48493. this._touches = new BABYLON.StringDictionary();
  48494. this.deltaPosition = BABYLON.Vector3.Zero();
  48495. this._joystickSensibility = 25;
  48496. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48497. this._rotationSpeed = 25;
  48498. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48499. this._rotateOnAxisRelativeToMesh = false;
  48500. this._onResize = function (evt) {
  48501. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48502. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48503. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48504. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48505. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48506. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48507. };
  48508. // injecting a canvas element on top of the canvas 3D game
  48509. if (!VirtualJoystick.vjCanvas) {
  48510. window.addEventListener("resize", this._onResize, false);
  48511. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48512. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48513. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48514. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48515. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48516. VirtualJoystick.vjCanvas.style.width = "100%";
  48517. VirtualJoystick.vjCanvas.style.height = "100%";
  48518. VirtualJoystick.vjCanvas.style.position = "absolute";
  48519. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48520. VirtualJoystick.vjCanvas.style.top = "0px";
  48521. VirtualJoystick.vjCanvas.style.left = "0px";
  48522. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48523. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48524. // Support for jQuery PEP polyfill
  48525. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48526. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48527. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48528. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48529. document.body.appendChild(VirtualJoystick.vjCanvas);
  48530. }
  48531. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48532. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48533. this.pressed = false;
  48534. // default joystick color
  48535. this._joystickColor = "cyan";
  48536. this._joystickPointerID = -1;
  48537. // current joystick position
  48538. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48539. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48540. // origin joystick position
  48541. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48542. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48543. this._onPointerDownHandlerRef = function (evt) {
  48544. _this._onPointerDown(evt);
  48545. };
  48546. this._onPointerMoveHandlerRef = function (evt) {
  48547. _this._onPointerMove(evt);
  48548. };
  48549. this._onPointerOutHandlerRef = function (evt) {
  48550. _this._onPointerUp(evt);
  48551. };
  48552. this._onPointerUpHandlerRef = function (evt) {
  48553. _this._onPointerUp(evt);
  48554. };
  48555. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48556. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48557. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48558. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48559. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48560. evt.preventDefault(); // Disables system menu
  48561. }, false);
  48562. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48563. }
  48564. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48565. this._joystickSensibility = newJoystickSensibility;
  48566. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48567. };
  48568. VirtualJoystick.prototype._onPointerDown = function (e) {
  48569. var positionOnScreenCondition;
  48570. e.preventDefault();
  48571. if (this._leftJoystick === true) {
  48572. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48573. }
  48574. else {
  48575. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48576. }
  48577. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48578. // First contact will be dedicated to the virtual joystick
  48579. this._joystickPointerID = e.pointerId;
  48580. this._joystickPointerStartPos.x = e.clientX;
  48581. this._joystickPointerStartPos.y = e.clientY;
  48582. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48583. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48584. this._deltaJoystickVector.x = 0;
  48585. this._deltaJoystickVector.y = 0;
  48586. this.pressed = true;
  48587. this._touches.add(e.pointerId.toString(), e);
  48588. }
  48589. else {
  48590. // You can only trigger the action buttons with a joystick declared
  48591. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48592. this._action();
  48593. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48594. }
  48595. }
  48596. };
  48597. VirtualJoystick.prototype._onPointerMove = function (e) {
  48598. // If the current pointer is the one associated to the joystick (first touch contact)
  48599. if (this._joystickPointerID == e.pointerId) {
  48600. this._joystickPointerPos.x = e.clientX;
  48601. this._joystickPointerPos.y = e.clientY;
  48602. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48603. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48604. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48605. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48606. switch (this._axisTargetedByLeftAndRight) {
  48607. case JoystickAxis.X:
  48608. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48609. break;
  48610. case JoystickAxis.Y:
  48611. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48612. break;
  48613. case JoystickAxis.Z:
  48614. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48615. break;
  48616. }
  48617. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48618. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48619. switch (this._axisTargetedByUpAndDown) {
  48620. case JoystickAxis.X:
  48621. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48622. break;
  48623. case JoystickAxis.Y:
  48624. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48625. break;
  48626. case JoystickAxis.Z:
  48627. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48628. break;
  48629. }
  48630. }
  48631. else {
  48632. var data = this._touches.get(e.pointerId.toString());
  48633. if (data) {
  48634. data.x = e.clientX;
  48635. data.y = e.clientY;
  48636. }
  48637. }
  48638. };
  48639. VirtualJoystick.prototype._onPointerUp = function (e) {
  48640. if (this._joystickPointerID == e.pointerId) {
  48641. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  48642. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  48643. this._joystickPointerID = -1;
  48644. this.pressed = false;
  48645. }
  48646. else {
  48647. var touch = this._touches.get(e.pointerId.toString());
  48648. if (touch) {
  48649. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48650. }
  48651. }
  48652. this._deltaJoystickVector.x = 0;
  48653. this._deltaJoystickVector.y = 0;
  48654. this._touches.remove(e.pointerId.toString());
  48655. };
  48656. /**
  48657. * Change the color of the virtual joystick
  48658. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48659. */
  48660. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48661. this._joystickColor = newColor;
  48662. };
  48663. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48664. this._action = action;
  48665. };
  48666. // Define which axis you'd like to control for left & right
  48667. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48668. switch (axis) {
  48669. case JoystickAxis.X:
  48670. case JoystickAxis.Y:
  48671. case JoystickAxis.Z:
  48672. this._axisTargetedByLeftAndRight = axis;
  48673. break;
  48674. default:
  48675. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48676. break;
  48677. }
  48678. };
  48679. // Define which axis you'd like to control for up & down
  48680. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48681. switch (axis) {
  48682. case JoystickAxis.X:
  48683. case JoystickAxis.Y:
  48684. case JoystickAxis.Z:
  48685. this._axisTargetedByUpAndDown = axis;
  48686. break;
  48687. default:
  48688. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48689. break;
  48690. }
  48691. };
  48692. VirtualJoystick.prototype._clearCanvas = function () {
  48693. if (this._leftJoystick) {
  48694. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48695. }
  48696. else {
  48697. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48698. }
  48699. };
  48700. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48701. var _this = this;
  48702. if (this.pressed) {
  48703. this._touches.forEach(function (key, touch) {
  48704. if (touch.pointerId === _this._joystickPointerID) {
  48705. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  48706. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  48707. VirtualJoystick.vjCanvasContext.beginPath();
  48708. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48709. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48710. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48711. VirtualJoystick.vjCanvasContext.stroke();
  48712. VirtualJoystick.vjCanvasContext.closePath();
  48713. VirtualJoystick.vjCanvasContext.beginPath();
  48714. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48715. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48716. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48717. VirtualJoystick.vjCanvasContext.stroke();
  48718. VirtualJoystick.vjCanvasContext.closePath();
  48719. VirtualJoystick.vjCanvasContext.beginPath();
  48720. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48721. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48722. VirtualJoystick.vjCanvasContext.stroke();
  48723. VirtualJoystick.vjCanvasContext.closePath();
  48724. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48725. }
  48726. else {
  48727. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48728. VirtualJoystick.vjCanvasContext.beginPath();
  48729. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48730. VirtualJoystick.vjCanvasContext.beginPath();
  48731. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48732. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48733. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48734. VirtualJoystick.vjCanvasContext.stroke();
  48735. VirtualJoystick.vjCanvasContext.closePath();
  48736. touch.prevX = touch.x;
  48737. touch.prevY = touch.y;
  48738. }
  48739. ;
  48740. });
  48741. }
  48742. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48743. };
  48744. VirtualJoystick.prototype.releaseCanvas = function () {
  48745. if (VirtualJoystick.vjCanvas) {
  48746. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48747. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48748. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48749. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48750. window.removeEventListener("resize", this._onResize);
  48751. document.body.removeChild(VirtualJoystick.vjCanvas);
  48752. VirtualJoystick.vjCanvas = null;
  48753. }
  48754. };
  48755. return VirtualJoystick;
  48756. }());
  48757. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48758. VirtualJoystick._globalJoystickIndex = 0;
  48759. BABYLON.VirtualJoystick = VirtualJoystick;
  48760. })(BABYLON || (BABYLON = {}));
  48761. //# sourceMappingURL=babylon.virtualJoystick.js.map
  48762. var BABYLON;
  48763. (function (BABYLON) {
  48764. // We're mainly based on the logic defined into the FreeCamera code
  48765. var VirtualJoysticksCamera = (function (_super) {
  48766. __extends(VirtualJoysticksCamera, _super);
  48767. function VirtualJoysticksCamera(name, position, scene) {
  48768. var _this = _super.call(this, name, position, scene) || this;
  48769. _this.inputs.addVirtualJoystick();
  48770. return _this;
  48771. }
  48772. VirtualJoysticksCamera.prototype.getClassName = function () {
  48773. return "VirtualJoysticksCamera";
  48774. };
  48775. return VirtualJoysticksCamera;
  48776. }(BABYLON.FreeCamera));
  48777. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48778. })(BABYLON || (BABYLON = {}));
  48779. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  48780. var BABYLON;
  48781. (function (BABYLON) {
  48782. var FreeCameraVirtualJoystickInput = (function () {
  48783. function FreeCameraVirtualJoystickInput() {
  48784. }
  48785. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48786. return this._leftjoystick;
  48787. };
  48788. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48789. return this._rightjoystick;
  48790. };
  48791. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48792. if (this._leftjoystick) {
  48793. var camera = this.camera;
  48794. var speed = camera._computeLocalCameraSpeed() * 50;
  48795. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48796. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48797. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48798. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48799. if (!this._leftjoystick.pressed) {
  48800. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48801. }
  48802. if (!this._rightjoystick.pressed) {
  48803. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48804. }
  48805. }
  48806. };
  48807. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48808. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48809. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48810. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48811. this._leftjoystick.setJoystickSensibility(0.15);
  48812. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48813. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48814. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48815. this._rightjoystick.reverseUpDown = true;
  48816. this._rightjoystick.setJoystickSensibility(0.05);
  48817. this._rightjoystick.setJoystickColor("yellow");
  48818. };
  48819. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48820. this._leftjoystick.releaseCanvas();
  48821. this._rightjoystick.releaseCanvas();
  48822. };
  48823. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48824. return "FreeCameraVirtualJoystickInput";
  48825. };
  48826. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48827. return "virtualJoystick";
  48828. };
  48829. return FreeCameraVirtualJoystickInput;
  48830. }());
  48831. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48832. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48833. })(BABYLON || (BABYLON = {}));
  48834. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48835. var BABYLON;
  48836. (function (BABYLON) {
  48837. var AnaglyphPostProcess = (function (_super) {
  48838. __extends(AnaglyphPostProcess, _super);
  48839. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48840. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48841. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48842. _this.onApplyObservable.add(function (effect) {
  48843. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48844. });
  48845. return _this;
  48846. }
  48847. return AnaglyphPostProcess;
  48848. }(BABYLON.PostProcess));
  48849. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48850. })(BABYLON || (BABYLON = {}));
  48851. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48852. var BABYLON;
  48853. (function (BABYLON) {
  48854. var OutlineRenderer = (function () {
  48855. function OutlineRenderer(scene) {
  48856. this._scene = scene;
  48857. }
  48858. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48859. var _this = this;
  48860. if (useOverlay === void 0) { useOverlay = false; }
  48861. var scene = this._scene;
  48862. var engine = this._scene.getEngine();
  48863. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48864. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48865. return;
  48866. }
  48867. var mesh = subMesh.getRenderingMesh();
  48868. var material = subMesh.getMaterial();
  48869. engine.enableEffect(this._effect);
  48870. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48871. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48872. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48873. // Bones
  48874. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48875. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48876. }
  48877. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48878. // Alpha test
  48879. if (material && material.needAlphaTesting()) {
  48880. var alphaTexture = material.getAlphaTestTexture();
  48881. this._effect.setTexture("diffuseSampler", alphaTexture);
  48882. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48883. }
  48884. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48885. };
  48886. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48887. var defines = [];
  48888. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48889. var mesh = subMesh.getMesh();
  48890. var material = subMesh.getMaterial();
  48891. // Alpha test
  48892. if (material && material.needAlphaTesting()) {
  48893. defines.push("#define ALPHATEST");
  48894. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48895. attribs.push(BABYLON.VertexBuffer.UVKind);
  48896. defines.push("#define UV1");
  48897. }
  48898. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48899. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48900. defines.push("#define UV2");
  48901. }
  48902. }
  48903. // Bones
  48904. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48907. if (mesh.numBoneInfluencers > 4) {
  48908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48910. }
  48911. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48912. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48913. }
  48914. else {
  48915. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48916. }
  48917. // Instances
  48918. if (useInstances) {
  48919. defines.push("#define INSTANCES");
  48920. attribs.push("world0");
  48921. attribs.push("world1");
  48922. attribs.push("world2");
  48923. attribs.push("world3");
  48924. }
  48925. // Get correct effect
  48926. var join = defines.join("\n");
  48927. if (this._cachedDefines !== join) {
  48928. this._cachedDefines = join;
  48929. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48930. }
  48931. return this._effect.isReady();
  48932. };
  48933. return OutlineRenderer;
  48934. }());
  48935. BABYLON.OutlineRenderer = OutlineRenderer;
  48936. })(BABYLON || (BABYLON = {}));
  48937. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48938. var BABYLON;
  48939. (function (BABYLON) {
  48940. var MeshAssetTask = (function () {
  48941. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48942. this.name = name;
  48943. this.meshesNames = meshesNames;
  48944. this.rootUrl = rootUrl;
  48945. this.sceneFilename = sceneFilename;
  48946. this.isCompleted = false;
  48947. }
  48948. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48949. var _this = this;
  48950. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48951. _this.loadedMeshes = meshes;
  48952. _this.loadedParticleSystems = particleSystems;
  48953. _this.loadedSkeletons = skeletons;
  48954. _this.isCompleted = true;
  48955. if (_this.onSuccess) {
  48956. _this.onSuccess(_this);
  48957. }
  48958. onSuccess();
  48959. }, null, function () {
  48960. if (_this.onError) {
  48961. _this.onError(_this);
  48962. }
  48963. onError();
  48964. });
  48965. };
  48966. return MeshAssetTask;
  48967. }());
  48968. BABYLON.MeshAssetTask = MeshAssetTask;
  48969. var TextFileAssetTask = (function () {
  48970. function TextFileAssetTask(name, url) {
  48971. this.name = name;
  48972. this.url = url;
  48973. this.isCompleted = false;
  48974. }
  48975. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48976. var _this = this;
  48977. BABYLON.Tools.LoadFile(this.url, function (data) {
  48978. _this.text = data;
  48979. _this.isCompleted = true;
  48980. if (_this.onSuccess) {
  48981. _this.onSuccess(_this);
  48982. }
  48983. onSuccess();
  48984. }, null, scene.database, false, function () {
  48985. if (_this.onError) {
  48986. _this.onError(_this);
  48987. }
  48988. onError();
  48989. });
  48990. };
  48991. return TextFileAssetTask;
  48992. }());
  48993. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48994. var BinaryFileAssetTask = (function () {
  48995. function BinaryFileAssetTask(name, url) {
  48996. this.name = name;
  48997. this.url = url;
  48998. this.isCompleted = false;
  48999. }
  49000. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49001. var _this = this;
  49002. BABYLON.Tools.LoadFile(this.url, function (data) {
  49003. _this.data = data;
  49004. _this.isCompleted = true;
  49005. if (_this.onSuccess) {
  49006. _this.onSuccess(_this);
  49007. }
  49008. onSuccess();
  49009. }, null, scene.database, true, function () {
  49010. if (_this.onError) {
  49011. _this.onError(_this);
  49012. }
  49013. onError();
  49014. });
  49015. };
  49016. return BinaryFileAssetTask;
  49017. }());
  49018. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  49019. var ImageAssetTask = (function () {
  49020. function ImageAssetTask(name, url) {
  49021. this.name = name;
  49022. this.url = url;
  49023. this.isCompleted = false;
  49024. }
  49025. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49026. var _this = this;
  49027. var img = new Image();
  49028. BABYLON.Tools.SetCorsBehavior(this.url, img);
  49029. img.onload = function () {
  49030. _this.image = img;
  49031. _this.isCompleted = true;
  49032. if (_this.onSuccess) {
  49033. _this.onSuccess(_this);
  49034. }
  49035. onSuccess();
  49036. };
  49037. img.onerror = function () {
  49038. if (_this.onError) {
  49039. _this.onError(_this);
  49040. }
  49041. onError();
  49042. };
  49043. img.src = this.url;
  49044. };
  49045. return ImageAssetTask;
  49046. }());
  49047. BABYLON.ImageAssetTask = ImageAssetTask;
  49048. var TextureAssetTask = (function () {
  49049. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  49050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49051. this.name = name;
  49052. this.url = url;
  49053. this.noMipmap = noMipmap;
  49054. this.invertY = invertY;
  49055. this.samplingMode = samplingMode;
  49056. this.isCompleted = false;
  49057. }
  49058. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49059. var _this = this;
  49060. var onload = function () {
  49061. _this.isCompleted = true;
  49062. if (_this.onSuccess) {
  49063. _this.onSuccess(_this);
  49064. }
  49065. onSuccess();
  49066. };
  49067. var onerror = function () {
  49068. if (_this.onError) {
  49069. _this.onError(_this);
  49070. }
  49071. onError();
  49072. };
  49073. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  49074. };
  49075. return TextureAssetTask;
  49076. }());
  49077. BABYLON.TextureAssetTask = TextureAssetTask;
  49078. var CubeTextureAssetTask = (function () {
  49079. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  49080. this.name = name;
  49081. this.url = url;
  49082. this.extensions = extensions;
  49083. this.noMipmap = noMipmap;
  49084. this.files = files;
  49085. this.isCompleted = false;
  49086. }
  49087. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49088. var _this = this;
  49089. var onload = function () {
  49090. _this.isCompleted = true;
  49091. if (_this.onSuccess) {
  49092. _this.onSuccess(_this);
  49093. }
  49094. onSuccess();
  49095. };
  49096. var onerror = function () {
  49097. if (_this.onError) {
  49098. _this.onError(_this);
  49099. }
  49100. onError();
  49101. };
  49102. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  49103. };
  49104. return CubeTextureAssetTask;
  49105. }());
  49106. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  49107. var HDRCubeTextureAssetTask = (function () {
  49108. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49109. if (noMipmap === void 0) { noMipmap = false; }
  49110. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49111. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49112. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49113. this.name = name;
  49114. this.url = url;
  49115. this.size = size;
  49116. this.noMipmap = noMipmap;
  49117. this.generateHarmonics = generateHarmonics;
  49118. this.useInGammaSpace = useInGammaSpace;
  49119. this.usePMREMGenerator = usePMREMGenerator;
  49120. this.isCompleted = false;
  49121. }
  49122. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49123. var _this = this;
  49124. var onload = function () {
  49125. _this.isCompleted = true;
  49126. if (_this.onSuccess) {
  49127. _this.onSuccess(_this);
  49128. }
  49129. onSuccess();
  49130. };
  49131. var onerror = function () {
  49132. if (_this.onError) {
  49133. _this.onError(_this);
  49134. }
  49135. onError();
  49136. };
  49137. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  49138. };
  49139. return HDRCubeTextureAssetTask;
  49140. }());
  49141. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  49142. var AssetsManager = (function () {
  49143. function AssetsManager(scene) {
  49144. this.tasks = new Array();
  49145. this.waitingTasksCount = 0;
  49146. this.useDefaultLoadingScreen = true;
  49147. this._scene = scene;
  49148. }
  49149. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  49150. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  49151. this.tasks.push(task);
  49152. return task;
  49153. };
  49154. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49155. var task = new TextFileAssetTask(taskName, url);
  49156. this.tasks.push(task);
  49157. return task;
  49158. };
  49159. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49160. var task = new BinaryFileAssetTask(taskName, url);
  49161. this.tasks.push(task);
  49162. return task;
  49163. };
  49164. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49165. var task = new ImageAssetTask(taskName, url);
  49166. this.tasks.push(task);
  49167. return task;
  49168. };
  49169. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49171. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49172. this.tasks.push(task);
  49173. return task;
  49174. };
  49175. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49176. this.waitingTasksCount--;
  49177. if (this.waitingTasksCount === 0) {
  49178. if (this.onFinish) {
  49179. this.onFinish(this.tasks);
  49180. }
  49181. this._scene.getEngine().hideLoadingUI();
  49182. }
  49183. };
  49184. AssetsManager.prototype._runTask = function (task) {
  49185. var _this = this;
  49186. task.run(this._scene, function () {
  49187. if (_this.onTaskSuccess) {
  49188. _this.onTaskSuccess(task);
  49189. }
  49190. _this._decreaseWaitingTasksCount();
  49191. }, function () {
  49192. if (_this.onTaskError) {
  49193. _this.onTaskError(task);
  49194. }
  49195. _this._decreaseWaitingTasksCount();
  49196. });
  49197. };
  49198. AssetsManager.prototype.reset = function () {
  49199. this.tasks = new Array();
  49200. return this;
  49201. };
  49202. AssetsManager.prototype.load = function () {
  49203. this.waitingTasksCount = this.tasks.length;
  49204. if (this.waitingTasksCount === 0) {
  49205. if (this.onFinish) {
  49206. this.onFinish(this.tasks);
  49207. }
  49208. return this;
  49209. }
  49210. if (this.useDefaultLoadingScreen) {
  49211. this._scene.getEngine().displayLoadingUI();
  49212. }
  49213. for (var index = 0; index < this.tasks.length; index++) {
  49214. var task = this.tasks[index];
  49215. this._runTask(task);
  49216. }
  49217. return this;
  49218. };
  49219. return AssetsManager;
  49220. }());
  49221. BABYLON.AssetsManager = AssetsManager;
  49222. })(BABYLON || (BABYLON = {}));
  49223. //# sourceMappingURL=babylon.assetsManager.js.map
  49224. var BABYLON;
  49225. (function (BABYLON) {
  49226. var VRCameraMetrics = (function () {
  49227. function VRCameraMetrics() {
  49228. this.compensateDistortion = true;
  49229. }
  49230. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49231. get: function () {
  49232. return this.hResolution / (2 * this.vResolution);
  49233. },
  49234. enumerable: true,
  49235. configurable: true
  49236. });
  49237. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49238. get: function () {
  49239. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49240. },
  49241. enumerable: true,
  49242. configurable: true
  49243. });
  49244. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49245. get: function () {
  49246. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49247. var h = (4 * meters) / this.hScreenSize;
  49248. return BABYLON.Matrix.Translation(h, 0, 0);
  49249. },
  49250. enumerable: true,
  49251. configurable: true
  49252. });
  49253. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49254. get: function () {
  49255. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49256. var h = (4 * meters) / this.hScreenSize;
  49257. return BABYLON.Matrix.Translation(-h, 0, 0);
  49258. },
  49259. enumerable: true,
  49260. configurable: true
  49261. });
  49262. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49263. get: function () {
  49264. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49270. get: function () {
  49271. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49272. },
  49273. enumerable: true,
  49274. configurable: true
  49275. });
  49276. VRCameraMetrics.GetDefault = function () {
  49277. var result = new VRCameraMetrics();
  49278. result.hResolution = 1280;
  49279. result.vResolution = 800;
  49280. result.hScreenSize = 0.149759993;
  49281. result.vScreenSize = 0.0935999975;
  49282. result.vScreenCenter = 0.0467999987;
  49283. result.eyeToScreenDistance = 0.0410000011;
  49284. result.lensSeparationDistance = 0.0635000020;
  49285. result.interpupillaryDistance = 0.0640000030;
  49286. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49287. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49288. result.postProcessScaleFactor = 1.714605507808412;
  49289. result.lensCenterOffset = 0.151976421;
  49290. return result;
  49291. };
  49292. return VRCameraMetrics;
  49293. }());
  49294. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49295. })(BABYLON || (BABYLON = {}));
  49296. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  49297. var BABYLON;
  49298. (function (BABYLON) {
  49299. var WebVRFreeCamera = (function (_super) {
  49300. __extends(WebVRFreeCamera, _super);
  49301. function WebVRFreeCamera(name, position, scene, webVROptions) {
  49302. if (webVROptions === void 0) { webVROptions = {}; }
  49303. var _this = _super.call(this, name, position, scene) || this;
  49304. _this.webVROptions = webVROptions;
  49305. _this._vrDevice = null;
  49306. _this.rawPose = null;
  49307. _this._vrEnabled = false;
  49308. _this._attached = false;
  49309. _this._positionOffset = BABYLON.Vector3.Zero();
  49310. _this._descendants = [];
  49311. _this.devicePosition = BABYLON.Vector3.Zero();
  49312. _this.deviceScaleFactor = 1;
  49313. _this.controllers = [];
  49314. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  49315. //legacy support - the compensation boolean was removed.
  49316. if (arguments.length === 5) {
  49317. _this.webVROptions = arguments[4];
  49318. }
  49319. // default webVR options
  49320. if (_this.webVROptions.trackPosition == undefined) {
  49321. _this.webVROptions.trackPosition = true;
  49322. }
  49323. if (_this.webVROptions.controllerMeshes == undefined) {
  49324. _this.webVROptions.controllerMeshes = true;
  49325. }
  49326. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  49327. _this.webVROptions.defaultLightningOnControllers = true;
  49328. }
  49329. _this.rotationQuaternion = new BABYLON.Quaternion();
  49330. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49331. if (_this.webVROptions && _this.webVROptions.positionScale) {
  49332. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  49333. }
  49334. //enable VR
  49335. _this.getEngine().initWebVR();
  49336. if (!_this.getEngine().vrDisplaysPromise) {
  49337. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  49338. }
  49339. else {
  49340. _this._frameData = new VRFrameData();
  49341. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  49342. if (devices.length > 0) {
  49343. _this._vrEnabled = true;
  49344. if (_this.webVROptions.displayName) {
  49345. var found = devices.some(function (device) {
  49346. if (device.displayName === _this.webVROptions.displayName) {
  49347. _this._vrDevice = device;
  49348. return true;
  49349. }
  49350. else {
  49351. return false;
  49352. }
  49353. });
  49354. if (!found) {
  49355. _this._vrDevice = devices[0];
  49356. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  49357. }
  49358. }
  49359. else {
  49360. //choose the first one
  49361. _this._vrDevice = devices[0];
  49362. }
  49363. //reset the rig parameters.
  49364. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  49365. if (_this._attached) {
  49366. _this.getEngine().enableVR(_this._vrDevice);
  49367. }
  49368. }
  49369. else {
  49370. BABYLON.Tools.Error("No WebVR devices found!");
  49371. }
  49372. });
  49373. }
  49374. // try to attach the controllers, if found.
  49375. _this.initControllers();
  49376. /**
  49377. * The idea behind the following lines:
  49378. * objects that have the camera as parent should actually have the rig cameras as a parent.
  49379. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  49380. * the second will not show it correctly.
  49381. *
  49382. * To solve this - each object that has the camera as parent will be added to a protected array.
  49383. * When the rig camera renders, it will take this array and set all of those to be its children.
  49384. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  49385. * Amazing!
  49386. */
  49387. scene.onBeforeCameraRenderObservable.add(function (camera) {
  49388. if (camera.parent === _this && _this.rigParenting) {
  49389. _this._descendants = _this.getDescendants(true, function (n) {
  49390. // don't take the cameras or the controllers!
  49391. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  49392. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  49393. return !isController && !isRigCamera;
  49394. });
  49395. _this._descendants.forEach(function (node) {
  49396. node.parent = camera;
  49397. });
  49398. }
  49399. });
  49400. scene.onAfterCameraRenderObservable.add(function (camera) {
  49401. if (camera.parent === _this && _this.rigParenting) {
  49402. _this._descendants.forEach(function (node) {
  49403. node.parent = _this;
  49404. });
  49405. }
  49406. });
  49407. return _this;
  49408. }
  49409. WebVRFreeCamera.prototype._checkInputs = function () {
  49410. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  49411. var currentPose = this._frameData.pose;
  49412. this.updateFromDevice(currentPose);
  49413. }
  49414. _super.prototype._checkInputs.call(this);
  49415. };
  49416. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  49417. if (poseData && poseData.orientation) {
  49418. this.rawPose = poseData;
  49419. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49420. if (this.getScene().useRightHandedSystem) {
  49421. this.deviceRotationQuaternion.z *= -1;
  49422. this.deviceRotationQuaternion.w *= -1;
  49423. }
  49424. if (this.webVROptions.trackPosition && this.rawPose.position) {
  49425. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  49426. if (this.getScene().useRightHandedSystem) {
  49427. this.devicePosition.z *= -1;
  49428. }
  49429. }
  49430. }
  49431. };
  49432. /**
  49433. * WebVR's attach control will start broadcasting frames to the device.
  49434. * Note that in certain browsers (chrome for example) this function must be called
  49435. * within a user-interaction callback. Example:
  49436. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  49437. *
  49438. * @param {HTMLElement} element
  49439. * @param {boolean} [noPreventDefault]
  49440. *
  49441. * @memberOf WebVRFreeCamera
  49442. */
  49443. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49444. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49445. this._attached = true;
  49446. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49447. if (this._vrEnabled) {
  49448. this.getEngine().enableVR(this._vrDevice);
  49449. }
  49450. };
  49451. WebVRFreeCamera.prototype.detachControl = function (element) {
  49452. _super.prototype.detachControl.call(this, element);
  49453. this._vrEnabled = false;
  49454. this._attached = false;
  49455. this.getEngine().disableVR();
  49456. };
  49457. WebVRFreeCamera.prototype.getClassName = function () {
  49458. return "WebVRFreeCamera";
  49459. };
  49460. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  49461. //uses the vrDisplay's "resetPose()".
  49462. //pitch and roll won't be affected.
  49463. this._vrDevice.resetPose();
  49464. };
  49465. WebVRFreeCamera.prototype._updateRigCameras = function () {
  49466. var camLeft = this._rigCameras[0];
  49467. var camRight = this._rigCameras[1];
  49468. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49469. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49470. camLeft.position.copyFrom(this.devicePosition);
  49471. camRight.position.copyFrom(this.devicePosition);
  49472. };
  49473. /**
  49474. * This function is called by the two RIG cameras.
  49475. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  49476. */
  49477. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  49478. var _this = this;
  49479. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  49480. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  49481. if (!this.getScene().useRightHandedSystem) {
  49482. [2, 6, 8, 9, 14].forEach(function (num) {
  49483. _this._webvrViewMatrix.m[num] *= -1;
  49484. });
  49485. }
  49486. var parentCamera = this._cameraRigParams["parentCamera"];
  49487. // should the view matrix be updated with scale and position offset?
  49488. if (parentCamera.deviceScaleFactor !== 1) {
  49489. this._webvrViewMatrix.invert();
  49490. // scale the position, if set
  49491. if (parentCamera.deviceScaleFactor) {
  49492. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  49493. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  49494. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  49495. }
  49496. this._webvrViewMatrix.invert();
  49497. }
  49498. // update the camera rotation matrix
  49499. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  49500. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49501. // Computing target and final matrix
  49502. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49503. return this._webvrViewMatrix;
  49504. };
  49505. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  49506. var _this = this;
  49507. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  49508. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  49509. //babylon compatible matrix
  49510. if (!this.getScene().useRightHandedSystem) {
  49511. [8, 9, 10, 11].forEach(function (num) {
  49512. _this._projectionMatrix.m[num] *= -1;
  49513. });
  49514. }
  49515. return this._projectionMatrix;
  49516. };
  49517. WebVRFreeCamera.prototype.initControllers = function () {
  49518. var _this = this;
  49519. this.controllers = [];
  49520. new BABYLON.Gamepads(function (gp) {
  49521. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  49522. var webVrController = gp;
  49523. if (_this.webVROptions.controllerMeshes) {
  49524. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  49525. if (_this.webVROptions.defaultLightningOnControllers) {
  49526. if (!_this._lightOnControllers) {
  49527. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  49528. }
  49529. loadedMesh.getChildren().forEach(function (mesh) {
  49530. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  49531. });
  49532. }
  49533. });
  49534. }
  49535. webVrController.attachToPoseControlledCamera(_this);
  49536. // since this is async - sanity check. Is the controller already stored?
  49537. if (_this.controllers.indexOf(webVrController) === -1) {
  49538. //add to the controllers array
  49539. _this.controllers.push(webVrController);
  49540. //did we find enough controllers? Great! let the developer know.
  49541. if (_this.onControllersAttached && _this.controllers.length === 2) {
  49542. _this.onControllersAttached(_this.controllers);
  49543. }
  49544. }
  49545. }
  49546. });
  49547. };
  49548. return WebVRFreeCamera;
  49549. }(BABYLON.FreeCamera));
  49550. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49551. })(BABYLON || (BABYLON = {}));
  49552. //# sourceMappingURL=babylon.webVRCamera.js.map
  49553. var BABYLON;
  49554. (function (BABYLON) {
  49555. // Standard optimizations
  49556. var SceneOptimization = (function () {
  49557. function SceneOptimization(priority) {
  49558. if (priority === void 0) { priority = 0; }
  49559. this.priority = priority;
  49560. this.apply = function (scene) {
  49561. return true; // Return true if everything that can be done was applied
  49562. };
  49563. }
  49564. return SceneOptimization;
  49565. }());
  49566. BABYLON.SceneOptimization = SceneOptimization;
  49567. var TextureOptimization = (function (_super) {
  49568. __extends(TextureOptimization, _super);
  49569. function TextureOptimization(priority, maximumSize) {
  49570. if (priority === void 0) { priority = 0; }
  49571. if (maximumSize === void 0) { maximumSize = 1024; }
  49572. var _this = _super.call(this, priority) || this;
  49573. _this.priority = priority;
  49574. _this.maximumSize = maximumSize;
  49575. _this.apply = function (scene) {
  49576. var allDone = true;
  49577. for (var index = 0; index < scene.textures.length; index++) {
  49578. var texture = scene.textures[index];
  49579. if (!texture.canRescale) {
  49580. continue;
  49581. }
  49582. var currentSize = texture.getSize();
  49583. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49584. if (maxDimension > _this.maximumSize) {
  49585. texture.scale(0.5);
  49586. allDone = false;
  49587. }
  49588. }
  49589. return allDone;
  49590. };
  49591. return _this;
  49592. }
  49593. return TextureOptimization;
  49594. }(SceneOptimization));
  49595. BABYLON.TextureOptimization = TextureOptimization;
  49596. var HardwareScalingOptimization = (function (_super) {
  49597. __extends(HardwareScalingOptimization, _super);
  49598. function HardwareScalingOptimization(priority, maximumScale) {
  49599. if (priority === void 0) { priority = 0; }
  49600. if (maximumScale === void 0) { maximumScale = 2; }
  49601. var _this = _super.call(this, priority) || this;
  49602. _this.priority = priority;
  49603. _this.maximumScale = maximumScale;
  49604. _this._currentScale = 1;
  49605. _this.apply = function (scene) {
  49606. _this._currentScale++;
  49607. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49608. return _this._currentScale >= _this.maximumScale;
  49609. };
  49610. return _this;
  49611. }
  49612. return HardwareScalingOptimization;
  49613. }(SceneOptimization));
  49614. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49615. var ShadowsOptimization = (function (_super) {
  49616. __extends(ShadowsOptimization, _super);
  49617. function ShadowsOptimization() {
  49618. var _this = _super !== null && _super.apply(this, arguments) || this;
  49619. _this.apply = function (scene) {
  49620. scene.shadowsEnabled = false;
  49621. return true;
  49622. };
  49623. return _this;
  49624. }
  49625. return ShadowsOptimization;
  49626. }(SceneOptimization));
  49627. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49628. var PostProcessesOptimization = (function (_super) {
  49629. __extends(PostProcessesOptimization, _super);
  49630. function PostProcessesOptimization() {
  49631. var _this = _super !== null && _super.apply(this, arguments) || this;
  49632. _this.apply = function (scene) {
  49633. scene.postProcessesEnabled = false;
  49634. return true;
  49635. };
  49636. return _this;
  49637. }
  49638. return PostProcessesOptimization;
  49639. }(SceneOptimization));
  49640. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49641. var LensFlaresOptimization = (function (_super) {
  49642. __extends(LensFlaresOptimization, _super);
  49643. function LensFlaresOptimization() {
  49644. var _this = _super !== null && _super.apply(this, arguments) || this;
  49645. _this.apply = function (scene) {
  49646. scene.lensFlaresEnabled = false;
  49647. return true;
  49648. };
  49649. return _this;
  49650. }
  49651. return LensFlaresOptimization;
  49652. }(SceneOptimization));
  49653. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49654. var ParticlesOptimization = (function (_super) {
  49655. __extends(ParticlesOptimization, _super);
  49656. function ParticlesOptimization() {
  49657. var _this = _super !== null && _super.apply(this, arguments) || this;
  49658. _this.apply = function (scene) {
  49659. scene.particlesEnabled = false;
  49660. return true;
  49661. };
  49662. return _this;
  49663. }
  49664. return ParticlesOptimization;
  49665. }(SceneOptimization));
  49666. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49667. var RenderTargetsOptimization = (function (_super) {
  49668. __extends(RenderTargetsOptimization, _super);
  49669. function RenderTargetsOptimization() {
  49670. var _this = _super !== null && _super.apply(this, arguments) || this;
  49671. _this.apply = function (scene) {
  49672. scene.renderTargetsEnabled = false;
  49673. return true;
  49674. };
  49675. return _this;
  49676. }
  49677. return RenderTargetsOptimization;
  49678. }(SceneOptimization));
  49679. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49680. var MergeMeshesOptimization = (function (_super) {
  49681. __extends(MergeMeshesOptimization, _super);
  49682. function MergeMeshesOptimization() {
  49683. var _this = _super !== null && _super.apply(this, arguments) || this;
  49684. _this._canBeMerged = function (abstractMesh) {
  49685. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49686. return false;
  49687. }
  49688. var mesh = abstractMesh;
  49689. if (!mesh.isVisible || !mesh.isEnabled()) {
  49690. return false;
  49691. }
  49692. if (mesh.instances.length > 0) {
  49693. return false;
  49694. }
  49695. if (mesh.skeleton || mesh.hasLODLevels) {
  49696. return false;
  49697. }
  49698. if (mesh.parent) {
  49699. return false;
  49700. }
  49701. return true;
  49702. };
  49703. _this.apply = function (scene, updateSelectionTree) {
  49704. var globalPool = scene.meshes.slice(0);
  49705. var globalLength = globalPool.length;
  49706. for (var index = 0; index < globalLength; index++) {
  49707. var currentPool = new Array();
  49708. var current = globalPool[index];
  49709. // Checks
  49710. if (!_this._canBeMerged(current)) {
  49711. continue;
  49712. }
  49713. currentPool.push(current);
  49714. // Find compatible meshes
  49715. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49716. var otherMesh = globalPool[subIndex];
  49717. if (!_this._canBeMerged(otherMesh)) {
  49718. continue;
  49719. }
  49720. if (otherMesh.material !== current.material) {
  49721. continue;
  49722. }
  49723. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49724. continue;
  49725. }
  49726. currentPool.push(otherMesh);
  49727. globalLength--;
  49728. globalPool.splice(subIndex, 1);
  49729. subIndex--;
  49730. }
  49731. if (currentPool.length < 2) {
  49732. continue;
  49733. }
  49734. // Merge meshes
  49735. BABYLON.Mesh.MergeMeshes(currentPool);
  49736. }
  49737. if (updateSelectionTree != undefined) {
  49738. if (updateSelectionTree) {
  49739. scene.createOrUpdateSelectionOctree();
  49740. }
  49741. }
  49742. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49743. scene.createOrUpdateSelectionOctree();
  49744. }
  49745. return true;
  49746. };
  49747. return _this;
  49748. }
  49749. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49750. get: function () {
  49751. return MergeMeshesOptimization._UpdateSelectionTree;
  49752. },
  49753. set: function (value) {
  49754. MergeMeshesOptimization._UpdateSelectionTree = value;
  49755. },
  49756. enumerable: true,
  49757. configurable: true
  49758. });
  49759. return MergeMeshesOptimization;
  49760. }(SceneOptimization));
  49761. MergeMeshesOptimization._UpdateSelectionTree = false;
  49762. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49763. // Options
  49764. var SceneOptimizerOptions = (function () {
  49765. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49766. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49767. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49768. this.targetFrameRate = targetFrameRate;
  49769. this.trackerDuration = trackerDuration;
  49770. this.optimizations = new Array();
  49771. }
  49772. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49773. var result = new SceneOptimizerOptions(targetFrameRate);
  49774. var priority = 0;
  49775. result.optimizations.push(new MergeMeshesOptimization(priority));
  49776. result.optimizations.push(new ShadowsOptimization(priority));
  49777. result.optimizations.push(new LensFlaresOptimization(priority));
  49778. // Next priority
  49779. priority++;
  49780. result.optimizations.push(new PostProcessesOptimization(priority));
  49781. result.optimizations.push(new ParticlesOptimization(priority));
  49782. // Next priority
  49783. priority++;
  49784. result.optimizations.push(new TextureOptimization(priority, 1024));
  49785. return result;
  49786. };
  49787. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49788. var result = new SceneOptimizerOptions(targetFrameRate);
  49789. var priority = 0;
  49790. result.optimizations.push(new MergeMeshesOptimization(priority));
  49791. result.optimizations.push(new ShadowsOptimization(priority));
  49792. result.optimizations.push(new LensFlaresOptimization(priority));
  49793. // Next priority
  49794. priority++;
  49795. result.optimizations.push(new PostProcessesOptimization(priority));
  49796. result.optimizations.push(new ParticlesOptimization(priority));
  49797. // Next priority
  49798. priority++;
  49799. result.optimizations.push(new TextureOptimization(priority, 512));
  49800. // Next priority
  49801. priority++;
  49802. result.optimizations.push(new RenderTargetsOptimization(priority));
  49803. // Next priority
  49804. priority++;
  49805. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49806. return result;
  49807. };
  49808. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49809. var result = new SceneOptimizerOptions(targetFrameRate);
  49810. var priority = 0;
  49811. result.optimizations.push(new MergeMeshesOptimization(priority));
  49812. result.optimizations.push(new ShadowsOptimization(priority));
  49813. result.optimizations.push(new LensFlaresOptimization(priority));
  49814. // Next priority
  49815. priority++;
  49816. result.optimizations.push(new PostProcessesOptimization(priority));
  49817. result.optimizations.push(new ParticlesOptimization(priority));
  49818. // Next priority
  49819. priority++;
  49820. result.optimizations.push(new TextureOptimization(priority, 256));
  49821. // Next priority
  49822. priority++;
  49823. result.optimizations.push(new RenderTargetsOptimization(priority));
  49824. // Next priority
  49825. priority++;
  49826. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49827. return result;
  49828. };
  49829. return SceneOptimizerOptions;
  49830. }());
  49831. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49832. // Scene optimizer tool
  49833. var SceneOptimizer = (function () {
  49834. function SceneOptimizer() {
  49835. }
  49836. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49837. // TODO: add an epsilon
  49838. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49839. if (onSuccess) {
  49840. onSuccess();
  49841. }
  49842. return;
  49843. }
  49844. // Apply current level of optimizations
  49845. var allDone = true;
  49846. var noOptimizationApplied = true;
  49847. for (var index = 0; index < options.optimizations.length; index++) {
  49848. var optimization = options.optimizations[index];
  49849. if (optimization.priority === currentPriorityLevel) {
  49850. noOptimizationApplied = false;
  49851. allDone = allDone && optimization.apply(scene);
  49852. }
  49853. }
  49854. // If no optimization was applied, this is a failure :(
  49855. if (noOptimizationApplied) {
  49856. if (onFailure) {
  49857. onFailure();
  49858. }
  49859. return;
  49860. }
  49861. // If all optimizations were done, move to next level
  49862. if (allDone) {
  49863. currentPriorityLevel++;
  49864. }
  49865. // Let's the system running for a specific amount of time before checking FPS
  49866. scene.executeWhenReady(function () {
  49867. setTimeout(function () {
  49868. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49869. }, options.trackerDuration);
  49870. });
  49871. };
  49872. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49873. if (!options) {
  49874. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49875. }
  49876. // Let's the system running for a specific amount of time before checking FPS
  49877. scene.executeWhenReady(function () {
  49878. setTimeout(function () {
  49879. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49880. }, options.trackerDuration);
  49881. });
  49882. };
  49883. return SceneOptimizer;
  49884. }());
  49885. BABYLON.SceneOptimizer = SceneOptimizer;
  49886. })(BABYLON || (BABYLON = {}));
  49887. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49888. var BABYLON;
  49889. (function (BABYLON) {
  49890. var Internals;
  49891. (function (Internals) {
  49892. var MeshLODLevel = (function () {
  49893. function MeshLODLevel(distance, mesh) {
  49894. this.distance = distance;
  49895. this.mesh = mesh;
  49896. }
  49897. return MeshLODLevel;
  49898. }());
  49899. Internals.MeshLODLevel = MeshLODLevel;
  49900. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49901. })(BABYLON || (BABYLON = {}));
  49902. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49903. var BABYLON;
  49904. (function (BABYLON) {
  49905. var RawTexture = (function (_super) {
  49906. __extends(RawTexture, _super);
  49907. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49908. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49909. if (invertY === void 0) { invertY = false; }
  49910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49911. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49912. _this.format = format;
  49913. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49914. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49915. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49916. return _this;
  49917. }
  49918. RawTexture.prototype.update = function (data) {
  49919. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49920. };
  49921. // Statics
  49922. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49924. if (invertY === void 0) { invertY = false; }
  49925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49927. };
  49928. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49929. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49930. if (invertY === void 0) { invertY = false; }
  49931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49932. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49933. };
  49934. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49935. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49936. if (invertY === void 0) { invertY = false; }
  49937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49938. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49939. };
  49940. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49942. if (invertY === void 0) { invertY = false; }
  49943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49944. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49945. };
  49946. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49947. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49948. if (invertY === void 0) { invertY = false; }
  49949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49950. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49951. };
  49952. return RawTexture;
  49953. }(BABYLON.Texture));
  49954. BABYLON.RawTexture = RawTexture;
  49955. })(BABYLON || (BABYLON = {}));
  49956. //# sourceMappingURL=babylon.rawTexture.js.map
  49957. /// <reference path="..\Math\babylon.math.ts" />
  49958. var BABYLON;
  49959. (function (BABYLON) {
  49960. var IndexedVector2 = (function (_super) {
  49961. __extends(IndexedVector2, _super);
  49962. function IndexedVector2(original, index) {
  49963. var _this = _super.call(this, original.x, original.y) || this;
  49964. _this.index = index;
  49965. return _this;
  49966. }
  49967. return IndexedVector2;
  49968. }(BABYLON.Vector2));
  49969. var PolygonPoints = (function () {
  49970. function PolygonPoints() {
  49971. this.elements = new Array();
  49972. }
  49973. PolygonPoints.prototype.add = function (originalPoints) {
  49974. var _this = this;
  49975. var result = new Array();
  49976. originalPoints.forEach(function (point) {
  49977. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49978. var newPoint = new IndexedVector2(point, _this.elements.length);
  49979. result.push(newPoint);
  49980. _this.elements.push(newPoint);
  49981. }
  49982. });
  49983. return result;
  49984. };
  49985. PolygonPoints.prototype.computeBounds = function () {
  49986. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49987. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49988. this.elements.forEach(function (point) {
  49989. // x
  49990. if (point.x < lmin.x) {
  49991. lmin.x = point.x;
  49992. }
  49993. else if (point.x > lmax.x) {
  49994. lmax.x = point.x;
  49995. }
  49996. // y
  49997. if (point.y < lmin.y) {
  49998. lmin.y = point.y;
  49999. }
  50000. else if (point.y > lmax.y) {
  50001. lmax.y = point.y;
  50002. }
  50003. });
  50004. return {
  50005. min: lmin,
  50006. max: lmax,
  50007. width: lmax.x - lmin.x,
  50008. height: lmax.y - lmin.y
  50009. };
  50010. };
  50011. return PolygonPoints;
  50012. }());
  50013. var Polygon = (function () {
  50014. function Polygon() {
  50015. }
  50016. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  50017. return [
  50018. new BABYLON.Vector2(xmin, ymin),
  50019. new BABYLON.Vector2(xmax, ymin),
  50020. new BABYLON.Vector2(xmax, ymax),
  50021. new BABYLON.Vector2(xmin, ymax)
  50022. ];
  50023. };
  50024. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  50025. if (cx === void 0) { cx = 0; }
  50026. if (cy === void 0) { cy = 0; }
  50027. if (numberOfSides === void 0) { numberOfSides = 32; }
  50028. var result = new Array();
  50029. var angle = 0;
  50030. var increment = (Math.PI * 2) / numberOfSides;
  50031. for (var i = 0; i < numberOfSides; i++) {
  50032. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  50033. angle -= increment;
  50034. }
  50035. return result;
  50036. };
  50037. Polygon.Parse = function (input) {
  50038. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  50039. var i, result = [];
  50040. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  50041. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  50042. }
  50043. return result;
  50044. };
  50045. Polygon.StartingAt = function (x, y) {
  50046. return BABYLON.Path2.StartingAt(x, y);
  50047. };
  50048. return Polygon;
  50049. }());
  50050. BABYLON.Polygon = Polygon;
  50051. var PolygonMeshBuilder = (function () {
  50052. function PolygonMeshBuilder(name, contours, scene) {
  50053. this._points = new PolygonPoints();
  50054. this._outlinepoints = new PolygonPoints();
  50055. this._holes = [];
  50056. this._epoints = new Array();
  50057. this._eholes = new Array();
  50058. this._name = name;
  50059. this._scene = scene;
  50060. var points;
  50061. if (contours instanceof BABYLON.Path2) {
  50062. points = contours.getPoints();
  50063. }
  50064. else {
  50065. points = contours;
  50066. }
  50067. this._addToepoint(points);
  50068. this._points.add(points);
  50069. this._outlinepoints.add(points);
  50070. }
  50071. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  50072. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  50073. var p = points_1[_i];
  50074. this._epoints.push(p.x, p.y);
  50075. }
  50076. };
  50077. PolygonMeshBuilder.prototype.addHole = function (hole) {
  50078. this._points.add(hole);
  50079. var holepoints = new PolygonPoints();
  50080. holepoints.add(hole);
  50081. this._holes.push(holepoints);
  50082. this._eholes.push(this._epoints.length / 2);
  50083. this._addToepoint(hole);
  50084. return this;
  50085. };
  50086. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  50087. var _this = this;
  50088. if (updatable === void 0) { updatable = false; }
  50089. var result = new BABYLON.Mesh(this._name, this._scene);
  50090. var normals = [];
  50091. var positions = [];
  50092. var uvs = [];
  50093. var bounds = this._points.computeBounds();
  50094. this._points.elements.forEach(function (p) {
  50095. normals.push(0, 1.0, 0);
  50096. positions.push(p.x, 0, p.y);
  50097. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  50098. });
  50099. var indices = [];
  50100. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  50101. for (var i = 0; i < res.length; i++) {
  50102. indices.push(res[i]);
  50103. }
  50104. if (depth > 0) {
  50105. var positionscount = (positions.length / 3); //get the current pointcount
  50106. this._points.elements.forEach(function (p) {
  50107. normals.push(0, -1.0, 0);
  50108. positions.push(p.x, -depth, p.y);
  50109. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  50110. });
  50111. var totalCount = indices.length;
  50112. for (var i = 0; i < totalCount; i += 3) {
  50113. var i0 = indices[i + 0];
  50114. var i1 = indices[i + 1];
  50115. var i2 = indices[i + 2];
  50116. indices.push(i2 + positionscount);
  50117. indices.push(i1 + positionscount);
  50118. indices.push(i0 + positionscount);
  50119. }
  50120. //Add the sides
  50121. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  50122. this._holes.forEach(function (hole) {
  50123. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  50124. });
  50125. }
  50126. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  50127. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  50128. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  50129. result.setIndices(indices);
  50130. return result;
  50131. };
  50132. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  50133. var StartIndex = positions.length / 3;
  50134. var ulength = 0;
  50135. for (var i = 0; i < points.elements.length; i++) {
  50136. var p = points.elements[i];
  50137. var p1;
  50138. if ((i + 1) > points.elements.length - 1) {
  50139. p1 = points.elements[0];
  50140. }
  50141. else {
  50142. p1 = points.elements[i + 1];
  50143. }
  50144. positions.push(p.x, 0, p.y);
  50145. positions.push(p.x, -depth, p.y);
  50146. positions.push(p1.x, 0, p1.y);
  50147. positions.push(p1.x, -depth, p1.y);
  50148. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  50149. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  50150. var v3 = v2.subtract(v1);
  50151. var v4 = new BABYLON.Vector3(0, 1, 0);
  50152. var vn = BABYLON.Vector3.Cross(v3, v4);
  50153. vn = vn.normalize();
  50154. uvs.push(ulength / bounds.width, 0);
  50155. uvs.push(ulength / bounds.width, 1);
  50156. ulength += v3.length();
  50157. uvs.push((ulength / bounds.width), 0);
  50158. uvs.push((ulength / bounds.width), 1);
  50159. if (!flip) {
  50160. normals.push(-vn.x, -vn.y, -vn.z);
  50161. normals.push(-vn.x, -vn.y, -vn.z);
  50162. normals.push(-vn.x, -vn.y, -vn.z);
  50163. normals.push(-vn.x, -vn.y, -vn.z);
  50164. indices.push(StartIndex);
  50165. indices.push(StartIndex + 1);
  50166. indices.push(StartIndex + 2);
  50167. indices.push(StartIndex + 1);
  50168. indices.push(StartIndex + 3);
  50169. indices.push(StartIndex + 2);
  50170. }
  50171. else {
  50172. normals.push(vn.x, vn.y, vn.z);
  50173. normals.push(vn.x, vn.y, vn.z);
  50174. normals.push(vn.x, vn.y, vn.z);
  50175. normals.push(vn.x, vn.y, vn.z);
  50176. indices.push(StartIndex);
  50177. indices.push(StartIndex + 2);
  50178. indices.push(StartIndex + 1);
  50179. indices.push(StartIndex + 1);
  50180. indices.push(StartIndex + 2);
  50181. indices.push(StartIndex + 3);
  50182. }
  50183. StartIndex += 4;
  50184. }
  50185. ;
  50186. };
  50187. return PolygonMeshBuilder;
  50188. }());
  50189. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50190. })(BABYLON || (BABYLON = {}));
  50191. //# sourceMappingURL=babylon.polygonMesh.js.map
  50192. var BABYLON;
  50193. (function (BABYLON) {
  50194. var Octree = (function () {
  50195. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50196. if (maxDepth === void 0) { maxDepth = 2; }
  50197. this.maxDepth = maxDepth;
  50198. this.dynamicContent = new Array();
  50199. this._maxBlockCapacity = maxBlockCapacity || 64;
  50200. this._selectionContent = new BABYLON.SmartArray(1024);
  50201. this._creationFunc = creationFunc;
  50202. }
  50203. // Methods
  50204. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50205. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50206. };
  50207. Octree.prototype.addMesh = function (entry) {
  50208. for (var index = 0; index < this.blocks.length; index++) {
  50209. var block = this.blocks[index];
  50210. block.addEntry(entry);
  50211. }
  50212. };
  50213. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50214. this._selectionContent.reset();
  50215. for (var index = 0; index < this.blocks.length; index++) {
  50216. var block = this.blocks[index];
  50217. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50218. }
  50219. if (allowDuplicate) {
  50220. this._selectionContent.concat(this.dynamicContent);
  50221. }
  50222. else {
  50223. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50224. }
  50225. return this._selectionContent;
  50226. };
  50227. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50228. this._selectionContent.reset();
  50229. for (var index = 0; index < this.blocks.length; index++) {
  50230. var block = this.blocks[index];
  50231. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50232. }
  50233. if (allowDuplicate) {
  50234. this._selectionContent.concat(this.dynamicContent);
  50235. }
  50236. else {
  50237. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50238. }
  50239. return this._selectionContent;
  50240. };
  50241. Octree.prototype.intersectsRay = function (ray) {
  50242. this._selectionContent.reset();
  50243. for (var index = 0; index < this.blocks.length; index++) {
  50244. var block = this.blocks[index];
  50245. block.intersectsRay(ray, this._selectionContent);
  50246. }
  50247. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50248. return this._selectionContent;
  50249. };
  50250. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50251. target.blocks = new Array();
  50252. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50253. // Segmenting space
  50254. for (var x = 0; x < 2; x++) {
  50255. for (var y = 0; y < 2; y++) {
  50256. for (var z = 0; z < 2; z++) {
  50257. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50258. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50259. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50260. block.addEntries(entries);
  50261. target.blocks.push(block);
  50262. }
  50263. }
  50264. }
  50265. };
  50266. return Octree;
  50267. }());
  50268. Octree.CreationFuncForMeshes = function (entry, block) {
  50269. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50270. block.entries.push(entry);
  50271. }
  50272. };
  50273. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50274. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50275. block.entries.push(entry);
  50276. }
  50277. };
  50278. BABYLON.Octree = Octree;
  50279. })(BABYLON || (BABYLON = {}));
  50280. //# sourceMappingURL=babylon.octree.js.map
  50281. var BABYLON;
  50282. (function (BABYLON) {
  50283. var OctreeBlock = (function () {
  50284. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50285. this.entries = new Array();
  50286. this._boundingVectors = new Array();
  50287. this._capacity = capacity;
  50288. this._depth = depth;
  50289. this._maxDepth = maxDepth;
  50290. this._creationFunc = creationFunc;
  50291. this._minPoint = minPoint;
  50292. this._maxPoint = maxPoint;
  50293. this._boundingVectors.push(minPoint.clone());
  50294. this._boundingVectors.push(maxPoint.clone());
  50295. this._boundingVectors.push(minPoint.clone());
  50296. this._boundingVectors[2].x = maxPoint.x;
  50297. this._boundingVectors.push(minPoint.clone());
  50298. this._boundingVectors[3].y = maxPoint.y;
  50299. this._boundingVectors.push(minPoint.clone());
  50300. this._boundingVectors[4].z = maxPoint.z;
  50301. this._boundingVectors.push(maxPoint.clone());
  50302. this._boundingVectors[5].z = minPoint.z;
  50303. this._boundingVectors.push(maxPoint.clone());
  50304. this._boundingVectors[6].x = minPoint.x;
  50305. this._boundingVectors.push(maxPoint.clone());
  50306. this._boundingVectors[7].y = minPoint.y;
  50307. }
  50308. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50309. // Property
  50310. get: function () {
  50311. return this._capacity;
  50312. },
  50313. enumerable: true,
  50314. configurable: true
  50315. });
  50316. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50317. get: function () {
  50318. return this._minPoint;
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50324. get: function () {
  50325. return this._maxPoint;
  50326. },
  50327. enumerable: true,
  50328. configurable: true
  50329. });
  50330. // Methods
  50331. OctreeBlock.prototype.addEntry = function (entry) {
  50332. if (this.blocks) {
  50333. for (var index = 0; index < this.blocks.length; index++) {
  50334. var block = this.blocks[index];
  50335. block.addEntry(entry);
  50336. }
  50337. return;
  50338. }
  50339. this._creationFunc(entry, this);
  50340. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50341. this.createInnerBlocks();
  50342. }
  50343. };
  50344. OctreeBlock.prototype.addEntries = function (entries) {
  50345. for (var index = 0; index < entries.length; index++) {
  50346. var mesh = entries[index];
  50347. this.addEntry(mesh);
  50348. }
  50349. };
  50350. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50351. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50352. if (this.blocks) {
  50353. for (var index = 0; index < this.blocks.length; index++) {
  50354. var block = this.blocks[index];
  50355. block.select(frustumPlanes, selection, allowDuplicate);
  50356. }
  50357. return;
  50358. }
  50359. if (allowDuplicate) {
  50360. selection.concat(this.entries);
  50361. }
  50362. else {
  50363. selection.concatWithNoDuplicate(this.entries);
  50364. }
  50365. }
  50366. };
  50367. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50368. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50369. if (this.blocks) {
  50370. for (var index = 0; index < this.blocks.length; index++) {
  50371. var block = this.blocks[index];
  50372. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50373. }
  50374. return;
  50375. }
  50376. if (allowDuplicate) {
  50377. selection.concat(this.entries);
  50378. }
  50379. else {
  50380. selection.concatWithNoDuplicate(this.entries);
  50381. }
  50382. }
  50383. };
  50384. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50385. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50386. if (this.blocks) {
  50387. for (var index = 0; index < this.blocks.length; index++) {
  50388. var block = this.blocks[index];
  50389. block.intersectsRay(ray, selection);
  50390. }
  50391. return;
  50392. }
  50393. selection.concatWithNoDuplicate(this.entries);
  50394. }
  50395. };
  50396. OctreeBlock.prototype.createInnerBlocks = function () {
  50397. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50398. };
  50399. return OctreeBlock;
  50400. }());
  50401. BABYLON.OctreeBlock = OctreeBlock;
  50402. })(BABYLON || (BABYLON = {}));
  50403. //# sourceMappingURL=babylon.octreeBlock.js.map
  50404. var BABYLON;
  50405. (function (BABYLON) {
  50406. var BlurPostProcess = (function (_super) {
  50407. __extends(BlurPostProcess, _super);
  50408. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50410. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  50411. _this.direction = direction;
  50412. _this.blurWidth = blurWidth;
  50413. _this.onApplyObservable.add(function (effect) {
  50414. effect.setFloat2("screenSize", _this.width, _this.height);
  50415. effect.setVector2("direction", _this.direction);
  50416. effect.setFloat("blurWidth", _this.blurWidth);
  50417. });
  50418. return _this;
  50419. }
  50420. return BlurPostProcess;
  50421. }(BABYLON.PostProcess));
  50422. BABYLON.BlurPostProcess = BlurPostProcess;
  50423. })(BABYLON || (BABYLON = {}));
  50424. //# sourceMappingURL=babylon.blurPostProcess.js.map
  50425. var BABYLON;
  50426. (function (BABYLON) {
  50427. var RefractionPostProcess = (function (_super) {
  50428. __extends(RefractionPostProcess, _super);
  50429. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50430. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50431. _this.color = color;
  50432. _this.depth = depth;
  50433. _this.colorLevel = colorLevel;
  50434. _this.onActivateObservable.add(function (cam) {
  50435. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50436. });
  50437. _this.onApplyObservable.add(function (effect) {
  50438. effect.setColor3("baseColor", _this.color);
  50439. effect.setFloat("depth", _this.depth);
  50440. effect.setFloat("colorLevel", _this.colorLevel);
  50441. effect.setTexture("refractionSampler", _this._refRexture);
  50442. });
  50443. return _this;
  50444. }
  50445. // Methods
  50446. RefractionPostProcess.prototype.dispose = function (camera) {
  50447. if (this._refRexture) {
  50448. this._refRexture.dispose();
  50449. }
  50450. _super.prototype.dispose.call(this, camera);
  50451. };
  50452. return RefractionPostProcess;
  50453. }(BABYLON.PostProcess));
  50454. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50455. })(BABYLON || (BABYLON = {}));
  50456. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50457. var BABYLON;
  50458. (function (BABYLON) {
  50459. var BlackAndWhitePostProcess = (function (_super) {
  50460. __extends(BlackAndWhitePostProcess, _super);
  50461. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50462. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50463. }
  50464. return BlackAndWhitePostProcess;
  50465. }(BABYLON.PostProcess));
  50466. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50467. })(BABYLON || (BABYLON = {}));
  50468. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50469. var BABYLON;
  50470. (function (BABYLON) {
  50471. var ConvolutionPostProcess = (function (_super) {
  50472. __extends(ConvolutionPostProcess, _super);
  50473. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50474. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50475. _this.kernel = kernel;
  50476. _this.onApply = function (effect) {
  50477. effect.setFloat2("screenSize", _this.width, _this.height);
  50478. effect.setArray("kernel", _this.kernel);
  50479. };
  50480. return _this;
  50481. }
  50482. return ConvolutionPostProcess;
  50483. }(BABYLON.PostProcess));
  50484. // Statics
  50485. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50486. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50487. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50488. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50489. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50490. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50491. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50492. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50493. })(BABYLON || (BABYLON = {}));
  50494. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50495. var BABYLON;
  50496. (function (BABYLON) {
  50497. var FilterPostProcess = (function (_super) {
  50498. __extends(FilterPostProcess, _super);
  50499. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50500. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50501. _this.kernelMatrix = kernelMatrix;
  50502. _this.onApply = function (effect) {
  50503. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50504. };
  50505. return _this;
  50506. }
  50507. return FilterPostProcess;
  50508. }(BABYLON.PostProcess));
  50509. BABYLON.FilterPostProcess = FilterPostProcess;
  50510. })(BABYLON || (BABYLON = {}));
  50511. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50512. var BABYLON;
  50513. (function (BABYLON) {
  50514. var FxaaPostProcess = (function (_super) {
  50515. __extends(FxaaPostProcess, _super);
  50516. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50517. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  50518. _this.onSizeChangedObservable.add(function () {
  50519. _this.texelWidth = 1.0 / _this.width;
  50520. _this.texelHeight = 1.0 / _this.height;
  50521. });
  50522. _this.onApplyObservable.add(function (effect) {
  50523. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50524. });
  50525. return _this;
  50526. }
  50527. return FxaaPostProcess;
  50528. }(BABYLON.PostProcess));
  50529. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50530. })(BABYLON || (BABYLON = {}));
  50531. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50532. var BABYLON;
  50533. (function (BABYLON) {
  50534. var StereoscopicInterlacePostProcess = (function (_super) {
  50535. __extends(StereoscopicInterlacePostProcess, _super);
  50536. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50537. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  50538. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50539. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50540. _this.onSizeChangedObservable.add(function () {
  50541. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50542. });
  50543. _this.onApplyObservable.add(function (effect) {
  50544. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50545. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50546. });
  50547. return _this;
  50548. }
  50549. return StereoscopicInterlacePostProcess;
  50550. }(BABYLON.PostProcess));
  50551. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50552. })(BABYLON || (BABYLON = {}));
  50553. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  50554. var BABYLON;
  50555. (function (BABYLON) {
  50556. var LensFlare = (function () {
  50557. function LensFlare(size, position, color, imgUrl, system) {
  50558. this.size = size;
  50559. this.position = position;
  50560. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  50561. this.dispose = function () {
  50562. if (this.texture) {
  50563. this.texture.dispose();
  50564. }
  50565. // Remove from scene
  50566. var index = this._system.lensFlares.indexOf(this);
  50567. this._system.lensFlares.splice(index, 1);
  50568. };
  50569. this.color = color || new BABYLON.Color3(1, 1, 1);
  50570. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50571. this._system = system;
  50572. system.lensFlares.push(this);
  50573. }
  50574. return LensFlare;
  50575. }());
  50576. BABYLON.LensFlare = LensFlare;
  50577. })(BABYLON || (BABYLON = {}));
  50578. //# sourceMappingURL=babylon.lensFlare.js.map
  50579. var BABYLON;
  50580. (function (BABYLON) {
  50581. var LensFlareSystem = (function () {
  50582. function LensFlareSystem(name, emitter, scene) {
  50583. this.name = name;
  50584. this.lensFlares = new Array();
  50585. this.borderLimit = 300;
  50586. this.viewportBorder = 0;
  50587. this.layerMask = 0x0FFFFFFF;
  50588. this._vertexBuffers = {};
  50589. this._isEnabled = true;
  50590. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50591. this._emitter = emitter;
  50592. this.id = name;
  50593. scene.lensFlareSystems.push(this);
  50594. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50595. var engine = scene.getEngine();
  50596. // VBO
  50597. var vertices = [];
  50598. vertices.push(1, 1);
  50599. vertices.push(-1, 1);
  50600. vertices.push(-1, -1);
  50601. vertices.push(1, -1);
  50602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50603. // Indices
  50604. var indices = [];
  50605. indices.push(0);
  50606. indices.push(1);
  50607. indices.push(2);
  50608. indices.push(0);
  50609. indices.push(2);
  50610. indices.push(3);
  50611. this._indexBuffer = engine.createIndexBuffer(indices);
  50612. // Effects
  50613. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50614. }
  50615. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50616. get: function () {
  50617. return this._isEnabled;
  50618. },
  50619. set: function (value) {
  50620. this._isEnabled = value;
  50621. },
  50622. enumerable: true,
  50623. configurable: true
  50624. });
  50625. LensFlareSystem.prototype.getScene = function () {
  50626. return this._scene;
  50627. };
  50628. LensFlareSystem.prototype.getEmitter = function () {
  50629. return this._emitter;
  50630. };
  50631. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50632. this._emitter = newEmitter;
  50633. };
  50634. LensFlareSystem.prototype.getEmitterPosition = function () {
  50635. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50636. };
  50637. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50638. var position = this.getEmitterPosition();
  50639. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50640. this._positionX = position.x;
  50641. this._positionY = position.y;
  50642. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50643. if (this.viewportBorder > 0) {
  50644. globalViewport.x -= this.viewportBorder;
  50645. globalViewport.y -= this.viewportBorder;
  50646. globalViewport.width += this.viewportBorder * 2;
  50647. globalViewport.height += this.viewportBorder * 2;
  50648. position.x += this.viewportBorder;
  50649. position.y += this.viewportBorder;
  50650. this._positionX += this.viewportBorder;
  50651. this._positionY += this.viewportBorder;
  50652. }
  50653. if (position.z > 0) {
  50654. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50655. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50656. return true;
  50657. }
  50658. return true;
  50659. }
  50660. return false;
  50661. };
  50662. LensFlareSystem.prototype._isVisible = function () {
  50663. if (!this._isEnabled) {
  50664. return false;
  50665. }
  50666. var emitterPosition = this.getEmitterPosition();
  50667. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  50668. var distance = direction.length();
  50669. direction.normalize();
  50670. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  50671. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50672. return !pickInfo.hit || pickInfo.distance > distance;
  50673. };
  50674. LensFlareSystem.prototype.render = function () {
  50675. if (!this._effect.isReady())
  50676. return false;
  50677. var engine = this._scene.getEngine();
  50678. var viewport = this._scene.activeCamera.viewport;
  50679. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50680. // Position
  50681. if (!this.computeEffectivePosition(globalViewport)) {
  50682. return false;
  50683. }
  50684. // Visibility
  50685. if (!this._isVisible()) {
  50686. return false;
  50687. }
  50688. // Intensity
  50689. var awayX;
  50690. var awayY;
  50691. if (this._positionX < this.borderLimit + globalViewport.x) {
  50692. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50693. }
  50694. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50695. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50696. }
  50697. else {
  50698. awayX = 0;
  50699. }
  50700. if (this._positionY < this.borderLimit + globalViewport.y) {
  50701. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50702. }
  50703. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50704. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50705. }
  50706. else {
  50707. awayY = 0;
  50708. }
  50709. var away = (awayX > awayY) ? awayX : awayY;
  50710. away -= this.viewportBorder;
  50711. if (away > this.borderLimit) {
  50712. away = this.borderLimit;
  50713. }
  50714. var intensity = 1.0 - (away / this.borderLimit);
  50715. if (intensity < 0) {
  50716. return false;
  50717. }
  50718. if (intensity > 1.0) {
  50719. intensity = 1.0;
  50720. }
  50721. if (this.viewportBorder > 0) {
  50722. globalViewport.x += this.viewportBorder;
  50723. globalViewport.y += this.viewportBorder;
  50724. globalViewport.width -= this.viewportBorder * 2;
  50725. globalViewport.height -= this.viewportBorder * 2;
  50726. this._positionX -= this.viewportBorder;
  50727. this._positionY -= this.viewportBorder;
  50728. }
  50729. // Position
  50730. var centerX = globalViewport.x + globalViewport.width / 2;
  50731. var centerY = globalViewport.y + globalViewport.height / 2;
  50732. var distX = centerX - this._positionX;
  50733. var distY = centerY - this._positionY;
  50734. // Effects
  50735. engine.enableEffect(this._effect);
  50736. engine.setState(false);
  50737. engine.setDepthBuffer(false);
  50738. // VBOs
  50739. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50740. // Flares
  50741. for (var index = 0; index < this.lensFlares.length; index++) {
  50742. var flare = this.lensFlares[index];
  50743. engine.setAlphaMode(flare.alphaMode);
  50744. var x = centerX - (distX * flare.position);
  50745. var y = centerY - (distY * flare.position);
  50746. var cw = flare.size;
  50747. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50748. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  50749. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  50750. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50751. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50752. // Texture
  50753. this._effect.setTexture("textureSampler", flare.texture);
  50754. // Color
  50755. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50756. // Draw order
  50757. engine.draw(true, 0, 6);
  50758. }
  50759. engine.setDepthBuffer(true);
  50760. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50761. return true;
  50762. };
  50763. LensFlareSystem.prototype.dispose = function () {
  50764. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50765. if (vertexBuffer) {
  50766. vertexBuffer.dispose();
  50767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50768. }
  50769. if (this._indexBuffer) {
  50770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50771. this._indexBuffer = null;
  50772. }
  50773. while (this.lensFlares.length) {
  50774. this.lensFlares[0].dispose();
  50775. }
  50776. // Remove from scene
  50777. var index = this._scene.lensFlareSystems.indexOf(this);
  50778. this._scene.lensFlareSystems.splice(index, 1);
  50779. };
  50780. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50781. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50782. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50783. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50784. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50785. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50786. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50787. var parsedFlare = parsedLensFlareSystem.flares[index];
  50788. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50789. }
  50790. return lensFlareSystem;
  50791. };
  50792. LensFlareSystem.prototype.serialize = function () {
  50793. var serializationObject = {};
  50794. serializationObject.id = this.id;
  50795. serializationObject.name = this.name;
  50796. serializationObject.emitterId = this.getEmitter().id;
  50797. serializationObject.borderLimit = this.borderLimit;
  50798. serializationObject.flares = [];
  50799. for (var index = 0; index < this.lensFlares.length; index++) {
  50800. var flare = this.lensFlares[index];
  50801. serializationObject.flares.push({
  50802. size: flare.size,
  50803. position: flare.position,
  50804. color: flare.color.asArray(),
  50805. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50806. });
  50807. }
  50808. return serializationObject;
  50809. };
  50810. return LensFlareSystem;
  50811. }());
  50812. BABYLON.LensFlareSystem = LensFlareSystem;
  50813. })(BABYLON || (BABYLON = {}));
  50814. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  50815. /// <reference path="babylon.freeCamera.ts" />
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. // We're mainly based on the logic defined into the FreeCamera code
  50819. var DeviceOrientationCamera = (function (_super) {
  50820. __extends(DeviceOrientationCamera, _super);
  50821. function DeviceOrientationCamera(name, position, scene) {
  50822. var _this = _super.call(this, name, position, scene) || this;
  50823. _this._quaternionCache = new BABYLON.Quaternion();
  50824. _this.inputs.addDeviceOrientation();
  50825. return _this;
  50826. }
  50827. DeviceOrientationCamera.prototype.getClassName = function () {
  50828. return "DeviceOrientationCamera";
  50829. };
  50830. DeviceOrientationCamera.prototype._checkInputs = function () {
  50831. _super.prototype._checkInputs.call(this);
  50832. this._quaternionCache.copyFrom(this.rotationQuaternion);
  50833. if (this._initialQuaternion) {
  50834. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50835. }
  50836. };
  50837. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  50838. var _this = this;
  50839. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  50840. //can only work if this camera has a rotation quaternion already.
  50841. if (!this.rotationQuaternion)
  50842. return;
  50843. if (!this._initialQuaternion) {
  50844. this._initialQuaternion = new BABYLON.Quaternion();
  50845. }
  50846. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50847. ['x', 'y', 'z'].forEach(function (axisName) {
  50848. if (!axis[axisName]) {
  50849. _this._initialQuaternion[axisName] = 0;
  50850. }
  50851. else {
  50852. _this._initialQuaternion[axisName] *= -1;
  50853. }
  50854. });
  50855. this._initialQuaternion.normalize();
  50856. //force rotation update
  50857. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50858. };
  50859. return DeviceOrientationCamera;
  50860. }(BABYLON.FreeCamera));
  50861. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50862. })(BABYLON || (BABYLON = {}));
  50863. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  50864. var BABYLON;
  50865. (function (BABYLON) {
  50866. var VRDeviceOrientationFreeCamera = (function (_super) {
  50867. __extends(VRDeviceOrientationFreeCamera, _super);
  50868. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50869. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50870. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50871. var _this = _super.call(this, name, position, scene) || this;
  50872. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50873. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50874. return _this;
  50875. }
  50876. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50877. return "VRDeviceOrientationFreeCamera";
  50878. };
  50879. return VRDeviceOrientationFreeCamera;
  50880. }(BABYLON.DeviceOrientationCamera));
  50881. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50882. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50883. __extends(VRDeviceOrientationGamepadCamera, _super);
  50884. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50885. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50886. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50887. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50888. _this.inputs.addGamepad();
  50889. return _this;
  50890. }
  50891. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50892. return "VRDeviceOrientationGamepadCamera";
  50893. };
  50894. return VRDeviceOrientationGamepadCamera;
  50895. }(VRDeviceOrientationFreeCamera));
  50896. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50897. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50898. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50899. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50900. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50901. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50902. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50903. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50904. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50905. _this.inputs.addVRDeviceOrientation();
  50906. return _this;
  50907. }
  50908. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50909. return "VRDeviceOrientationArcRotateCamera";
  50910. };
  50911. return VRDeviceOrientationArcRotateCamera;
  50912. }(BABYLON.ArcRotateCamera));
  50913. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50914. })(BABYLON || (BABYLON = {}));
  50915. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50916. /// <reference path="babylon.touchCamera.ts" />
  50917. var BABYLON;
  50918. (function (BABYLON) {
  50919. // We're mainly based on the logic defined into the FreeCamera code
  50920. var UniversalCamera = (function (_super) {
  50921. __extends(UniversalCamera, _super);
  50922. //-- end properties for backward compatibility for inputs
  50923. function UniversalCamera(name, position, scene) {
  50924. var _this = _super.call(this, name, position, scene) || this;
  50925. _this.inputs.addGamepad();
  50926. return _this;
  50927. }
  50928. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50929. //-- Begin properties for backward compatibility for inputs
  50930. get: function () {
  50931. var gamepad = this.inputs.attached["gamepad"];
  50932. if (gamepad)
  50933. return gamepad.gamepadAngularSensibility;
  50934. },
  50935. set: function (value) {
  50936. var gamepad = this.inputs.attached["gamepad"];
  50937. if (gamepad)
  50938. gamepad.gamepadAngularSensibility = value;
  50939. },
  50940. enumerable: true,
  50941. configurable: true
  50942. });
  50943. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50944. get: function () {
  50945. var gamepad = this.inputs.attached["gamepad"];
  50946. if (gamepad)
  50947. return gamepad.gamepadMoveSensibility;
  50948. },
  50949. set: function (value) {
  50950. var gamepad = this.inputs.attached["gamepad"];
  50951. if (gamepad)
  50952. gamepad.gamepadMoveSensibility = value;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. UniversalCamera.prototype.getClassName = function () {
  50958. return "UniversalCamera";
  50959. };
  50960. return UniversalCamera;
  50961. }(BABYLON.TouchCamera));
  50962. BABYLON.UniversalCamera = UniversalCamera;
  50963. })(BABYLON || (BABYLON = {}));
  50964. //# sourceMappingURL=babylon.universalCamera.js.map
  50965. var BABYLON;
  50966. (function (BABYLON) {
  50967. var Gamepads = (function () {
  50968. function Gamepads(ongamedpadconnected) {
  50969. var _this = this;
  50970. this.babylonGamepads = [];
  50971. this.oneGamepadConnected = false;
  50972. this.isMonitoring = false;
  50973. this.gamepadEventSupported = 'GamepadEvent' in window;
  50974. this.gamepadSupport = (navigator.getGamepads ||
  50975. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50976. this._callbackGamepadConnected = ongamedpadconnected;
  50977. if (this.gamepadSupport) {
  50978. //first add already-connected gamepads
  50979. this._updateGamepadObjects();
  50980. if (this.babylonGamepads.length) {
  50981. this._startMonitoringGamepads();
  50982. }
  50983. // Checking if the gamepad connected event is supported (like in Firefox)
  50984. if (this.gamepadEventSupported) {
  50985. this._onGamepadConnectedEvent = function (evt) {
  50986. _this._onGamepadConnected(evt.gamepad);
  50987. };
  50988. this._onGamepadDisonnectedEvent = function (evt) {
  50989. _this._onGamepadDisconnected(evt);
  50990. };
  50991. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50992. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50993. }
  50994. else {
  50995. this._startMonitoringGamepads();
  50996. }
  50997. }
  50998. }
  50999. Gamepads.prototype.dispose = function () {
  51000. if (Gamepads.gamepadDOMInfo) {
  51001. document.body.removeChild(Gamepads.gamepadDOMInfo);
  51002. }
  51003. if (this._onGamepadConnectedEvent) {
  51004. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51005. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  51006. this._onGamepadConnectedEvent = null;
  51007. this._onGamepadDisonnectedEvent = null;
  51008. }
  51009. };
  51010. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  51011. var newGamepad = this._addNewGamepad(gamepad);
  51012. if (this._callbackGamepadConnected)
  51013. this._callbackGamepadConnected(newGamepad);
  51014. this._startMonitoringGamepads();
  51015. };
  51016. Gamepads.prototype._addNewGamepad = function (gamepad) {
  51017. if (!this.oneGamepadConnected) {
  51018. this.oneGamepadConnected = true;
  51019. if (Gamepads.gamepadDOMInfo) {
  51020. document.body.removeChild(Gamepads.gamepadDOMInfo);
  51021. Gamepads.gamepadDOMInfo = null;
  51022. }
  51023. }
  51024. var newGamepad;
  51025. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51026. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51027. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51028. }
  51029. else if (gamepad.pose) {
  51030. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51031. }
  51032. else {
  51033. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  51034. }
  51035. this.babylonGamepads.push(newGamepad);
  51036. return newGamepad;
  51037. };
  51038. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  51039. // Remove the gamepad from the list of gamepads to monitor.
  51040. for (var i in this.babylonGamepads) {
  51041. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  51042. this.babylonGamepads.splice(+i, 1);
  51043. break;
  51044. }
  51045. }
  51046. // If no gamepads are left, stop the polling loop.
  51047. if (this.babylonGamepads.length == 0) {
  51048. this._stopMonitoringGamepads();
  51049. }
  51050. };
  51051. Gamepads.prototype._startMonitoringGamepads = function () {
  51052. if (!this.isMonitoring) {
  51053. this.isMonitoring = true;
  51054. this._checkGamepadsStatus();
  51055. }
  51056. };
  51057. Gamepads.prototype._stopMonitoringGamepads = function () {
  51058. this.isMonitoring = false;
  51059. };
  51060. Gamepads.prototype._checkGamepadsStatus = function () {
  51061. var _this = this;
  51062. // updating gamepad objects
  51063. this._updateGamepadObjects();
  51064. for (var i in this.babylonGamepads) {
  51065. this.babylonGamepads[i].update();
  51066. }
  51067. if (this.isMonitoring) {
  51068. if (window.requestAnimationFrame) {
  51069. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51070. }
  51071. else if (window.mozRequestAnimationFrame) {
  51072. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51073. }
  51074. else if (window.webkitRequestAnimationFrame) {
  51075. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51076. }
  51077. }
  51078. };
  51079. // This function is called only on Chrome, which does not yet support
  51080. // connection/disconnection events, but requires you to monitor
  51081. // an array for changes.
  51082. Gamepads.prototype._updateGamepadObjects = function () {
  51083. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51084. for (var i = 0; i < gamepads.length; i++) {
  51085. if (gamepads[i]) {
  51086. if (!(gamepads[i].index in this.babylonGamepads)) {
  51087. var newGamepad = this._addNewGamepad(gamepads[i]);
  51088. if (this._callbackGamepadConnected) {
  51089. this._callbackGamepadConnected(newGamepad);
  51090. }
  51091. }
  51092. else {
  51093. this.babylonGamepads[i].browserGamepad = gamepads[i];
  51094. }
  51095. }
  51096. }
  51097. };
  51098. return Gamepads;
  51099. }());
  51100. BABYLON.Gamepads = Gamepads;
  51101. var StickValues = (function () {
  51102. function StickValues(x, y) {
  51103. this.x = x;
  51104. this.y = y;
  51105. }
  51106. return StickValues;
  51107. }());
  51108. BABYLON.StickValues = StickValues;
  51109. var Gamepad = (function () {
  51110. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51111. if (leftStickX === void 0) { leftStickX = 0; }
  51112. if (leftStickY === void 0) { leftStickY = 1; }
  51113. if (rightStickX === void 0) { rightStickX = 2; }
  51114. if (rightStickY === void 0) { rightStickY = 3; }
  51115. this.id = id;
  51116. this.index = index;
  51117. this.browserGamepad = browserGamepad;
  51118. this.type = Gamepad.GAMEPAD;
  51119. this._leftStickAxisX = leftStickX;
  51120. this._leftStickAxisY = leftStickY;
  51121. this._rightStickAxisX = rightStickX;
  51122. this._rightStickAxisY = rightStickY;
  51123. if (this.browserGamepad.axes.length >= 2) {
  51124. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51125. }
  51126. if (this.browserGamepad.axes.length >= 4) {
  51127. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51128. }
  51129. }
  51130. Gamepad.prototype.onleftstickchanged = function (callback) {
  51131. this._onleftstickchanged = callback;
  51132. };
  51133. Gamepad.prototype.onrightstickchanged = function (callback) {
  51134. this._onrightstickchanged = callback;
  51135. };
  51136. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51137. get: function () {
  51138. return this._leftStick;
  51139. },
  51140. set: function (newValues) {
  51141. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51142. this._onleftstickchanged(newValues);
  51143. }
  51144. this._leftStick = newValues;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51150. get: function () {
  51151. return this._rightStick;
  51152. },
  51153. set: function (newValues) {
  51154. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51155. this._onrightstickchanged(newValues);
  51156. }
  51157. this._rightStick = newValues;
  51158. },
  51159. enumerable: true,
  51160. configurable: true
  51161. });
  51162. Gamepad.prototype.update = function () {
  51163. if (this._leftStick) {
  51164. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51165. }
  51166. if (this._rightStick) {
  51167. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51168. }
  51169. };
  51170. return Gamepad;
  51171. }());
  51172. Gamepad.GAMEPAD = 0;
  51173. Gamepad.GENERIC = 1;
  51174. Gamepad.XBOX = 2;
  51175. Gamepad.POSE_ENABLED = 3;
  51176. BABYLON.Gamepad = Gamepad;
  51177. var GenericPad = (function (_super) {
  51178. __extends(GenericPad, _super);
  51179. function GenericPad(id, index, gamepad) {
  51180. var _this = _super.call(this, id, index, gamepad) || this;
  51181. _this.id = id;
  51182. _this.index = index;
  51183. _this.gamepad = gamepad;
  51184. _this.type = Gamepad.GENERIC;
  51185. _this._buttons = new Array(gamepad.buttons.length);
  51186. return _this;
  51187. }
  51188. GenericPad.prototype.onbuttondown = function (callback) {
  51189. this._onbuttondown = callback;
  51190. };
  51191. GenericPad.prototype.onbuttonup = function (callback) {
  51192. this._onbuttonup = callback;
  51193. };
  51194. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51195. if (newValue !== currentValue) {
  51196. if (this._onbuttondown && newValue === 1) {
  51197. this._onbuttondown(buttonIndex);
  51198. }
  51199. if (this._onbuttonup && newValue === 0) {
  51200. this._onbuttonup(buttonIndex);
  51201. }
  51202. }
  51203. return newValue;
  51204. };
  51205. GenericPad.prototype.update = function () {
  51206. _super.prototype.update.call(this);
  51207. for (var index = 0; index < this._buttons.length; index++) {
  51208. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51209. }
  51210. };
  51211. return GenericPad;
  51212. }(Gamepad));
  51213. BABYLON.GenericPad = GenericPad;
  51214. var Xbox360Button;
  51215. (function (Xbox360Button) {
  51216. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51217. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51218. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51219. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51220. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51221. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51222. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51223. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51224. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51225. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51226. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51227. var Xbox360Dpad;
  51228. (function (Xbox360Dpad) {
  51229. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51230. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51231. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51232. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51233. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51234. var Xbox360Pad = (function (_super) {
  51235. __extends(Xbox360Pad, _super);
  51236. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51237. if (xboxOne === void 0) { xboxOne = false; }
  51238. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51239. _this._leftTrigger = 0;
  51240. _this._rightTrigger = 0;
  51241. _this._buttonA = 0;
  51242. _this._buttonB = 0;
  51243. _this._buttonX = 0;
  51244. _this._buttonY = 0;
  51245. _this._buttonBack = 0;
  51246. _this._buttonStart = 0;
  51247. _this._buttonLB = 0;
  51248. _this._buttonRB = 0;
  51249. _this._buttonLeftStick = 0;
  51250. _this._buttonRightStick = 0;
  51251. _this._dPadUp = 0;
  51252. _this._dPadDown = 0;
  51253. _this._dPadLeft = 0;
  51254. _this._dPadRight = 0;
  51255. _this._isXboxOnePad = false;
  51256. _this.type = Gamepad.XBOX;
  51257. _this._isXboxOnePad = xboxOne;
  51258. return _this;
  51259. }
  51260. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51261. this._onlefttriggerchanged = callback;
  51262. };
  51263. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51264. this._onrighttriggerchanged = callback;
  51265. };
  51266. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51267. get: function () {
  51268. return this._leftTrigger;
  51269. },
  51270. set: function (newValue) {
  51271. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51272. this._onlefttriggerchanged(newValue);
  51273. }
  51274. this._leftTrigger = newValue;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51280. get: function () {
  51281. return this._rightTrigger;
  51282. },
  51283. set: function (newValue) {
  51284. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51285. this._onrighttriggerchanged(newValue);
  51286. }
  51287. this._rightTrigger = newValue;
  51288. },
  51289. enumerable: true,
  51290. configurable: true
  51291. });
  51292. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51293. this._onbuttondown = callback;
  51294. };
  51295. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51296. this._onbuttonup = callback;
  51297. };
  51298. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51299. this._ondpaddown = callback;
  51300. };
  51301. Xbox360Pad.prototype.ondpadup = function (callback) {
  51302. this._ondpadup = callback;
  51303. };
  51304. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51305. if (newValue !== currentValue) {
  51306. if (this._onbuttondown && newValue === 1) {
  51307. this._onbuttondown(buttonType);
  51308. }
  51309. if (this._onbuttonup && newValue === 0) {
  51310. this._onbuttonup(buttonType);
  51311. }
  51312. }
  51313. return newValue;
  51314. };
  51315. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51316. if (newValue !== currentValue) {
  51317. if (this._ondpaddown && newValue === 1) {
  51318. this._ondpaddown(buttonType);
  51319. }
  51320. if (this._ondpadup && newValue === 0) {
  51321. this._ondpadup(buttonType);
  51322. }
  51323. }
  51324. return newValue;
  51325. };
  51326. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51327. get: function () {
  51328. return this._buttonA;
  51329. },
  51330. set: function (value) {
  51331. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51337. get: function () {
  51338. return this._buttonB;
  51339. },
  51340. set: function (value) {
  51341. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51342. },
  51343. enumerable: true,
  51344. configurable: true
  51345. });
  51346. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51347. get: function () {
  51348. return this._buttonX;
  51349. },
  51350. set: function (value) {
  51351. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51357. get: function () {
  51358. return this._buttonY;
  51359. },
  51360. set: function (value) {
  51361. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51362. },
  51363. enumerable: true,
  51364. configurable: true
  51365. });
  51366. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51367. get: function () {
  51368. return this._buttonStart;
  51369. },
  51370. set: function (value) {
  51371. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51372. },
  51373. enumerable: true,
  51374. configurable: true
  51375. });
  51376. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51377. get: function () {
  51378. return this._buttonBack;
  51379. },
  51380. set: function (value) {
  51381. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51382. },
  51383. enumerable: true,
  51384. configurable: true
  51385. });
  51386. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51387. get: function () {
  51388. return this._buttonLB;
  51389. },
  51390. set: function (value) {
  51391. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51392. },
  51393. enumerable: true,
  51394. configurable: true
  51395. });
  51396. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51397. get: function () {
  51398. return this._buttonRB;
  51399. },
  51400. set: function (value) {
  51401. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51402. },
  51403. enumerable: true,
  51404. configurable: true
  51405. });
  51406. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51407. get: function () {
  51408. return this._buttonLeftStick;
  51409. },
  51410. set: function (value) {
  51411. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51412. },
  51413. enumerable: true,
  51414. configurable: true
  51415. });
  51416. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51417. get: function () {
  51418. return this._buttonRightStick;
  51419. },
  51420. set: function (value) {
  51421. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51422. },
  51423. enumerable: true,
  51424. configurable: true
  51425. });
  51426. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51427. get: function () {
  51428. return this._dPadUp;
  51429. },
  51430. set: function (value) {
  51431. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51432. },
  51433. enumerable: true,
  51434. configurable: true
  51435. });
  51436. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51437. get: function () {
  51438. return this._dPadDown;
  51439. },
  51440. set: function (value) {
  51441. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51442. },
  51443. enumerable: true,
  51444. configurable: true
  51445. });
  51446. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51447. get: function () {
  51448. return this._dPadLeft;
  51449. },
  51450. set: function (value) {
  51451. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51452. },
  51453. enumerable: true,
  51454. configurable: true
  51455. });
  51456. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51457. get: function () {
  51458. return this._dPadRight;
  51459. },
  51460. set: function (value) {
  51461. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51462. },
  51463. enumerable: true,
  51464. configurable: true
  51465. });
  51466. Xbox360Pad.prototype.update = function () {
  51467. _super.prototype.update.call(this);
  51468. if (this._isXboxOnePad) {
  51469. this.buttonA = this.browserGamepad.buttons[0].value;
  51470. this.buttonB = this.browserGamepad.buttons[1].value;
  51471. this.buttonX = this.browserGamepad.buttons[2].value;
  51472. this.buttonY = this.browserGamepad.buttons[3].value;
  51473. this.buttonLB = this.browserGamepad.buttons[4].value;
  51474. this.buttonRB = this.browserGamepad.buttons[5].value;
  51475. this.leftTrigger = this.browserGamepad.axes[2];
  51476. this.rightTrigger = this.browserGamepad.axes[5];
  51477. this.buttonBack = this.browserGamepad.buttons[9].value;
  51478. this.buttonStart = this.browserGamepad.buttons[8].value;
  51479. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51480. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51481. this.dPadUp = this.browserGamepad.buttons[11].value;
  51482. this.dPadDown = this.browserGamepad.buttons[12].value;
  51483. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51484. this.dPadRight = this.browserGamepad.buttons[14].value;
  51485. }
  51486. else {
  51487. this.buttonA = this.browserGamepad.buttons[0].value;
  51488. this.buttonB = this.browserGamepad.buttons[1].value;
  51489. this.buttonX = this.browserGamepad.buttons[2].value;
  51490. this.buttonY = this.browserGamepad.buttons[3].value;
  51491. this.buttonLB = this.browserGamepad.buttons[4].value;
  51492. this.buttonRB = this.browserGamepad.buttons[5].value;
  51493. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51494. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51495. this.buttonBack = this.browserGamepad.buttons[8].value;
  51496. this.buttonStart = this.browserGamepad.buttons[9].value;
  51497. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51498. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51499. this.dPadUp = this.browserGamepad.buttons[12].value;
  51500. this.dPadDown = this.browserGamepad.buttons[13].value;
  51501. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51502. this.dPadRight = this.browserGamepad.buttons[15].value;
  51503. }
  51504. };
  51505. return Xbox360Pad;
  51506. }(Gamepad));
  51507. BABYLON.Xbox360Pad = Xbox360Pad;
  51508. })(BABYLON || (BABYLON = {}));
  51509. //# sourceMappingURL=babylon.gamepads.js.map
  51510. var BABYLON;
  51511. (function (BABYLON) {
  51512. var PoseEnabledControllerType;
  51513. (function (PoseEnabledControllerType) {
  51514. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51515. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51516. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  51517. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51518. var PoseEnabledControllerHelper = (function () {
  51519. function PoseEnabledControllerHelper() {
  51520. }
  51521. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51522. // for now, only Oculus and Vive are supported
  51523. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51524. return new OculusTouchController(vrGamepad);
  51525. }
  51526. else {
  51527. return new ViveController(vrGamepad);
  51528. }
  51529. };
  51530. return PoseEnabledControllerHelper;
  51531. }());
  51532. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51533. var PoseEnabledController = (function (_super) {
  51534. __extends(PoseEnabledController, _super);
  51535. function PoseEnabledController(vrGamepad) {
  51536. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51537. _this.vrGamepad = vrGamepad;
  51538. _this.deviceScaleFactor = 1;
  51539. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51540. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51541. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51542. _this.position = BABYLON.Vector3.Zero();
  51543. _this.rotationQuaternion = new BABYLON.Quaternion();
  51544. _this.devicePosition = BABYLON.Vector3.Zero();
  51545. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51546. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51547. _this._calculatedRotation = new BABYLON.Quaternion();
  51548. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51549. return _this;
  51550. }
  51551. PoseEnabledController.prototype.update = function () {
  51552. _super.prototype.update.call(this);
  51553. // update this device's offset position from the attached camera, if provided
  51554. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  51555. //this.position.copyFrom(this._poseControlledCamera.position);
  51556. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  51557. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  51558. //}
  51559. var pose = this.vrGamepad.pose;
  51560. this.updateFromDevice(pose);
  51561. if (this._mesh) {
  51562. this._mesh.position.copyFrom(this._calculatedPosition);
  51563. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51564. }
  51565. };
  51566. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51567. if (poseData) {
  51568. this.rawPose = poseData;
  51569. if (poseData.position) {
  51570. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51571. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51572. this.devicePosition.z *= -1;
  51573. }
  51574. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51575. this._calculatedPosition.addInPlace(this.position);
  51576. // scale the position using the scale factor, add the device's position
  51577. /*if (this._poseControlledCamera) {
  51578. // this allows total positioning freedom - the device, the camera and the mesh can be individually controlled.
  51579. this._calculatedPosition.addInPlace(this._poseControlledCamera.position);
  51580. }*/
  51581. }
  51582. if (poseData.orientation) {
  51583. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51584. if (this._mesh) {
  51585. if (this._mesh.getScene().useRightHandedSystem) {
  51586. this.deviceRotationQuaternion.z *= -1;
  51587. this.deviceRotationQuaternion.w *= -1;
  51588. }
  51589. else {
  51590. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51591. }
  51592. }
  51593. // if the camera is set, rotate to the camera's rotation
  51594. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51595. /*if (this._poseControlledCamera) {
  51596. Matrix.ScalingToRef(1, 1, 1, Tmp.Matrix[1]);
  51597. this._calculatedRotation.toRotationMatrix(Tmp.Matrix[0]);
  51598. Matrix.TranslationToRef(this._calculatedPosition.x, this._calculatedPosition.y, this._calculatedPosition.z, Tmp.Matrix[2]);
  51599. //Matrix.Identity().multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  51600. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  51601. this._poseControlledCamera.getWorldMatrix().getTranslationToRef(Tmp.Vector3[0])
  51602. Matrix.ComposeToRef(new Vector3(this.deviceScaleFactor, this.deviceScaleFactor, this.deviceScaleFactor), this._poseControlledCamera.rotationQuaternion, Tmp.Vector3[0], Tmp.Matrix[4]);
  51603. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], Tmp.Matrix[1]);
  51604. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[4], Tmp.Matrix[2]);
  51605. Tmp.Matrix[2].decompose(Tmp.Vector3[0], this._calculatedRotation, this._calculatedPosition);
  51606. }*/
  51607. }
  51608. }
  51609. };
  51610. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51611. if (this._mesh) {
  51612. this._mesh.parent = undefined;
  51613. }
  51614. this._mesh = mesh;
  51615. if (this._poseControlledCamera) {
  51616. this._mesh.parent = this._poseControlledCamera;
  51617. }
  51618. if (!this._mesh.rotationQuaternion) {
  51619. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51620. }
  51621. };
  51622. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51623. this._poseControlledCamera = camera;
  51624. if (this._mesh) {
  51625. this._mesh.parent = this._poseControlledCamera;
  51626. }
  51627. };
  51628. PoseEnabledController.prototype.detachMesh = function () {
  51629. this._mesh = undefined;
  51630. };
  51631. return PoseEnabledController;
  51632. }(BABYLON.Gamepad));
  51633. BABYLON.PoseEnabledController = PoseEnabledController;
  51634. var WebVRController = (function (_super) {
  51635. __extends(WebVRController, _super);
  51636. function WebVRController(vrGamepad) {
  51637. var _this = _super.call(this, vrGamepad) || this;
  51638. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  51639. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51640. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51641. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51642. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51643. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51644. _this.pad = { x: 0, y: 0 };
  51645. // avoid GC, store state in a tmp object
  51646. _this._changes = {
  51647. pressChanged: false,
  51648. touchChanged: false,
  51649. valueChanged: false,
  51650. changed: false
  51651. };
  51652. _this._buttons = new Array(vrGamepad.buttons.length);
  51653. _this.hand = vrGamepad.hand;
  51654. return _this;
  51655. }
  51656. WebVRController.prototype.onButtonStateChange = function (callback) {
  51657. this._onButtonStateChange = callback;
  51658. };
  51659. WebVRController.prototype.update = function () {
  51660. _super.prototype.update.call(this);
  51661. for (var index = 0; index < this._buttons.length; index++) {
  51662. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51663. }
  51664. ;
  51665. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51666. this.pad.x = this.leftStick.x;
  51667. this.pad.y = this.leftStick.y;
  51668. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51669. }
  51670. };
  51671. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51672. if (!currentState) {
  51673. this._buttons[buttonIndex] = {
  51674. pressed: newState.pressed,
  51675. touched: newState.touched,
  51676. value: newState.value
  51677. };
  51678. return;
  51679. }
  51680. this._checkChanges(newState, currentState);
  51681. if (this._changes.changed) {
  51682. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51683. this.handleButtonChange(buttonIndex, newState, this._changes);
  51684. }
  51685. this._buttons[buttonIndex].pressed = newState.pressed;
  51686. this._buttons[buttonIndex].touched = newState.touched;
  51687. // oculus triggers are never 0, thou not touched.
  51688. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51689. };
  51690. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51691. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51692. this._changes.touchChanged = newState.touched !== currentState.touched;
  51693. this._changes.valueChanged = newState.value !== currentState.value;
  51694. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51695. return this._changes;
  51696. };
  51697. return WebVRController;
  51698. }(PoseEnabledController));
  51699. BABYLON.WebVRController = WebVRController;
  51700. var OculusTouchController = (function (_super) {
  51701. __extends(OculusTouchController, _super);
  51702. function OculusTouchController(vrGamepad) {
  51703. var _this = _super.call(this, vrGamepad) || this;
  51704. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51705. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51706. _this.controllerType = PoseEnabledControllerType.OCULUS;
  51707. return _this;
  51708. }
  51709. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51710. var _this = this;
  51711. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51712. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51713. /*
  51714. Parent Mesh name: oculus_touch_left
  51715. - body
  51716. - trigger
  51717. - thumbstick
  51718. - grip
  51719. - button_y
  51720. - button_x
  51721. - button_enter
  51722. */
  51723. _this._defaultModel = newMeshes[1];
  51724. if (meshLoaded) {
  51725. meshLoaded(_this._defaultModel);
  51726. }
  51727. _this.attachToMesh(_this._defaultModel);
  51728. });
  51729. };
  51730. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51731. // helper getters for left and right hand.
  51732. get: function () {
  51733. if (this.hand === 'right') {
  51734. return this.onMainButtonStateChangedObservable;
  51735. }
  51736. else {
  51737. throw new Error('No A button on left hand');
  51738. }
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51744. get: function () {
  51745. if (this.hand === 'right') {
  51746. return this.onSecondaryButtonStateChangedObservable;
  51747. }
  51748. else {
  51749. throw new Error('No B button on left hand');
  51750. }
  51751. },
  51752. enumerable: true,
  51753. configurable: true
  51754. });
  51755. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51756. get: function () {
  51757. if (this.hand === 'left') {
  51758. return this.onMainButtonStateChangedObservable;
  51759. }
  51760. else {
  51761. throw new Error('No X button on right hand');
  51762. }
  51763. },
  51764. enumerable: true,
  51765. configurable: true
  51766. });
  51767. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51768. get: function () {
  51769. if (this.hand === 'left') {
  51770. return this.onSecondaryButtonStateChangedObservable;
  51771. }
  51772. else {
  51773. throw new Error('No Y button on right hand');
  51774. }
  51775. },
  51776. enumerable: true,
  51777. configurable: true
  51778. });
  51779. /*
  51780. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51781. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51782. 2) secondary trigger (same)
  51783. 3) A (right) X (left), touch, pressed = value
  51784. 4) B / Y
  51785. 5) thumb rest
  51786. */
  51787. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51788. var notifyObject = state; //{ state: state, changes: changes };
  51789. switch (buttonIdx) {
  51790. case 0:
  51791. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51792. return;
  51793. case 1:
  51794. if (this._defaultModel) {
  51795. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51796. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51797. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51798. }
  51799. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51800. return;
  51801. case 2:
  51802. if (this._defaultModel) {
  51803. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  51804. }
  51805. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51806. return;
  51807. case 3:
  51808. if (this._defaultModel) {
  51809. if (notifyObject.pressed) {
  51810. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51811. }
  51812. else {
  51813. (this._defaultModel.getChildren()[1]).position.y = 0;
  51814. }
  51815. }
  51816. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51817. return;
  51818. case 4:
  51819. if (this._defaultModel) {
  51820. if (notifyObject.pressed) {
  51821. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51822. }
  51823. else {
  51824. (this._defaultModel.getChildren()[2]).position.y = 0;
  51825. }
  51826. }
  51827. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51828. return;
  51829. case 5:
  51830. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51831. return;
  51832. }
  51833. };
  51834. return OculusTouchController;
  51835. }(WebVRController));
  51836. BABYLON.OculusTouchController = OculusTouchController;
  51837. var ViveController = (function (_super) {
  51838. __extends(ViveController, _super);
  51839. function ViveController(vrGamepad) {
  51840. var _this = _super.call(this, vrGamepad) || this;
  51841. _this.controllerType = PoseEnabledControllerType.VIVE;
  51842. return _this;
  51843. }
  51844. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51845. var _this = this;
  51846. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51847. /*
  51848. Parent Mesh name: ViveWand
  51849. - body
  51850. - r_gripper
  51851. - l_gripper
  51852. - menu_button
  51853. - system_button
  51854. - trackpad
  51855. - trigger
  51856. - LED
  51857. */
  51858. _this._defaultModel = newMeshes[1];
  51859. if (meshLoaded) {
  51860. meshLoaded(_this._defaultModel);
  51861. }
  51862. _this.attachToMesh(_this._defaultModel);
  51863. });
  51864. };
  51865. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51866. get: function () {
  51867. return this.onMainButtonStateChangedObservable;
  51868. },
  51869. enumerable: true,
  51870. configurable: true
  51871. });
  51872. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51873. get: function () {
  51874. return this.onMainButtonStateChangedObservable;
  51875. },
  51876. enumerable: true,
  51877. configurable: true
  51878. });
  51879. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51880. get: function () {
  51881. return this.onSecondaryButtonStateChangedObservable;
  51882. },
  51883. enumerable: true,
  51884. configurable: true
  51885. });
  51886. /**
  51887. * Vive mapping:
  51888. * 0: touchpad
  51889. * 1: trigger
  51890. * 2: left AND right buttons
  51891. * 3: menu button
  51892. */
  51893. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51894. var notifyObject = state; //{ state: state, changes: changes };
  51895. switch (buttonIdx) {
  51896. case 0:
  51897. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51898. return;
  51899. case 1:
  51900. if (this._defaultModel) {
  51901. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51902. }
  51903. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51904. return;
  51905. case 2:
  51906. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51907. return;
  51908. case 3:
  51909. if (this._defaultModel) {
  51910. if (notifyObject.pressed) {
  51911. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51912. }
  51913. else {
  51914. (this._defaultModel.getChildren()[2]).position.y = 0;
  51915. }
  51916. }
  51917. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51918. return;
  51919. }
  51920. };
  51921. return ViveController;
  51922. }(WebVRController));
  51923. BABYLON.ViveController = ViveController;
  51924. })(BABYLON || (BABYLON = {}));
  51925. //# sourceMappingURL=babylon.extendedGamepad.js.map
  51926. /// <reference path="babylon.universalCamera.ts" />
  51927. var BABYLON;
  51928. (function (BABYLON) {
  51929. // We're mainly based on the logic defined into the FreeCamera code
  51930. var GamepadCamera = (function (_super) {
  51931. __extends(GamepadCamera, _super);
  51932. //-- end properties for backward compatibility for inputs
  51933. function GamepadCamera(name, position, scene) {
  51934. return _super.call(this, name, position, scene) || this;
  51935. }
  51936. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51937. //-- Begin properties for backward compatibility for inputs
  51938. get: function () {
  51939. var gamepad = this.inputs.attached["gamepad"];
  51940. if (gamepad)
  51941. return gamepad.gamepadAngularSensibility;
  51942. },
  51943. set: function (value) {
  51944. var gamepad = this.inputs.attached["gamepad"];
  51945. if (gamepad)
  51946. gamepad.gamepadAngularSensibility = value;
  51947. },
  51948. enumerable: true,
  51949. configurable: true
  51950. });
  51951. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51952. get: function () {
  51953. var gamepad = this.inputs.attached["gamepad"];
  51954. if (gamepad)
  51955. return gamepad.gamepadMoveSensibility;
  51956. },
  51957. set: function (value) {
  51958. var gamepad = this.inputs.attached["gamepad"];
  51959. if (gamepad)
  51960. gamepad.gamepadMoveSensibility = value;
  51961. },
  51962. enumerable: true,
  51963. configurable: true
  51964. });
  51965. GamepadCamera.prototype.getClassName = function () {
  51966. return "GamepadCamera";
  51967. };
  51968. return GamepadCamera;
  51969. }(BABYLON.UniversalCamera));
  51970. BABYLON.GamepadCamera = GamepadCamera;
  51971. })(BABYLON || (BABYLON = {}));
  51972. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51973. var BABYLON;
  51974. (function (BABYLON) {
  51975. var Analyser = (function () {
  51976. function Analyser(scene) {
  51977. this.SMOOTHING = 0.75;
  51978. this.FFT_SIZE = 512;
  51979. this.BARGRAPHAMPLITUDE = 256;
  51980. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51981. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51982. this._scene = scene;
  51983. this._audioEngine = BABYLON.Engine.audioEngine;
  51984. if (this._audioEngine.canUseWebAudio) {
  51985. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51986. this._webAudioAnalyser.minDecibels = -140;
  51987. this._webAudioAnalyser.maxDecibels = 0;
  51988. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51989. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51990. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51991. }
  51992. }
  51993. Analyser.prototype.getFrequencyBinCount = function () {
  51994. if (this._audioEngine.canUseWebAudio) {
  51995. return this._webAudioAnalyser.frequencyBinCount;
  51996. }
  51997. else {
  51998. return 0;
  51999. }
  52000. };
  52001. Analyser.prototype.getByteFrequencyData = function () {
  52002. if (this._audioEngine.canUseWebAudio) {
  52003. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52004. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52005. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  52006. }
  52007. return this._byteFreqs;
  52008. };
  52009. Analyser.prototype.getByteTimeDomainData = function () {
  52010. if (this._audioEngine.canUseWebAudio) {
  52011. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52012. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52013. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  52014. }
  52015. return this._byteTime;
  52016. };
  52017. Analyser.prototype.getFloatFrequencyData = function () {
  52018. if (this._audioEngine.canUseWebAudio) {
  52019. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52020. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52021. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  52022. }
  52023. return this._floatFreqs;
  52024. };
  52025. Analyser.prototype.drawDebugCanvas = function () {
  52026. var _this = this;
  52027. if (this._audioEngine.canUseWebAudio) {
  52028. if (!this._debugCanvas) {
  52029. this._debugCanvas = document.createElement("canvas");
  52030. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  52031. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  52032. this._debugCanvas.style.position = "absolute";
  52033. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  52034. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  52035. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52036. document.body.appendChild(this._debugCanvas);
  52037. this._registerFunc = function () {
  52038. _this.drawDebugCanvas();
  52039. };
  52040. this._scene.registerBeforeRender(this._registerFunc);
  52041. }
  52042. if (this._registerFunc) {
  52043. var workingArray = this.getByteFrequencyData();
  52044. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52045. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52046. // Draw the frequency domain chart.
  52047. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52048. var value = workingArray[i];
  52049. var percent = value / this.BARGRAPHAMPLITUDE;
  52050. var height = this.DEBUGCANVASSIZE.height * percent;
  52051. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52052. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52053. var hue = i / this.getFrequencyBinCount() * 360;
  52054. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52055. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52056. }
  52057. }
  52058. }
  52059. };
  52060. Analyser.prototype.stopDebugCanvas = function () {
  52061. if (this._debugCanvas) {
  52062. this._scene.unregisterBeforeRender(this._registerFunc);
  52063. this._registerFunc = null;
  52064. document.body.removeChild(this._debugCanvas);
  52065. this._debugCanvas = null;
  52066. this._debugCanvasContext = null;
  52067. }
  52068. };
  52069. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52070. if (this._audioEngine.canUseWebAudio) {
  52071. inputAudioNode.connect(this._webAudioAnalyser);
  52072. this._webAudioAnalyser.connect(outputAudioNode);
  52073. }
  52074. };
  52075. Analyser.prototype.dispose = function () {
  52076. if (this._audioEngine.canUseWebAudio) {
  52077. this._webAudioAnalyser.disconnect();
  52078. }
  52079. };
  52080. return Analyser;
  52081. }());
  52082. BABYLON.Analyser = Analyser;
  52083. })(BABYLON || (BABYLON = {}));
  52084. //# sourceMappingURL=babylon.analyser.js.map
  52085. var BABYLON;
  52086. (function (BABYLON) {
  52087. var DepthRenderer = (function () {
  52088. function DepthRenderer(scene, type) {
  52089. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52090. var _this = this;
  52091. this._viewMatrix = BABYLON.Matrix.Zero();
  52092. this._projectionMatrix = BABYLON.Matrix.Zero();
  52093. this._transformMatrix = BABYLON.Matrix.Zero();
  52094. this._worldViewProjection = BABYLON.Matrix.Zero();
  52095. this._scene = scene;
  52096. var engine = scene.getEngine();
  52097. // Render target
  52098. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52099. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52100. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52101. this._depthMap.refreshRate = 1;
  52102. this._depthMap.renderParticles = false;
  52103. this._depthMap.renderList = null;
  52104. // set default depth value to 1.0 (far away)
  52105. this._depthMap.onClearObservable.add(function (engine) {
  52106. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52107. });
  52108. // Custom render function
  52109. var renderSubMesh = function (subMesh) {
  52110. var mesh = subMesh.getRenderingMesh();
  52111. var scene = _this._scene;
  52112. var engine = scene.getEngine();
  52113. // Culling
  52114. engine.setState(subMesh.getMaterial().backFaceCulling);
  52115. // Managing instances
  52116. var batch = mesh._getInstancesRenderList(subMesh._id);
  52117. if (batch.mustReturn) {
  52118. return;
  52119. }
  52120. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52121. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52122. engine.enableEffect(_this._effect);
  52123. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52124. var material = subMesh.getMaterial();
  52125. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52126. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  52127. // Alpha test
  52128. if (material && material.needAlphaTesting()) {
  52129. var alphaTexture = material.getAlphaTestTexture();
  52130. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52131. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52132. }
  52133. // Bones
  52134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52135. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52136. }
  52137. // Draw
  52138. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52139. }
  52140. };
  52141. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52142. var index;
  52143. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52144. renderSubMesh(opaqueSubMeshes.data[index]);
  52145. }
  52146. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52147. renderSubMesh(alphaTestSubMeshes.data[index]);
  52148. }
  52149. };
  52150. }
  52151. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52152. var material = subMesh.getMaterial();
  52153. if (material.disableDepthWrite) {
  52154. return false;
  52155. }
  52156. var defines = [];
  52157. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52158. var mesh = subMesh.getMesh();
  52159. var scene = mesh.getScene();
  52160. // Alpha test
  52161. if (material && material.needAlphaTesting()) {
  52162. defines.push("#define ALPHATEST");
  52163. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52164. attribs.push(BABYLON.VertexBuffer.UVKind);
  52165. defines.push("#define UV1");
  52166. }
  52167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52168. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52169. defines.push("#define UV2");
  52170. }
  52171. }
  52172. // Bones
  52173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52176. if (mesh.numBoneInfluencers > 4) {
  52177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52179. }
  52180. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52181. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52182. }
  52183. else {
  52184. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52185. }
  52186. // Instances
  52187. if (useInstances) {
  52188. defines.push("#define INSTANCES");
  52189. attribs.push("world0");
  52190. attribs.push("world1");
  52191. attribs.push("world2");
  52192. attribs.push("world3");
  52193. }
  52194. // Get correct effect
  52195. var join = defines.join("\n");
  52196. if (this._cachedDefines !== join) {
  52197. this._cachedDefines = join;
  52198. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52199. }
  52200. return this._effect.isReady();
  52201. };
  52202. DepthRenderer.prototype.getDepthMap = function () {
  52203. return this._depthMap;
  52204. };
  52205. // Methods
  52206. DepthRenderer.prototype.dispose = function () {
  52207. this._depthMap.dispose();
  52208. };
  52209. return DepthRenderer;
  52210. }());
  52211. BABYLON.DepthRenderer = DepthRenderer;
  52212. })(BABYLON || (BABYLON = {}));
  52213. //# sourceMappingURL=babylon.depthRenderer.js.map
  52214. var BABYLON;
  52215. (function (BABYLON) {
  52216. var SSAORenderingPipeline = (function (_super) {
  52217. __extends(SSAORenderingPipeline, _super);
  52218. /**
  52219. * @constructor
  52220. * @param {string} name - The rendering pipeline name
  52221. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52222. * @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 }
  52223. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52224. */
  52225. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52226. var _this = _super.call(this, scene.getEngine(), name) || this;
  52227. // Members
  52228. /**
  52229. * The PassPostProcess id in the pipeline that contains the original scene color
  52230. * @type {string}
  52231. */
  52232. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52233. /**
  52234. * The SSAO PostProcess id in the pipeline
  52235. * @type {string}
  52236. */
  52237. _this.SSAORenderEffect = "SSAORenderEffect";
  52238. /**
  52239. * The horizontal blur PostProcess id in the pipeline
  52240. * @type {string}
  52241. */
  52242. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52243. /**
  52244. * The vertical blur PostProcess id in the pipeline
  52245. * @type {string}
  52246. */
  52247. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52248. /**
  52249. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52250. * @type {string}
  52251. */
  52252. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52253. /**
  52254. * The output strength of the SSAO post-process. Default value is 1.0.
  52255. * @type {number}
  52256. */
  52257. _this.totalStrength = 1.0;
  52258. /**
  52259. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52260. * @type {number}
  52261. */
  52262. _this.radius = 0.0001;
  52263. /**
  52264. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52265. * Must not be equal to fallOff and superior to fallOff.
  52266. * Default value is 0.975
  52267. * @type {number}
  52268. */
  52269. _this.area = 0.0075;
  52270. /**
  52271. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52272. * Must not be equal to area and inferior to area.
  52273. * Default value is 0.0
  52274. * @type {number}
  52275. */
  52276. _this.fallOff = 0.000001;
  52277. /**
  52278. * The base color of the SSAO post-process
  52279. * The final result is "base + ssao" between [0, 1]
  52280. * @type {number}
  52281. */
  52282. _this.base = 0.5;
  52283. _this._firstUpdate = true;
  52284. _this._scene = scene;
  52285. // Set up assets
  52286. _this._createRandomTexture();
  52287. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52288. var ssaoRatio = ratio.ssaoRatio || ratio;
  52289. var combineRatio = ratio.combineRatio || ratio;
  52290. _this._ratio = {
  52291. ssaoRatio: ssaoRatio,
  52292. combineRatio: combineRatio
  52293. };
  52294. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52295. _this._createSSAOPostProcess(ssaoRatio);
  52296. _this._createBlurPostProcess(ssaoRatio);
  52297. _this._createSSAOCombinePostProcess(combineRatio);
  52298. // Set up pipeline
  52299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52302. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52303. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52304. // Finish
  52305. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52306. if (cameras)
  52307. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52308. return _this;
  52309. }
  52310. // Public Methods
  52311. /**
  52312. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52313. */
  52314. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52315. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52316. for (var i = 0; i < this._scene.cameras.length; i++) {
  52317. var camera = this._scene.cameras[i];
  52318. this._originalColorPostProcess.dispose(camera);
  52319. this._ssaoPostProcess.dispose(camera);
  52320. this._blurHPostProcess.dispose(camera);
  52321. this._blurVPostProcess.dispose(camera);
  52322. this._ssaoCombinePostProcess.dispose(camera);
  52323. }
  52324. this._randomTexture.dispose();
  52325. if (disableDepthRender)
  52326. this._scene.disableDepthRenderer();
  52327. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52328. _super.prototype.dispose.call(this);
  52329. };
  52330. // Private Methods
  52331. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52332. var _this = this;
  52333. /*
  52334. var samplerOffsets = [
  52335. -8.0, -6.0, -4.0, -2.0,
  52336. 0.0,
  52337. 2.0, 4.0, 6.0, 8.0
  52338. ];
  52339. */
  52340. var samples = 16;
  52341. var samplerOffsets = [];
  52342. for (var i = -8; i < 8; i++) {
  52343. samplerOffsets.push(i * 2);
  52344. }
  52345. 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");
  52346. this._blurHPostProcess.onApply = function (effect) {
  52347. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52348. effect.setTexture("depthSampler", _this._depthTexture);
  52349. if (_this._firstUpdate) {
  52350. effect.setArray("samplerOffsets", samplerOffsets);
  52351. }
  52352. };
  52353. 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");
  52354. this._blurVPostProcess.onApply = function (effect) {
  52355. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52356. effect.setTexture("depthSampler", _this._depthTexture);
  52357. if (_this._firstUpdate) {
  52358. effect.setArray("samplerOffsets", samplerOffsets);
  52359. _this._firstUpdate = false;
  52360. }
  52361. };
  52362. };
  52363. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52364. var _this = this;
  52365. var numSamples = 16;
  52366. var sampleSphere = [
  52367. 0.5381, 0.1856, -0.4319,
  52368. 0.1379, 0.2486, 0.4430,
  52369. 0.3371, 0.5679, -0.0057,
  52370. -0.6999, -0.0451, -0.0019,
  52371. 0.0689, -0.1598, -0.8547,
  52372. 0.0560, 0.0069, -0.1843,
  52373. -0.0146, 0.1402, 0.0762,
  52374. 0.0100, -0.1924, -0.0344,
  52375. -0.3577, -0.5301, -0.4358,
  52376. -0.3169, 0.1063, 0.0158,
  52377. 0.0103, -0.5869, 0.0046,
  52378. -0.0897, -0.4940, 0.3287,
  52379. 0.7119, -0.0154, -0.0918,
  52380. -0.0533, 0.0596, -0.5411,
  52381. 0.0352, -0.0631, 0.5460,
  52382. -0.4776, 0.2847, -0.0271
  52383. ];
  52384. var samplesFactor = 1.0 / numSamples;
  52385. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52386. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52387. "area", "fallOff", "base", "range", "viewport"
  52388. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52389. var viewport = new BABYLON.Vector2(0, 0);
  52390. this._ssaoPostProcess.onApply = function (effect) {
  52391. if (_this._firstUpdate) {
  52392. effect.setArray3("sampleSphere", sampleSphere);
  52393. effect.setFloat("samplesFactor", samplesFactor);
  52394. effect.setFloat("randTextureTiles", 4.0);
  52395. }
  52396. effect.setFloat("totalStrength", _this.totalStrength);
  52397. effect.setFloat("radius", _this.radius);
  52398. effect.setFloat("area", _this.area);
  52399. effect.setFloat("fallOff", _this.fallOff);
  52400. effect.setFloat("base", _this.base);
  52401. effect.setTexture("textureSampler", _this._depthTexture);
  52402. effect.setTexture("randomSampler", _this._randomTexture);
  52403. };
  52404. };
  52405. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52406. var _this = this;
  52407. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52408. this._ssaoCombinePostProcess.onApply = function (effect) {
  52409. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52410. };
  52411. };
  52412. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52413. var size = 512;
  52414. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52415. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52416. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52417. var context = this._randomTexture.getContext();
  52418. var rand = function (min, max) {
  52419. return Math.random() * (max - min) + min;
  52420. };
  52421. var randVector = BABYLON.Vector3.Zero();
  52422. for (var x = 0; x < size; x++) {
  52423. for (var y = 0; y < size; y++) {
  52424. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52425. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52426. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52427. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52428. context.fillRect(x, y, 1, 1);
  52429. }
  52430. }
  52431. this._randomTexture.update(false);
  52432. };
  52433. return SSAORenderingPipeline;
  52434. }(BABYLON.PostProcessRenderPipeline));
  52435. __decorate([
  52436. BABYLON.serialize()
  52437. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52438. __decorate([
  52439. BABYLON.serialize()
  52440. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52441. __decorate([
  52442. BABYLON.serialize()
  52443. ], SSAORenderingPipeline.prototype, "area", void 0);
  52444. __decorate([
  52445. BABYLON.serialize()
  52446. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52447. __decorate([
  52448. BABYLON.serialize()
  52449. ], SSAORenderingPipeline.prototype, "base", void 0);
  52450. __decorate([
  52451. BABYLON.serialize()
  52452. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52453. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52454. })(BABYLON || (BABYLON = {}));
  52455. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52456. var BABYLON;
  52457. (function (BABYLON) {
  52458. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52459. var VolumetricLightScatteringPostProcess = (function (_super) {
  52460. __extends(VolumetricLightScatteringPostProcess, _super);
  52461. /**
  52462. * @constructor
  52463. * @param {string} name - The post-process name
  52464. * @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)
  52465. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52466. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52467. * @param {number} samples - The post-process quality, default 100
  52468. * @param {number} samplingMode - The post-process filtering mode
  52469. * @param {BABYLON.Engine} engine - The babylon engine
  52470. * @param {boolean} reusable - If the post-process is reusable
  52471. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52472. */
  52473. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52474. if (samples === void 0) { samples = 100; }
  52475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52476. 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;
  52477. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52478. /**
  52479. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52480. * @type {Vector3}
  52481. */
  52482. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52483. /**
  52484. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52485. * @type {boolean}
  52486. */
  52487. _this.useCustomMeshPosition = false;
  52488. /**
  52489. * If the post-process should inverse the light scattering direction
  52490. * @type {boolean}
  52491. */
  52492. _this.invert = true;
  52493. /**
  52494. * Array containing the excluded meshes not rendered in the internal pass
  52495. */
  52496. _this.excludedMeshes = new Array();
  52497. /**
  52498. * Controls the overall intensity of the post-process
  52499. * @type {number}
  52500. */
  52501. _this.exposure = 0.3;
  52502. /**
  52503. * Dissipates each sample's contribution in range [0, 1]
  52504. * @type {number}
  52505. */
  52506. _this.decay = 0.96815;
  52507. /**
  52508. * Controls the overall intensity of each sample
  52509. * @type {number}
  52510. */
  52511. _this.weight = 0.58767;
  52512. /**
  52513. * Controls the density of each sample
  52514. * @type {number}
  52515. */
  52516. _this.density = 0.926;
  52517. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52518. var engine = scene.getEngine();
  52519. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52520. // Configure mesh
  52521. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52522. // Configure
  52523. _this._createPass(scene, ratio.passRatio || ratio);
  52524. _this.onActivate = function (camera) {
  52525. if (!_this.isSupported) {
  52526. _this.dispose(camera);
  52527. }
  52528. _this.onActivate = null;
  52529. };
  52530. _this.onApplyObservable.add(function (effect) {
  52531. _this._updateMeshScreenCoordinates(scene);
  52532. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52533. effect.setFloat("exposure", _this.exposure);
  52534. effect.setFloat("decay", _this.decay);
  52535. effect.setFloat("weight", _this.weight);
  52536. effect.setFloat("density", _this.density);
  52537. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52538. });
  52539. return _this;
  52540. }
  52541. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52542. get: function () {
  52543. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52544. return false;
  52545. },
  52546. set: function (useDiffuseColor) {
  52547. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52553. var mesh = subMesh.getMesh();
  52554. // Render this.mesh as default
  52555. if (mesh === this.mesh) {
  52556. return mesh.material.isReady(mesh);
  52557. }
  52558. var defines = [];
  52559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52560. var material = subMesh.getMaterial();
  52561. var needUV = false;
  52562. // Alpha test
  52563. if (material) {
  52564. if (material.needAlphaTesting()) {
  52565. defines.push("#define ALPHATEST");
  52566. }
  52567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52568. attribs.push(BABYLON.VertexBuffer.UVKind);
  52569. defines.push("#define UV1");
  52570. }
  52571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52572. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52573. defines.push("#define UV2");
  52574. }
  52575. }
  52576. // Bones
  52577. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52580. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52581. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52582. }
  52583. else {
  52584. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52585. }
  52586. // Instances
  52587. if (useInstances) {
  52588. defines.push("#define INSTANCES");
  52589. attribs.push("world0");
  52590. attribs.push("world1");
  52591. attribs.push("world2");
  52592. attribs.push("world3");
  52593. }
  52594. // Get correct effect
  52595. var join = defines.join("\n");
  52596. if (this._cachedDefines !== join) {
  52597. this._cachedDefines = join;
  52598. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52599. }
  52600. return this._volumetricLightScatteringPass.isReady();
  52601. };
  52602. /**
  52603. * Sets the new light position for light scattering effect
  52604. * @param {BABYLON.Vector3} The new custom light position
  52605. */
  52606. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52607. this.customMeshPosition = position;
  52608. };
  52609. /**
  52610. * Returns the light position for light scattering effect
  52611. * @return {BABYLON.Vector3} The custom light position
  52612. */
  52613. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52614. return this.customMeshPosition;
  52615. };
  52616. /**
  52617. * Disposes the internal assets and detaches the post-process from the camera
  52618. */
  52619. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52620. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52621. if (rttIndex !== -1) {
  52622. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52623. }
  52624. this._volumetricLightScatteringRTT.dispose();
  52625. _super.prototype.dispose.call(this, camera);
  52626. };
  52627. /**
  52628. * Returns the render target texture used by the post-process
  52629. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52630. */
  52631. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52632. return this._volumetricLightScatteringRTT;
  52633. };
  52634. // Private methods
  52635. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52636. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52637. return true;
  52638. }
  52639. return false;
  52640. };
  52641. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52642. var _this = this;
  52643. var engine = scene.getEngine();
  52644. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52645. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52646. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52647. this._volumetricLightScatteringRTT.renderList = null;
  52648. this._volumetricLightScatteringRTT.renderParticles = false;
  52649. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52650. // Custom render function for submeshes
  52651. var renderSubMesh = function (subMesh) {
  52652. var mesh = subMesh.getRenderingMesh();
  52653. if (_this._meshExcluded(mesh)) {
  52654. return;
  52655. }
  52656. var scene = mesh.getScene();
  52657. var engine = scene.getEngine();
  52658. // Culling
  52659. engine.setState(subMesh.getMaterial().backFaceCulling);
  52660. // Managing instances
  52661. var batch = mesh._getInstancesRenderList(subMesh._id);
  52662. if (batch.mustReturn) {
  52663. return;
  52664. }
  52665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52666. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52667. var effect = _this._volumetricLightScatteringPass;
  52668. if (mesh === _this.mesh) {
  52669. effect = subMesh.getMaterial().getEffect();
  52670. }
  52671. engine.enableEffect(effect);
  52672. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52673. if (mesh === _this.mesh) {
  52674. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52675. }
  52676. else {
  52677. var material = subMesh.getMaterial();
  52678. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52679. // Alpha test
  52680. if (material && material.needAlphaTesting()) {
  52681. var alphaTexture = material.getAlphaTestTexture();
  52682. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52683. if (alphaTexture) {
  52684. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52685. }
  52686. }
  52687. // Bones
  52688. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52689. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52690. }
  52691. }
  52692. // Draw
  52693. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52694. }
  52695. };
  52696. // Render target texture callbacks
  52697. var savedSceneClearColor;
  52698. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52699. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52700. savedSceneClearColor = scene.clearColor;
  52701. scene.clearColor = sceneClearColor;
  52702. });
  52703. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52704. scene.clearColor = savedSceneClearColor;
  52705. });
  52706. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52707. var engine = scene.getEngine();
  52708. var index;
  52709. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52710. renderSubMesh(opaqueSubMeshes.data[index]);
  52711. }
  52712. engine.setAlphaTesting(true);
  52713. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52714. renderSubMesh(alphaTestSubMeshes.data[index]);
  52715. }
  52716. engine.setAlphaTesting(false);
  52717. if (transparentSubMeshes.length) {
  52718. // Sort sub meshes
  52719. for (index = 0; index < transparentSubMeshes.length; index++) {
  52720. var submesh = transparentSubMeshes.data[index];
  52721. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52722. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52723. }
  52724. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52725. sortedArray.sort(function (a, b) {
  52726. // Alpha index first
  52727. if (a._alphaIndex > b._alphaIndex) {
  52728. return 1;
  52729. }
  52730. if (a._alphaIndex < b._alphaIndex) {
  52731. return -1;
  52732. }
  52733. // Then distance to camera
  52734. if (a._distanceToCamera < b._distanceToCamera) {
  52735. return 1;
  52736. }
  52737. if (a._distanceToCamera > b._distanceToCamera) {
  52738. return -1;
  52739. }
  52740. return 0;
  52741. });
  52742. // Render sub meshes
  52743. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52744. for (index = 0; index < sortedArray.length; index++) {
  52745. renderSubMesh(sortedArray[index]);
  52746. }
  52747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52748. }
  52749. };
  52750. };
  52751. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52752. var transform = scene.getTransformMatrix();
  52753. var meshPosition;
  52754. if (this.useCustomMeshPosition) {
  52755. meshPosition = this.customMeshPosition;
  52756. }
  52757. else if (this.attachedNode) {
  52758. meshPosition = this.attachedNode.position;
  52759. }
  52760. else {
  52761. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52762. }
  52763. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52764. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52765. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52766. if (this.invert)
  52767. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52768. };
  52769. // Static methods
  52770. /**
  52771. * Creates a default mesh for the Volumeric Light Scattering post-process
  52772. * @param {string} The mesh name
  52773. * @param {BABYLON.Scene} The scene where to create the mesh
  52774. * @return {BABYLON.Mesh} the default mesh
  52775. */
  52776. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52777. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52778. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52779. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52780. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52781. mesh.material = material;
  52782. return mesh;
  52783. };
  52784. return VolumetricLightScatteringPostProcess;
  52785. }(BABYLON.PostProcess));
  52786. __decorate([
  52787. BABYLON.serializeAsVector3()
  52788. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52789. __decorate([
  52790. BABYLON.serialize()
  52791. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52792. __decorate([
  52793. BABYLON.serialize()
  52794. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52795. __decorate([
  52796. BABYLON.serializeAsMeshReference()
  52797. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52798. __decorate([
  52799. BABYLON.serialize()
  52800. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52801. __decorate([
  52802. BABYLON.serialize()
  52803. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52804. __decorate([
  52805. BABYLON.serialize()
  52806. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52807. __decorate([
  52808. BABYLON.serialize()
  52809. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52810. __decorate([
  52811. BABYLON.serialize()
  52812. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52813. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52814. })(BABYLON || (BABYLON = {}));
  52815. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52816. // BABYLON.JS Chromatic Aberration GLSL Shader
  52817. // Author: Olivier Guyot
  52818. // Separates very slightly R, G and B colors on the edges of the screen
  52819. // Inspired by Francois Tarlier & Martins Upitis
  52820. var BABYLON;
  52821. (function (BABYLON) {
  52822. var LensRenderingPipeline = (function (_super) {
  52823. __extends(LensRenderingPipeline, _super);
  52824. /**
  52825. * @constructor
  52826. *
  52827. * Effect parameters are as follow:
  52828. * {
  52829. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52830. * edge_blur: number; // from 0 to x (1 for realism)
  52831. * distortion: number; // from 0 to x (1 for realism)
  52832. * grain_amount: number; // from 0 to 1
  52833. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52834. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52835. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52836. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52837. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52838. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52839. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52840. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52841. * }
  52842. * Note: if an effect parameter is unset, effect is disabled
  52843. *
  52844. * @param {string} name - The rendering pipeline name
  52845. * @param {object} parameters - An object containing all parameters (see above)
  52846. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52847. * @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)
  52848. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52849. */
  52850. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52851. if (ratio === void 0) { ratio = 1.0; }
  52852. var _this = _super.call(this, scene.getEngine(), name) || this;
  52853. // Lens effects can be of the following:
  52854. // - chromatic aberration (slight shift of RGB colors)
  52855. // - blur on the edge of the lens
  52856. // - lens distortion
  52857. // - depth-of-field blur & highlights enhancing
  52858. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52859. // - grain effect (noise or custom texture)
  52860. // Two additional texture samplers are needed:
  52861. // - depth map (for depth-of-field)
  52862. // - grain texture
  52863. /**
  52864. * The chromatic aberration PostProcess id in the pipeline
  52865. * @type {string}
  52866. */
  52867. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52868. /**
  52869. * The highlights enhancing PostProcess id in the pipeline
  52870. * @type {string}
  52871. */
  52872. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52873. /**
  52874. * The depth-of-field PostProcess id in the pipeline
  52875. * @type {string}
  52876. */
  52877. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52878. _this._scene = scene;
  52879. // Fetch texture samplers
  52880. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52881. if (parameters.grain_texture) {
  52882. _this._grainTexture = parameters.grain_texture;
  52883. }
  52884. else {
  52885. _this._createGrainTexture();
  52886. }
  52887. // save parameters
  52888. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52889. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52890. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52891. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52892. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52893. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52894. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52895. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52896. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52897. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52898. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52899. // Create effects
  52900. _this._createChromaticAberrationPostProcess(ratio);
  52901. _this._createHighlightsPostProcess(ratio);
  52902. _this._createDepthOfFieldPostProcess(ratio / 4);
  52903. // Set up pipeline
  52904. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52907. if (_this._highlightsGain === -1) {
  52908. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52909. }
  52910. // Finish
  52911. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52912. if (cameras) {
  52913. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52914. }
  52915. return _this;
  52916. }
  52917. // public methods (self explanatory)
  52918. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52919. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52920. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52921. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52922. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52923. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52924. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52925. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52926. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52927. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52928. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52929. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52930. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52931. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52932. };
  52933. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52934. this._highlightsPostProcess.updateEffect();
  52935. };
  52936. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52937. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52938. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52939. this._highlightsGain = amount;
  52940. };
  52941. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52942. if (this._highlightsGain === -1) {
  52943. this._highlightsGain = 1.0;
  52944. }
  52945. this._highlightsThreshold = amount;
  52946. };
  52947. LensRenderingPipeline.prototype.disableHighlights = function () {
  52948. this._highlightsGain = -1;
  52949. };
  52950. /**
  52951. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52952. */
  52953. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52954. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52955. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52956. this._chromaticAberrationPostProcess = undefined;
  52957. this._highlightsPostProcess = undefined;
  52958. this._depthOfFieldPostProcess = undefined;
  52959. this._grainTexture.dispose();
  52960. if (disableDepthRender)
  52961. this._scene.disableDepthRenderer();
  52962. };
  52963. // colors shifting and distortion
  52964. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52965. var _this = this;
  52966. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52967. [], // samplers
  52968. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52969. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52970. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52971. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52972. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52973. };
  52974. };
  52975. // highlights enhancing
  52976. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52977. var _this = this;
  52978. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52979. [], // samplers
  52980. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52981. this._highlightsPostProcess.onApply = function (effect) {
  52982. effect.setFloat('gain', _this._highlightsGain);
  52983. effect.setFloat('threshold', _this._highlightsThreshold);
  52984. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52985. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52986. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52987. };
  52988. };
  52989. // colors shifting and distortion
  52990. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52991. var _this = this;
  52992. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52993. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52994. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52995. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52996. this._depthOfFieldPostProcess.onApply = function (effect) {
  52997. effect.setTexture("depthSampler", _this._depthTexture);
  52998. effect.setTexture("grainSampler", _this._grainTexture);
  52999. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53000. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53001. effect.setFloat('grain_amount', _this._grainAmount);
  53002. effect.setBool('blur_noise', _this._blurNoise);
  53003. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53004. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53005. effect.setFloat('distortion', _this._distortion);
  53006. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53007. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53008. effect.setFloat('aperture', _this._dofAperture);
  53009. effect.setFloat('darken', _this._dofDarken);
  53010. effect.setFloat('edge_blur', _this._edgeBlur);
  53011. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53012. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53013. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53014. };
  53015. };
  53016. // creates a black and white random noise texture, 512x512
  53017. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53018. var size = 512;
  53019. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53020. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53021. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53022. var context = this._grainTexture.getContext();
  53023. var rand = function (min, max) {
  53024. return Math.random() * (max - min) + min;
  53025. };
  53026. var value;
  53027. for (var x = 0; x < size; x++) {
  53028. for (var y = 0; y < size; y++) {
  53029. value = Math.floor(rand(0.42, 0.58) * 255);
  53030. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53031. context.fillRect(x, y, 1, 1);
  53032. }
  53033. }
  53034. this._grainTexture.update(false);
  53035. };
  53036. return LensRenderingPipeline;
  53037. }(BABYLON.PostProcessRenderPipeline));
  53038. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53039. })(BABYLON || (BABYLON = {}));
  53040. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  53041. //
  53042. // This post-process allows the modification of rendered colors by using
  53043. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53044. //
  53045. // The object needs to be provided an url to a texture containing the color
  53046. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53047. // Use an image editing software to tweak the LUT to match your needs.
  53048. //
  53049. // For an example of a color LUT, see here:
  53050. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53051. // For explanations on color grading, see here:
  53052. // http://udn.epicgames.com/Three/ColorGrading.html
  53053. //
  53054. var BABYLON;
  53055. (function (BABYLON) {
  53056. var ColorCorrectionPostProcess = (function (_super) {
  53057. __extends(ColorCorrectionPostProcess, _super);
  53058. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53059. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  53060. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53061. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  53062. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53063. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53064. _this.onApply = function (effect) {
  53065. effect.setTexture("colorTable", _this._colorTableTexture);
  53066. };
  53067. return _this;
  53068. }
  53069. return ColorCorrectionPostProcess;
  53070. }(BABYLON.PostProcess));
  53071. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53072. })(BABYLON || (BABYLON = {}));
  53073. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  53074. /// <reference path="babylon.freeCamera.ts" />
  53075. /// <reference path="babylon.arcRotateCamera.ts" />
  53076. /// <reference path="babylon.gamepadCamera.ts" />
  53077. /// <reference path="babylon.universalCamera.ts" />
  53078. var BABYLON;
  53079. (function (BABYLON) {
  53080. var AnaglyphFreeCamera = (function (_super) {
  53081. __extends(AnaglyphFreeCamera, _super);
  53082. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  53083. var _this = _super.call(this, name, position, scene) || this;
  53084. _this.interaxialDistance = interaxialDistance;
  53085. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53086. return _this;
  53087. }
  53088. AnaglyphFreeCamera.prototype.getClassName = function () {
  53089. return "AnaglyphFreeCamera";
  53090. };
  53091. return AnaglyphFreeCamera;
  53092. }(BABYLON.FreeCamera));
  53093. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  53094. var AnaglyphArcRotateCamera = (function (_super) {
  53095. __extends(AnaglyphArcRotateCamera, _super);
  53096. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  53097. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  53098. _this.interaxialDistance = interaxialDistance;
  53099. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53100. return _this;
  53101. }
  53102. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  53103. return "AnaglyphArcRotateCamera";
  53104. };
  53105. return AnaglyphArcRotateCamera;
  53106. }(BABYLON.ArcRotateCamera));
  53107. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  53108. var AnaglyphGamepadCamera = (function (_super) {
  53109. __extends(AnaglyphGamepadCamera, _super);
  53110. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  53111. var _this = _super.call(this, name, position, scene) || this;
  53112. _this.interaxialDistance = interaxialDistance;
  53113. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53114. return _this;
  53115. }
  53116. AnaglyphGamepadCamera.prototype.getClassName = function () {
  53117. return "AnaglyphGamepadCamera";
  53118. };
  53119. return AnaglyphGamepadCamera;
  53120. }(BABYLON.GamepadCamera));
  53121. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  53122. var AnaglyphUniversalCamera = (function (_super) {
  53123. __extends(AnaglyphUniversalCamera, _super);
  53124. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  53125. var _this = _super.call(this, name, position, scene) || this;
  53126. _this.interaxialDistance = interaxialDistance;
  53127. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53128. return _this;
  53129. }
  53130. AnaglyphUniversalCamera.prototype.getClassName = function () {
  53131. return "AnaglyphUniversalCamera";
  53132. };
  53133. return AnaglyphUniversalCamera;
  53134. }(BABYLON.UniversalCamera));
  53135. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  53136. var StereoscopicFreeCamera = (function (_super) {
  53137. __extends(StereoscopicFreeCamera, _super);
  53138. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53139. var _this = _super.call(this, name, position, scene) || this;
  53140. _this.interaxialDistance = interaxialDistance;
  53141. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53142. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53143. return _this;
  53144. }
  53145. StereoscopicFreeCamera.prototype.getClassName = function () {
  53146. return "StereoscopicFreeCamera";
  53147. };
  53148. return StereoscopicFreeCamera;
  53149. }(BABYLON.FreeCamera));
  53150. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  53151. var StereoscopicArcRotateCamera = (function (_super) {
  53152. __extends(StereoscopicArcRotateCamera, _super);
  53153. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  53154. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  53155. _this.interaxialDistance = interaxialDistance;
  53156. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53157. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53158. return _this;
  53159. }
  53160. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  53161. return "StereoscopicArcRotateCamera";
  53162. };
  53163. return StereoscopicArcRotateCamera;
  53164. }(BABYLON.ArcRotateCamera));
  53165. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  53166. var StereoscopicGamepadCamera = (function (_super) {
  53167. __extends(StereoscopicGamepadCamera, _super);
  53168. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53169. var _this = _super.call(this, name, position, scene) || this;
  53170. _this.interaxialDistance = interaxialDistance;
  53171. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53172. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53173. return _this;
  53174. }
  53175. StereoscopicGamepadCamera.prototype.getClassName = function () {
  53176. return "StereoscopicGamepadCamera";
  53177. };
  53178. return StereoscopicGamepadCamera;
  53179. }(BABYLON.GamepadCamera));
  53180. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53181. var StereoscopicUniversalCamera = (function (_super) {
  53182. __extends(StereoscopicUniversalCamera, _super);
  53183. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53184. var _this = _super.call(this, name, position, scene) || this;
  53185. _this.interaxialDistance = interaxialDistance;
  53186. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53187. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53188. return _this;
  53189. }
  53190. StereoscopicUniversalCamera.prototype.getClassName = function () {
  53191. return "StereoscopicUniversalCamera";
  53192. };
  53193. return StereoscopicUniversalCamera;
  53194. }(BABYLON.UniversalCamera));
  53195. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53196. })(BABYLON || (BABYLON = {}));
  53197. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  53198. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  53199. var BABYLON;
  53200. (function (BABYLON) {
  53201. var HDRRenderingPipeline = (function (_super) {
  53202. __extends(HDRRenderingPipeline, _super);
  53203. /**
  53204. * @constructor
  53205. * @param {string} name - The rendering pipeline name
  53206. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53207. * @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)
  53208. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53209. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53210. */
  53211. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53212. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53213. var _this = _super.call(this, scene.getEngine(), name) || this;
  53214. /**
  53215. * Public members
  53216. */
  53217. // Gaussian Blur
  53218. /**
  53219. * Gaussian blur coefficient
  53220. * @type {number}
  53221. */
  53222. _this.gaussCoeff = 0.3;
  53223. /**
  53224. * Gaussian blur mean
  53225. * @type {number}
  53226. */
  53227. _this.gaussMean = 1.0;
  53228. /**
  53229. * Gaussian blur standard deviation
  53230. * @type {number}
  53231. */
  53232. _this.gaussStandDev = 0.8;
  53233. /**
  53234. * Gaussian blur multiplier. Multiplies the blur effect
  53235. * @type {number}
  53236. */
  53237. _this.gaussMultiplier = 4.0;
  53238. // HDR
  53239. /**
  53240. * Exposure, controls the overall intensity of the pipeline
  53241. * @type {number}
  53242. */
  53243. _this.exposure = 1.0;
  53244. /**
  53245. * Minimum luminance that the post-process can output. Luminance is >= 0
  53246. * @type {number}
  53247. */
  53248. _this.minimumLuminance = 1.0;
  53249. /**
  53250. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53251. * @type {number}
  53252. */
  53253. _this.maximumLuminance = 1e20;
  53254. /**
  53255. * Increase rate for luminance: eye adaptation speed to dark
  53256. * @type {number}
  53257. */
  53258. _this.luminanceIncreaserate = 0.5;
  53259. /**
  53260. * Decrease rate for luminance: eye adaptation speed to bright
  53261. * @type {number}
  53262. */
  53263. _this.luminanceDecreaseRate = 0.5;
  53264. // Bright pass
  53265. /**
  53266. * Minimum luminance needed to compute HDR
  53267. * @type {number}
  53268. */
  53269. _this.brightThreshold = 0.8;
  53270. _this._needUpdate = true;
  53271. _this._scene = scene;
  53272. // Bright pass
  53273. _this._createBrightPassPostProcess(scene, ratio);
  53274. // Down sample X4
  53275. _this._createDownSampleX4PostProcess(scene, ratio);
  53276. // Create gaussian blur post-processes
  53277. _this._createGaussianBlurPostProcess(scene, ratio);
  53278. // Texture adder
  53279. _this._createTextureAdderPostProcess(scene, ratio);
  53280. // Luminance generator
  53281. _this._createLuminanceGeneratorPostProcess(scene);
  53282. // HDR
  53283. _this._createHDRPostProcess(scene, ratio);
  53284. // Pass postprocess
  53285. if (originalPostProcess === null) {
  53286. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53287. }
  53288. else {
  53289. _this._originalPostProcess = originalPostProcess;
  53290. }
  53291. // Configure pipeline
  53292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53296. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53297. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53298. var addDownSamplerPostProcess = function (id) {
  53299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53300. };
  53301. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53302. addDownSamplerPostProcess(i);
  53303. }
  53304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53305. // Finish
  53306. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53307. if (cameras !== null) {
  53308. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53309. }
  53310. _this.update();
  53311. return _this;
  53312. }
  53313. /**
  53314. * Tells the pipeline to update its post-processes
  53315. */
  53316. HDRRenderingPipeline.prototype.update = function () {
  53317. this._needUpdate = true;
  53318. };
  53319. /**
  53320. * Returns the current calculated luminance
  53321. */
  53322. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53323. return this._hdrCurrentLuminance;
  53324. };
  53325. /**
  53326. * Returns the currently drawn luminance
  53327. */
  53328. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53329. return this._hdrOutputLuminance;
  53330. };
  53331. /**
  53332. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53333. */
  53334. HDRRenderingPipeline.prototype.dispose = function () {
  53335. for (var i = 0; i < this._scene.cameras.length; i++) {
  53336. var camera = this._scene.cameras[i];
  53337. this._originalPostProcess.dispose(camera);
  53338. this._brightPassPostProcess.dispose(camera);
  53339. this._downSampleX4PostProcess.dispose(camera);
  53340. this._guassianBlurHPostProcess.dispose(camera);
  53341. this._guassianBlurVPostProcess.dispose(camera);
  53342. this._textureAdderPostProcess.dispose(camera);
  53343. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  53344. this._downSamplePostProcesses[j].dispose(camera);
  53345. }
  53346. this._hdrPostProcess.dispose(camera);
  53347. }
  53348. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53349. _super.prototype.dispose.call(this);
  53350. };
  53351. /**
  53352. * Creates the HDR post-process and computes the luminance adaptation
  53353. */
  53354. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53355. var _this = this;
  53356. var hdrLastLuminance = 0.0;
  53357. this._hdrOutputLuminance = -1.0;
  53358. this._hdrCurrentLuminance = 1.0;
  53359. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53360. this._hdrPostProcess.onApply = function (effect) {
  53361. if (_this._hdrOutputLuminance < 0.0) {
  53362. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53363. }
  53364. else {
  53365. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53366. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53367. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53368. }
  53369. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53370. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53371. }
  53372. else {
  53373. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53374. }
  53375. }
  53376. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53377. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53378. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53379. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53380. effect.setFloat("exposure", _this.exposure);
  53381. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53382. _this._needUpdate = false;
  53383. };
  53384. };
  53385. /**
  53386. * Texture Adder post-process
  53387. */
  53388. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53389. var _this = this;
  53390. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53391. this._textureAdderPostProcess.onApply = function (effect) {
  53392. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53393. };
  53394. };
  53395. /**
  53396. * Down sample X4 post-process
  53397. */
  53398. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53399. var _this = this;
  53400. var downSampleX4Offsets = new Array(32);
  53401. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53402. this._downSampleX4PostProcess.onApply = function (effect) {
  53403. if (_this._needUpdate) {
  53404. var id = 0;
  53405. for (var i = -2; i < 2; i++) {
  53406. for (var j = -2; j < 2; j++) {
  53407. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53408. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53409. id += 2;
  53410. }
  53411. }
  53412. }
  53413. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53414. };
  53415. };
  53416. /**
  53417. * Bright pass post-process
  53418. */
  53419. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53420. var _this = this;
  53421. var brightOffsets = new Array(8);
  53422. var brightPassCallback = function (effect) {
  53423. if (_this._needUpdate) {
  53424. var sU = (1.0 / _this._brightPassPostProcess.width);
  53425. var sV = (1.0 / _this._brightPassPostProcess.height);
  53426. brightOffsets[0] = -0.5 * sU;
  53427. brightOffsets[1] = 0.5 * sV;
  53428. brightOffsets[2] = 0.5 * sU;
  53429. brightOffsets[3] = 0.5 * sV;
  53430. brightOffsets[4] = -0.5 * sU;
  53431. brightOffsets[5] = -0.5 * sV;
  53432. brightOffsets[6] = 0.5 * sU;
  53433. brightOffsets[7] = -0.5 * sV;
  53434. }
  53435. effect.setArray2("dsOffsets", brightOffsets);
  53436. effect.setFloat("brightThreshold", _this.brightThreshold);
  53437. };
  53438. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53439. this._brightPassPostProcess.onApply = brightPassCallback;
  53440. };
  53441. /**
  53442. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53443. */
  53444. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53445. var _this = this;
  53446. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53447. var luminanceOffsets = new Array(8);
  53448. var downSampleOffsets = new Array(18);
  53449. var halfDestPixelSize;
  53450. this._downSamplePostProcesses = new Array(lumSteps);
  53451. // Utils for luminance
  53452. var luminanceUpdateSourceOffsets = function (width, height) {
  53453. var sU = (1.0 / width);
  53454. var sV = (1.0 / height);
  53455. luminanceOffsets[0] = -0.5 * sU;
  53456. luminanceOffsets[1] = 0.5 * sV;
  53457. luminanceOffsets[2] = 0.5 * sU;
  53458. luminanceOffsets[3] = 0.5 * sV;
  53459. luminanceOffsets[4] = -0.5 * sU;
  53460. luminanceOffsets[5] = -0.5 * sV;
  53461. luminanceOffsets[6] = 0.5 * sU;
  53462. luminanceOffsets[7] = -0.5 * sV;
  53463. };
  53464. var luminanceUpdateDestOffsets = function (width, height) {
  53465. var id = 0;
  53466. for (var x = -1; x < 2; x++) {
  53467. for (var y = -1; y < 2; y++) {
  53468. downSampleOffsets[id] = (x) / width;
  53469. downSampleOffsets[id + 1] = (y) / height;
  53470. id += 2;
  53471. }
  53472. }
  53473. };
  53474. // Luminance callback
  53475. var luminanceCallback = function (effect) {
  53476. if (_this._needUpdate) {
  53477. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53478. }
  53479. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53480. effect.setArray2("lumOffsets", luminanceOffsets);
  53481. };
  53482. // Down sample callbacks
  53483. var downSampleCallback = function (indice) {
  53484. var i = indice;
  53485. return function (effect) {
  53486. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53487. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53488. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53489. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53490. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53491. effect.setArray2("dsOffsets", downSampleOffsets);
  53492. };
  53493. };
  53494. var downSampleAfterRenderCallback = function (effect) {
  53495. // Unpack result
  53496. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53497. 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);
  53498. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53499. };
  53500. // Create luminance post-process
  53501. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53502. 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);
  53503. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53504. // Create down sample post-processes
  53505. for (var i = lumSteps - 2; i >= 0; i--) {
  53506. var length = Math.pow(3, i);
  53507. ratio = { width: length, height: length };
  53508. var defines = "#define DOWN_SAMPLE\n";
  53509. if (i === 0) {
  53510. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53511. }
  53512. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53513. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53514. if (i === 0) {
  53515. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53516. }
  53517. }
  53518. };
  53519. /**
  53520. * Gaussian blur post-processes. Horizontal and Vertical
  53521. */
  53522. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53523. var _this = this;
  53524. var blurOffsetsW = new Array(9);
  53525. var blurOffsetsH = new Array(9);
  53526. var blurWeights = new Array(9);
  53527. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53528. // Utils for gaussian blur
  53529. var calculateBlurOffsets = function (height) {
  53530. var lastOutputDimensions = {
  53531. width: scene.getEngine().getRenderWidth(),
  53532. height: scene.getEngine().getRenderHeight()
  53533. };
  53534. for (var i = 0; i < 9; i++) {
  53535. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53536. if (height) {
  53537. blurOffsetsH[i] = value;
  53538. }
  53539. else {
  53540. blurOffsetsW[i] = value;
  53541. }
  53542. }
  53543. };
  53544. var calculateWeights = function () {
  53545. var x = 0.0;
  53546. for (var i = 0; i < 9; i++) {
  53547. x = (i - 4.0) / 4.0;
  53548. 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));
  53549. }
  53550. };
  53551. // Callback
  53552. var gaussianBlurCallback = function (height) {
  53553. return function (effect) {
  53554. if (_this._needUpdate) {
  53555. calculateWeights();
  53556. calculateBlurOffsets(height);
  53557. }
  53558. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53559. effect.setArray("blurWeights", blurWeights);
  53560. effect.setFloat("multiplier", _this.gaussMultiplier);
  53561. };
  53562. };
  53563. // Create horizontal gaussian blur post-processes
  53564. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53565. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53566. // Create vertical gaussian blur post-process
  53567. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53568. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53569. };
  53570. return HDRRenderingPipeline;
  53571. }(BABYLON.PostProcessRenderPipeline));
  53572. // Luminance generator
  53573. HDRRenderingPipeline.LUM_STEPS = 6;
  53574. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53575. })(BABYLON || (BABYLON = {}));
  53576. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  53577. var BABYLON;
  53578. (function (BABYLON) {
  53579. var FaceAdjacencies = (function () {
  53580. function FaceAdjacencies() {
  53581. this.edges = new Array();
  53582. this.edgesConnectedCount = 0;
  53583. }
  53584. return FaceAdjacencies;
  53585. }());
  53586. var EdgesRenderer = (function () {
  53587. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53588. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53589. if (epsilon === void 0) { epsilon = 0.95; }
  53590. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53591. this.edgesWidthScalerForOrthographic = 1000.0;
  53592. this.edgesWidthScalerForPerspective = 50.0;
  53593. this._linesPositions = new Array();
  53594. this._linesNormals = new Array();
  53595. this._linesIndices = new Array();
  53596. this._buffers = {};
  53597. this._checkVerticesInsteadOfIndices = false;
  53598. this._source = source;
  53599. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53600. this._epsilon = epsilon;
  53601. this._prepareRessources();
  53602. this._generateEdgesLines();
  53603. }
  53604. EdgesRenderer.prototype._prepareRessources = function () {
  53605. if (this._lineShader) {
  53606. return;
  53607. }
  53608. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53609. attributes: ["position", "normal"],
  53610. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53611. });
  53612. this._lineShader.disableDepthWrite = true;
  53613. this._lineShader.backFaceCulling = false;
  53614. };
  53615. EdgesRenderer.prototype.dispose = function () {
  53616. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53617. if (buffer) {
  53618. buffer.dispose();
  53619. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53620. }
  53621. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53622. if (buffer) {
  53623. buffer.dispose();
  53624. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53625. }
  53626. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53627. this._lineShader.dispose();
  53628. };
  53629. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53630. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53631. return 0;
  53632. }
  53633. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53634. return 1;
  53635. }
  53636. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53637. return 2;
  53638. }
  53639. return -1;
  53640. };
  53641. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53642. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53643. return 0;
  53644. }
  53645. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53646. return 1;
  53647. }
  53648. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53649. return 2;
  53650. }
  53651. return -1;
  53652. };
  53653. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53654. var needToCreateLine;
  53655. if (edge === undefined) {
  53656. needToCreateLine = true;
  53657. }
  53658. else {
  53659. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53660. needToCreateLine = dotProduct < this._epsilon;
  53661. }
  53662. if (needToCreateLine) {
  53663. var offset = this._linesPositions.length / 3;
  53664. var normal = p0.subtract(p1);
  53665. normal.normalize();
  53666. // Positions
  53667. this._linesPositions.push(p0.x);
  53668. this._linesPositions.push(p0.y);
  53669. this._linesPositions.push(p0.z);
  53670. this._linesPositions.push(p0.x);
  53671. this._linesPositions.push(p0.y);
  53672. this._linesPositions.push(p0.z);
  53673. this._linesPositions.push(p1.x);
  53674. this._linesPositions.push(p1.y);
  53675. this._linesPositions.push(p1.z);
  53676. this._linesPositions.push(p1.x);
  53677. this._linesPositions.push(p1.y);
  53678. this._linesPositions.push(p1.z);
  53679. // Normals
  53680. this._linesNormals.push(p1.x);
  53681. this._linesNormals.push(p1.y);
  53682. this._linesNormals.push(p1.z);
  53683. this._linesNormals.push(-1);
  53684. this._linesNormals.push(p1.x);
  53685. this._linesNormals.push(p1.y);
  53686. this._linesNormals.push(p1.z);
  53687. this._linesNormals.push(1);
  53688. this._linesNormals.push(p0.x);
  53689. this._linesNormals.push(p0.y);
  53690. this._linesNormals.push(p0.z);
  53691. this._linesNormals.push(-1);
  53692. this._linesNormals.push(p0.x);
  53693. this._linesNormals.push(p0.y);
  53694. this._linesNormals.push(p0.z);
  53695. this._linesNormals.push(1);
  53696. // Indices
  53697. this._linesIndices.push(offset);
  53698. this._linesIndices.push(offset + 1);
  53699. this._linesIndices.push(offset + 2);
  53700. this._linesIndices.push(offset);
  53701. this._linesIndices.push(offset + 2);
  53702. this._linesIndices.push(offset + 3);
  53703. }
  53704. };
  53705. EdgesRenderer.prototype._generateEdgesLines = function () {
  53706. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53707. var indices = this._source.getIndices();
  53708. // First let's find adjacencies
  53709. var adjacencies = new Array();
  53710. var faceNormals = new Array();
  53711. var index;
  53712. var faceAdjacencies;
  53713. // Prepare faces
  53714. for (index = 0; index < indices.length; index += 3) {
  53715. faceAdjacencies = new FaceAdjacencies();
  53716. var p0Index = indices[index];
  53717. var p1Index = indices[index + 1];
  53718. var p2Index = indices[index + 2];
  53719. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53720. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53721. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53722. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53723. faceNormal.normalize();
  53724. faceNormals.push(faceNormal);
  53725. adjacencies.push(faceAdjacencies);
  53726. }
  53727. // Scan
  53728. for (index = 0; index < adjacencies.length; index++) {
  53729. faceAdjacencies = adjacencies[index];
  53730. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53731. var otherFaceAdjacencies = adjacencies[otherIndex];
  53732. if (faceAdjacencies.edgesConnectedCount === 3) {
  53733. break;
  53734. }
  53735. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53736. continue;
  53737. }
  53738. var otherP0 = indices[otherIndex * 3];
  53739. var otherP1 = indices[otherIndex * 3 + 1];
  53740. var otherP2 = indices[otherIndex * 3 + 2];
  53741. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53742. var otherEdgeIndex;
  53743. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53744. continue;
  53745. }
  53746. switch (edgeIndex) {
  53747. case 0:
  53748. if (this._checkVerticesInsteadOfIndices) {
  53749. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53750. }
  53751. else {
  53752. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53753. }
  53754. break;
  53755. case 1:
  53756. if (this._checkVerticesInsteadOfIndices) {
  53757. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53758. }
  53759. else {
  53760. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53761. }
  53762. break;
  53763. case 2:
  53764. if (this._checkVerticesInsteadOfIndices) {
  53765. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53766. }
  53767. else {
  53768. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53769. }
  53770. break;
  53771. }
  53772. if (otherEdgeIndex === -1) {
  53773. continue;
  53774. }
  53775. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53776. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53777. faceAdjacencies.edgesConnectedCount++;
  53778. otherFaceAdjacencies.edgesConnectedCount++;
  53779. if (faceAdjacencies.edgesConnectedCount === 3) {
  53780. break;
  53781. }
  53782. }
  53783. }
  53784. }
  53785. // Create lines
  53786. for (index = 0; index < adjacencies.length; index++) {
  53787. // 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
  53788. var current = adjacencies[index];
  53789. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53790. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53791. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53792. }
  53793. // Merge into a single mesh
  53794. var engine = this._source.getScene().getEngine();
  53795. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53796. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53797. this._ib = engine.createIndexBuffer(this._linesIndices);
  53798. this._indicesCount = this._linesIndices.length;
  53799. };
  53800. EdgesRenderer.prototype.render = function () {
  53801. if (!this._lineShader.isReady()) {
  53802. return;
  53803. }
  53804. var scene = this._source.getScene();
  53805. var engine = scene.getEngine();
  53806. this._lineShader._preBind();
  53807. // VBOs
  53808. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53809. scene.resetCachedMaterial();
  53810. this._lineShader.setColor4("color", this._source.edgesColor);
  53811. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53812. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53813. }
  53814. else {
  53815. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53816. }
  53817. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53818. this._lineShader.bind(this._source.getWorldMatrix());
  53819. // Draw order
  53820. engine.draw(true, 0, this._indicesCount);
  53821. this._lineShader.unbind();
  53822. engine.setDepthWrite(true);
  53823. };
  53824. return EdgesRenderer;
  53825. }());
  53826. BABYLON.EdgesRenderer = EdgesRenderer;
  53827. })(BABYLON || (BABYLON = {}));
  53828. //# sourceMappingURL=babylon.edgesRenderer.js.map
  53829. var BABYLON;
  53830. (function (BABYLON) {
  53831. var TonemappingOperator;
  53832. (function (TonemappingOperator) {
  53833. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53834. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53835. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53836. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53837. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53838. ;
  53839. var TonemapPostProcess = (function (_super) {
  53840. __extends(TonemapPostProcess, _super);
  53841. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53843. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53844. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53845. _this._operator = _operator;
  53846. _this.exposureAdjustment = exposureAdjustment;
  53847. var defines = "#define ";
  53848. if (_this._operator === TonemappingOperator.Hable)
  53849. defines += "HABLE_TONEMAPPING";
  53850. else if (_this._operator === TonemappingOperator.Reinhard)
  53851. defines += "REINHARD_TONEMAPPING";
  53852. else if (_this._operator === TonemappingOperator.HejiDawson)
  53853. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53854. else if (_this._operator === TonemappingOperator.Photographic)
  53855. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53856. //sadly a second call to create the effect.
  53857. _this.updateEffect(defines);
  53858. _this.onApply = function (effect) {
  53859. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53860. };
  53861. return _this;
  53862. }
  53863. return TonemapPostProcess;
  53864. }(BABYLON.PostProcess));
  53865. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53866. })(BABYLON || (BABYLON = {}));
  53867. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53868. var BABYLON;
  53869. (function (BABYLON) {
  53870. var ReflectionProbe = (function () {
  53871. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53873. var _this = this;
  53874. this.name = name;
  53875. this._viewMatrix = BABYLON.Matrix.Identity();
  53876. this._target = BABYLON.Vector3.Zero();
  53877. this._add = BABYLON.Vector3.Zero();
  53878. this.invertYAxis = false;
  53879. this.position = BABYLON.Vector3.Zero();
  53880. this._scene = scene;
  53881. this._scene.reflectionProbes.push(this);
  53882. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53883. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53884. switch (faceIndex) {
  53885. case 0:
  53886. _this._add.copyFromFloats(1, 0, 0);
  53887. break;
  53888. case 1:
  53889. _this._add.copyFromFloats(-1, 0, 0);
  53890. break;
  53891. case 2:
  53892. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53893. break;
  53894. case 3:
  53895. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53896. break;
  53897. case 4:
  53898. _this._add.copyFromFloats(0, 0, 1);
  53899. break;
  53900. case 5:
  53901. _this._add.copyFromFloats(0, 0, -1);
  53902. break;
  53903. }
  53904. if (_this._attachedMesh) {
  53905. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53906. }
  53907. _this.position.addToRef(_this._add, _this._target);
  53908. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53909. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53910. });
  53911. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53912. scene.updateTransformMatrix(true);
  53913. });
  53914. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53915. }
  53916. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  53917. get: function () {
  53918. return this._renderTargetTexture.samples;
  53919. },
  53920. set: function (value) {
  53921. this._renderTargetTexture.samples = value;
  53922. },
  53923. enumerable: true,
  53924. configurable: true
  53925. });
  53926. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53927. get: function () {
  53928. return this._renderTargetTexture.refreshRate;
  53929. },
  53930. set: function (value) {
  53931. this._renderTargetTexture.refreshRate = value;
  53932. },
  53933. enumerable: true,
  53934. configurable: true
  53935. });
  53936. ReflectionProbe.prototype.getScene = function () {
  53937. return this._scene;
  53938. };
  53939. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53940. get: function () {
  53941. return this._renderTargetTexture;
  53942. },
  53943. enumerable: true,
  53944. configurable: true
  53945. });
  53946. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53947. get: function () {
  53948. return this._renderTargetTexture.renderList;
  53949. },
  53950. enumerable: true,
  53951. configurable: true
  53952. });
  53953. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53954. this._attachedMesh = mesh;
  53955. };
  53956. ReflectionProbe.prototype.dispose = function () {
  53957. var index = this._scene.reflectionProbes.indexOf(this);
  53958. if (index !== -1) {
  53959. // Remove from the scene if found
  53960. this._scene.reflectionProbes.splice(index, 1);
  53961. }
  53962. if (this._renderTargetTexture) {
  53963. this._renderTargetTexture.dispose();
  53964. this._renderTargetTexture = null;
  53965. }
  53966. };
  53967. return ReflectionProbe;
  53968. }());
  53969. BABYLON.ReflectionProbe = ReflectionProbe;
  53970. })(BABYLON || (BABYLON = {}));
  53971. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53972. var BABYLON;
  53973. (function (BABYLON) {
  53974. var SolidParticle = (function () {
  53975. /**
  53976. * Creates a Solid Particle object.
  53977. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53978. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53979. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53980. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53981. * `shapeId` (integer) is the model shape identifier in the SPS.
  53982. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53983. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53984. */
  53985. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53986. this.idx = 0; // particle global index
  53987. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53988. this.position = BABYLON.Vector3.Zero(); // position
  53989. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53990. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53991. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53992. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53993. this.alive = true; // alive
  53994. this.isVisible = true; // visibility
  53995. this._pos = 0; // index of this particle in the global "positions" array
  53996. this.shapeId = 0; // model shape id
  53997. this.idxInShape = 0; // index of the particle in its shape id
  53998. this.idx = particleIndex;
  53999. this._pos = positionIndex;
  54000. this._model = model;
  54001. this.shapeId = shapeId;
  54002. this.idxInShape = idxInShape;
  54003. this._sps = sps;
  54004. if (modelBoundingInfo) {
  54005. this._modelBoundingInfo = modelBoundingInfo;
  54006. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54007. }
  54008. }
  54009. Object.defineProperty(SolidParticle.prototype, "scale", {
  54010. /**
  54011. * legacy support, changed scale to scaling
  54012. */
  54013. get: function () {
  54014. return this.scaling;
  54015. },
  54016. set: function (scale) {
  54017. this.scaling = scale;
  54018. },
  54019. enumerable: true,
  54020. configurable: true
  54021. });
  54022. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54023. /**
  54024. * legacy support, changed quaternion to rotationQuaternion
  54025. */
  54026. get: function () {
  54027. return this.rotationQuaternion;
  54028. },
  54029. set: function (q) {
  54030. this.rotationQuaternion = q;
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. /**
  54036. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54037. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54038. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  54039. */
  54040. SolidParticle.prototype.intersectsMesh = function (target) {
  54041. if (!this._boundingInfo || !target._boundingInfo) {
  54042. return false;
  54043. }
  54044. if (this._sps._bSphereOnly) {
  54045. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54046. }
  54047. return this._boundingInfo.intersects(target._boundingInfo, false);
  54048. };
  54049. return SolidParticle;
  54050. }());
  54051. BABYLON.SolidParticle = SolidParticle;
  54052. var ModelShape = (function () {
  54053. /**
  54054. * 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.
  54055. * SPS internal tool, don't use it manually.
  54056. */
  54057. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  54058. this.shapeID = id;
  54059. this._shape = shape;
  54060. this._shapeUV = shapeUV;
  54061. this._positionFunction = posFunction;
  54062. this._vertexFunction = vtxFunction;
  54063. }
  54064. return ModelShape;
  54065. }());
  54066. BABYLON.ModelShape = ModelShape;
  54067. })(BABYLON || (BABYLON = {}));
  54068. //# sourceMappingURL=babylon.solidParticle.js.map
  54069. var BABYLON;
  54070. (function (BABYLON) {
  54071. /**
  54072. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54073. */
  54074. var SolidParticleSystem = (function () {
  54075. /**
  54076. * Creates a SPS (Solid Particle System) object.
  54077. * `name` (String) is the SPS name, this will be the underlying mesh name.
  54078. * `scene` (Scene) is the scene in which the SPS is added.
  54079. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  54080. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  54081. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  54082. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54083. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54084. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54085. */
  54086. function SolidParticleSystem(name, scene, options) {
  54087. // public members
  54088. /**
  54089. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54090. * Example : var p = SPS.particles[i];
  54091. */
  54092. this.particles = new Array();
  54093. /**
  54094. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54095. */
  54096. this.nbParticles = 0;
  54097. /**
  54098. * If the particles must ever face the camera (default false). Useful for planar particles.
  54099. */
  54100. this.billboard = false;
  54101. /**
  54102. * Recompute normals when adding a shape
  54103. */
  54104. this.recomputeNormals = true;
  54105. /**
  54106. * This a counter ofr your own usage. It's not set by any SPS functions.
  54107. */
  54108. this.counter = 0;
  54109. /**
  54110. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54111. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54112. */
  54113. this.vars = {};
  54114. this._positions = new Array();
  54115. this._indices = new Array();
  54116. this._normals = new Array();
  54117. this._colors = new Array();
  54118. this._uvs = new Array();
  54119. this._index = 0; // indices index
  54120. this._updatable = true;
  54121. this._pickable = false;
  54122. this._isVisibilityBoxLocked = false;
  54123. this._alwaysVisible = false;
  54124. this._shapeCounter = 0;
  54125. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  54126. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54127. this._computeParticleColor = true;
  54128. this._computeParticleTexture = true;
  54129. this._computeParticleRotation = true;
  54130. this._computeParticleVertex = false;
  54131. this._computeBoundingBox = false;
  54132. this._cam_axisZ = BABYLON.Vector3.Zero();
  54133. this._cam_axisY = BABYLON.Vector3.Zero();
  54134. this._cam_axisX = BABYLON.Vector3.Zero();
  54135. this._axisX = BABYLON.Axis.X;
  54136. this._axisY = BABYLON.Axis.Y;
  54137. this._axisZ = BABYLON.Axis.Z;
  54138. this._camDir = BABYLON.Vector3.Zero();
  54139. this._rotMatrix = new BABYLON.Matrix();
  54140. this._invertMatrix = new BABYLON.Matrix();
  54141. this._rotated = BABYLON.Vector3.Zero();
  54142. this._quaternion = new BABYLON.Quaternion();
  54143. this._vertex = BABYLON.Vector3.Zero();
  54144. this._normal = BABYLON.Vector3.Zero();
  54145. this._yaw = 0.0;
  54146. this._pitch = 0.0;
  54147. this._roll = 0.0;
  54148. this._halfroll = 0.0;
  54149. this._halfpitch = 0.0;
  54150. this._halfyaw = 0.0;
  54151. this._sinRoll = 0.0;
  54152. this._cosRoll = 0.0;
  54153. this._sinPitch = 0.0;
  54154. this._cosPitch = 0.0;
  54155. this._sinYaw = 0.0;
  54156. this._cosYaw = 0.0;
  54157. this._w = 0.0;
  54158. this._mustUnrotateFixedNormals = false;
  54159. this._minimum = BABYLON.Tmp.Vector3[0];
  54160. this._maximum = BABYLON.Tmp.Vector3[1];
  54161. this._scale = BABYLON.Tmp.Vector3[2];
  54162. this._translation = BABYLON.Tmp.Vector3[3];
  54163. this._minBbox = BABYLON.Tmp.Vector3[4];
  54164. this._maxBbox = BABYLON.Tmp.Vector3[5];
  54165. this._particlesIntersect = false;
  54166. this._bSphereOnly = false;
  54167. this._bSphereRadiusFactor = 1.0;
  54168. this.name = name;
  54169. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54170. this._camera = scene.activeCamera;
  54171. this._pickable = options ? options.isPickable : false;
  54172. this._particlesIntersect = options ? options.particleIntersection : false;
  54173. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54174. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54175. if (options && options.updatable) {
  54176. this._updatable = options.updatable;
  54177. }
  54178. else {
  54179. this._updatable = true;
  54180. }
  54181. if (this._pickable) {
  54182. this.pickedParticles = [];
  54183. }
  54184. }
  54185. /**
  54186. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54187. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54188. */
  54189. SolidParticleSystem.prototype.buildMesh = function () {
  54190. if (this.nbParticles === 0) {
  54191. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54192. this.addShape(triangle, 1);
  54193. triangle.dispose();
  54194. }
  54195. this._positions32 = new Float32Array(this._positions);
  54196. this._uvs32 = new Float32Array(this._uvs);
  54197. this._colors32 = new Float32Array(this._colors);
  54198. if (this.recomputeNormals) {
  54199. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54200. }
  54201. this._normals32 = new Float32Array(this._normals);
  54202. this._fixedNormal32 = new Float32Array(this._normals);
  54203. if (this._mustUnrotateFixedNormals) {
  54204. this._unrotateFixedNormals();
  54205. }
  54206. var vertexData = new BABYLON.VertexData();
  54207. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54208. vertexData.indices = this._indices;
  54209. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54210. if (this._uvs32) {
  54211. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54212. ;
  54213. }
  54214. if (this._colors32) {
  54215. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54216. }
  54217. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54218. vertexData.applyToMesh(mesh, this._updatable);
  54219. this.mesh = mesh;
  54220. this.mesh.isPickable = this._pickable;
  54221. // free memory
  54222. this._positions = null;
  54223. this._normals = null;
  54224. this._uvs = null;
  54225. this._colors = null;
  54226. if (!this._updatable) {
  54227. this.particles.length = 0;
  54228. }
  54229. return mesh;
  54230. };
  54231. /**
  54232. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54233. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54234. * Thus the particles generated from `digest()` have their property `position` set yet.
  54235. * `mesh` ( Mesh ) is the mesh to be digested
  54236. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54237. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54238. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54239. */
  54240. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54241. var size = (options && options.facetNb) || 1;
  54242. var number = (options && options.number);
  54243. var delta = (options && options.delta) || 0;
  54244. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54245. var meshInd = mesh.getIndices();
  54246. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54247. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54248. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54249. var f = 0; // facet counter
  54250. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54251. // compute size from number
  54252. if (number) {
  54253. number = (number > totalFacets) ? totalFacets : number;
  54254. size = Math.round(totalFacets / number);
  54255. delta = 0;
  54256. }
  54257. else {
  54258. size = (size > totalFacets) ? totalFacets : size;
  54259. }
  54260. var facetPos = []; // submesh positions
  54261. var facetInd = []; // submesh indices
  54262. var facetUV = []; // submesh UV
  54263. var facetCol = []; // submesh colors
  54264. var barycenter = BABYLON.Tmp.Vector3[0];
  54265. var rand;
  54266. var sizeO = size;
  54267. while (f < totalFacets) {
  54268. size = sizeO + Math.floor((1 + delta) * Math.random());
  54269. if (f > totalFacets - size) {
  54270. size = totalFacets - f;
  54271. }
  54272. // reset temp arrays
  54273. facetPos.length = 0;
  54274. facetInd.length = 0;
  54275. facetUV.length = 0;
  54276. facetCol.length = 0;
  54277. // iterate over "size" facets
  54278. var fi = 0;
  54279. for (var j = f * 3; j < (f + size) * 3; j++) {
  54280. facetInd.push(fi);
  54281. var i = meshInd[j];
  54282. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54283. if (meshUV) {
  54284. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54285. }
  54286. if (meshCol) {
  54287. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54288. }
  54289. fi++;
  54290. }
  54291. // create a model shape for each single particle
  54292. var idx = this.nbParticles;
  54293. var shape = this._posToShape(facetPos);
  54294. var shapeUV = this._uvsToShapeUV(facetUV);
  54295. // compute the barycenter of the shape
  54296. var v;
  54297. for (v = 0; v < shape.length; v++) {
  54298. barycenter.addInPlace(shape[v]);
  54299. }
  54300. barycenter.scaleInPlace(1 / shape.length);
  54301. // shift the shape from its barycenter to the origin
  54302. for (v = 0; v < shape.length; v++) {
  54303. shape[v].subtractInPlace(barycenter);
  54304. }
  54305. var bInfo;
  54306. if (this._particlesIntersect) {
  54307. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54308. }
  54309. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54310. // add the particle in the SPS
  54311. var currentPos = this._positions.length;
  54312. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54313. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  54314. // initialize the particle position
  54315. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54316. this._index += shape.length;
  54317. idx++;
  54318. this.nbParticles++;
  54319. this._shapeCounter++;
  54320. f += size;
  54321. }
  54322. return this;
  54323. };
  54324. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54325. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54326. var index = 0;
  54327. var idx = 0;
  54328. for (var p = 0; p < this.particles.length; p++) {
  54329. this._particle = this.particles[p];
  54330. this._shape = this._particle._model._shape;
  54331. if (this._particle.rotationQuaternion) {
  54332. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54333. }
  54334. else {
  54335. this._yaw = this._particle.rotation.y;
  54336. this._pitch = this._particle.rotation.x;
  54337. this._roll = this._particle.rotation.z;
  54338. this._quaternionRotationYPR();
  54339. }
  54340. this._quaternionToRotationMatrix();
  54341. this._rotMatrix.invertToRef(this._invertMatrix);
  54342. for (var pt = 0; pt < this._shape.length; pt++) {
  54343. idx = index + pt * 3;
  54344. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54345. this._fixedNormal32[idx] = this._normal.x;
  54346. this._fixedNormal32[idx + 1] = this._normal.y;
  54347. this._fixedNormal32[idx + 2] = this._normal.z;
  54348. }
  54349. index = idx + 3;
  54350. }
  54351. };
  54352. //reset copy
  54353. SolidParticleSystem.prototype._resetCopy = function () {
  54354. this._copy.position.x = 0;
  54355. this._copy.position.y = 0;
  54356. this._copy.position.z = 0;
  54357. this._copy.rotation.x = 0;
  54358. this._copy.rotation.y = 0;
  54359. this._copy.rotation.z = 0;
  54360. this._copy.rotationQuaternion = null;
  54361. this._copy.scaling.x = 1;
  54362. this._copy.scaling.y = 1;
  54363. this._copy.scaling.z = 1;
  54364. this._copy.uvs.x = 0;
  54365. this._copy.uvs.y = 0;
  54366. this._copy.uvs.z = 1;
  54367. this._copy.uvs.w = 1;
  54368. this._copy.color = null;
  54369. };
  54370. // _meshBuilder : inserts the shape model in the global SPS mesh
  54371. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54372. var i;
  54373. var u = 0;
  54374. var c = 0;
  54375. var n = 0;
  54376. this._resetCopy();
  54377. if (options && options.positionFunction) {
  54378. options.positionFunction(this._copy, idx, idxInShape);
  54379. this._mustUnrotateFixedNormals = true;
  54380. }
  54381. if (this._copy.rotationQuaternion) {
  54382. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54383. }
  54384. else {
  54385. this._yaw = this._copy.rotation.y;
  54386. this._pitch = this._copy.rotation.x;
  54387. this._roll = this._copy.rotation.z;
  54388. this._quaternionRotationYPR();
  54389. }
  54390. this._quaternionToRotationMatrix();
  54391. for (i = 0; i < shape.length; i++) {
  54392. this._vertex.x = shape[i].x;
  54393. this._vertex.y = shape[i].y;
  54394. this._vertex.z = shape[i].z;
  54395. if (options && options.vertexFunction) {
  54396. options.vertexFunction(this._copy, this._vertex, i);
  54397. }
  54398. this._vertex.x *= this._copy.scaling.x;
  54399. this._vertex.y *= this._copy.scaling.y;
  54400. this._vertex.z *= this._copy.scaling.z;
  54401. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54402. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54403. if (meshUV) {
  54404. 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);
  54405. u += 2;
  54406. }
  54407. if (this._copy.color) {
  54408. this._color = this._copy.color;
  54409. }
  54410. else if (meshCol && meshCol[c] !== undefined) {
  54411. this._color.r = meshCol[c];
  54412. this._color.g = meshCol[c + 1];
  54413. this._color.b = meshCol[c + 2];
  54414. this._color.a = meshCol[c + 3];
  54415. }
  54416. else {
  54417. this._color.r = 1;
  54418. this._color.g = 1;
  54419. this._color.b = 1;
  54420. this._color.a = 1;
  54421. }
  54422. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54423. c += 4;
  54424. if (!this.recomputeNormals && meshNor) {
  54425. this._normal.x = meshNor[n];
  54426. this._normal.y = meshNor[n + 1];
  54427. this._normal.z = meshNor[n + 2];
  54428. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54429. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54430. n += 3;
  54431. }
  54432. }
  54433. for (i = 0; i < meshInd.length; i++) {
  54434. indices.push(p + meshInd[i]);
  54435. }
  54436. if (this._pickable) {
  54437. var nbfaces = meshInd.length / 3;
  54438. for (i = 0; i < nbfaces; i++) {
  54439. this.pickedParticles.push({ idx: idx, faceId: i });
  54440. }
  54441. }
  54442. return this._copy;
  54443. };
  54444. // returns a shape array from positions array
  54445. SolidParticleSystem.prototype._posToShape = function (positions) {
  54446. var shape = [];
  54447. for (var i = 0; i < positions.length; i += 3) {
  54448. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54449. }
  54450. return shape;
  54451. };
  54452. // returns a shapeUV array from a Vector4 uvs
  54453. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54454. var shapeUV = [];
  54455. if (uvs) {
  54456. for (var i = 0; i < uvs.length; i++)
  54457. shapeUV.push(uvs[i]);
  54458. }
  54459. return shapeUV;
  54460. };
  54461. // adds a new particle object in the particles array
  54462. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  54463. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  54464. this.particles.push(sp);
  54465. return sp;
  54466. };
  54467. /**
  54468. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54469. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54470. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54471. * `nb` (positive integer) the number of particles to be created from this model
  54472. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54473. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54474. */
  54475. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54476. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54477. var meshInd = mesh.getIndices();
  54478. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54479. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54480. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54481. var bbInfo;
  54482. if (this._particlesIntersect) {
  54483. bbInfo = mesh.getBoundingInfo();
  54484. }
  54485. var shape = this._posToShape(meshPos);
  54486. var shapeUV = this._uvsToShapeUV(meshUV);
  54487. var posfunc = options ? options.positionFunction : null;
  54488. var vtxfunc = options ? options.vertexFunction : null;
  54489. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54490. // particles
  54491. var sp;
  54492. var currentCopy;
  54493. var idx = this.nbParticles;
  54494. for (var i = 0; i < nb; i++) {
  54495. var currentPos = this._positions.length;
  54496. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54497. if (this._updatable) {
  54498. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  54499. sp.position.copyFrom(currentCopy.position);
  54500. sp.rotation.copyFrom(currentCopy.rotation);
  54501. if (currentCopy.rotationQuaternion) {
  54502. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54503. }
  54504. if (currentCopy.color) {
  54505. sp.color.copyFrom(currentCopy.color);
  54506. }
  54507. sp.scaling.copyFrom(currentCopy.scaling);
  54508. sp.uvs.copyFrom(currentCopy.uvs);
  54509. }
  54510. this._index += shape.length;
  54511. idx++;
  54512. }
  54513. this.nbParticles += nb;
  54514. this._shapeCounter++;
  54515. return this._shapeCounter - 1;
  54516. };
  54517. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54518. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54519. this._resetCopy();
  54520. if (particle._model._positionFunction) {
  54521. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54522. }
  54523. if (this._copy.rotationQuaternion) {
  54524. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54525. }
  54526. else {
  54527. this._yaw = this._copy.rotation.y;
  54528. this._pitch = this._copy.rotation.x;
  54529. this._roll = this._copy.rotation.z;
  54530. this._quaternionRotationYPR();
  54531. }
  54532. this._quaternionToRotationMatrix();
  54533. this._shape = particle._model._shape;
  54534. for (var pt = 0; pt < this._shape.length; pt++) {
  54535. this._vertex.x = this._shape[pt].x;
  54536. this._vertex.y = this._shape[pt].y;
  54537. this._vertex.z = this._shape[pt].z;
  54538. if (particle._model._vertexFunction) {
  54539. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54540. }
  54541. this._vertex.x *= this._copy.scaling.x;
  54542. this._vertex.y *= this._copy.scaling.y;
  54543. this._vertex.z *= this._copy.scaling.z;
  54544. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54545. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54546. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54547. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54548. }
  54549. particle.position.x = 0.0;
  54550. particle.position.y = 0.0;
  54551. particle.position.z = 0.0;
  54552. particle.rotation.x = 0.0;
  54553. particle.rotation.y = 0.0;
  54554. particle.rotation.z = 0.0;
  54555. particle.rotationQuaternion = null;
  54556. particle.scaling.x = 1.0;
  54557. particle.scaling.y = 1.0;
  54558. particle.scaling.z = 1.0;
  54559. };
  54560. /**
  54561. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54562. * Returns the SPS.
  54563. */
  54564. SolidParticleSystem.prototype.rebuildMesh = function () {
  54565. for (var p = 0; p < this.particles.length; p++) {
  54566. this._rebuildParticle(this.particles[p]);
  54567. }
  54568. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54569. return this;
  54570. };
  54571. /**
  54572. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54573. * This method calls `updateParticle()` for each particle of the SPS.
  54574. * For an animated SPS, it is usually called within the render loop.
  54575. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54576. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54577. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54578. * Returns the SPS.
  54579. */
  54580. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54581. if (start === void 0) { start = 0; }
  54582. if (end === void 0) { end = this.nbParticles - 1; }
  54583. if (update === void 0) { update = true; }
  54584. if (!this._updatable) {
  54585. return;
  54586. }
  54587. // custom beforeUpdate
  54588. this.beforeUpdateParticles(start, end, update);
  54589. this._cam_axisX.x = 1.0;
  54590. this._cam_axisX.y = 0.0;
  54591. this._cam_axisX.z = 0.0;
  54592. this._cam_axisY.x = 0.0;
  54593. this._cam_axisY.y = 1.0;
  54594. this._cam_axisY.z = 0.0;
  54595. this._cam_axisZ.x = 0.0;
  54596. this._cam_axisZ.y = 0.0;
  54597. this._cam_axisZ.z = 1.0;
  54598. // if the particles will always face the camera
  54599. if (this.billboard) {
  54600. this.mesh.computeWorldMatrix(true);
  54601. // compute the camera position and un-rotate it by the current mesh rotation
  54602. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  54603. this._quaternionToRotationMatrix();
  54604. this._rotMatrix.invertToRef(this._invertMatrix);
  54605. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  54606. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54607. this._cam_axisZ.normalize();
  54608. // same for camera up vector extracted from the cam view matrix
  54609. var view = this._camera.getViewMatrix(true);
  54610. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54611. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54612. this._cam_axisY.normalize();
  54613. this._cam_axisX.normalize();
  54614. }
  54615. }
  54616. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54617. var idx = 0; // current position index in the global array positions32
  54618. var index = 0; // position start index in the global array positions32 of the current particle
  54619. var colidx = 0; // current color index in the global array colors32
  54620. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54621. var uvidx = 0; // current uv index in the global array uvs32
  54622. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54623. var pt = 0; // current index in the particle model shape
  54624. if (this.mesh.isFacetDataEnabled) {
  54625. this._computeBoundingBox = true;
  54626. }
  54627. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54628. if (this._computeBoundingBox) {
  54629. if (start == 0 && end == this.nbParticles - 1) {
  54630. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54631. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54632. }
  54633. else {
  54634. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54635. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54636. }
  54637. }
  54638. // particle loop
  54639. index = this.particles[start]._pos;
  54640. var vpos = (index / 3) | 0;
  54641. colorIndex = vpos * 4;
  54642. uvIndex = vpos * 2;
  54643. for (var p = start; p <= end; p++) {
  54644. this._particle = this.particles[p];
  54645. this._shape = this._particle._model._shape;
  54646. this._shapeUV = this._particle._model._shapeUV;
  54647. // call to custom user function to update the particle properties
  54648. this.updateParticle(this._particle);
  54649. if (this._particle.isVisible) {
  54650. // particle rotation matrix
  54651. if (this.billboard) {
  54652. this._particle.rotation.x = 0.0;
  54653. this._particle.rotation.y = 0.0;
  54654. }
  54655. if (this._computeParticleRotation || this.billboard) {
  54656. if (this._particle.rotationQuaternion) {
  54657. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54658. }
  54659. else {
  54660. this._yaw = this._particle.rotation.y;
  54661. this._pitch = this._particle.rotation.x;
  54662. this._roll = this._particle.rotation.z;
  54663. this._quaternionRotationYPR();
  54664. }
  54665. this._quaternionToRotationMatrix();
  54666. }
  54667. // particle vertex loop
  54668. for (pt = 0; pt < this._shape.length; pt++) {
  54669. idx = index + pt * 3;
  54670. colidx = colorIndex + pt * 4;
  54671. uvidx = uvIndex + pt * 2;
  54672. this._vertex.x = this._shape[pt].x;
  54673. this._vertex.y = this._shape[pt].y;
  54674. this._vertex.z = this._shape[pt].z;
  54675. if (this._computeParticleVertex) {
  54676. this.updateParticleVertex(this._particle, this._vertex, pt);
  54677. }
  54678. // positions
  54679. this._vertex.x *= this._particle.scaling.x;
  54680. this._vertex.y *= this._particle.scaling.y;
  54681. this._vertex.z *= this._particle.scaling.z;
  54682. 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];
  54683. 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;
  54684. 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;
  54685. 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;
  54686. 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;
  54687. 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;
  54688. 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;
  54689. if (this._computeBoundingBox) {
  54690. if (this._positions32[idx] < this._minimum.x) {
  54691. this._minimum.x = this._positions32[idx];
  54692. }
  54693. if (this._positions32[idx] > this._maximum.x) {
  54694. this._maximum.x = this._positions32[idx];
  54695. }
  54696. if (this._positions32[idx + 1] < this._minimum.y) {
  54697. this._minimum.y = this._positions32[idx + 1];
  54698. }
  54699. if (this._positions32[idx + 1] > this._maximum.y) {
  54700. this._maximum.y = this._positions32[idx + 1];
  54701. }
  54702. if (this._positions32[idx + 2] < this._minimum.z) {
  54703. this._minimum.z = this._positions32[idx + 2];
  54704. }
  54705. if (this._positions32[idx + 2] > this._maximum.z) {
  54706. this._maximum.z = this._positions32[idx + 2];
  54707. }
  54708. }
  54709. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54710. if (!this._computeParticleVertex) {
  54711. this._normal.x = this._fixedNormal32[idx];
  54712. this._normal.y = this._fixedNormal32[idx + 1];
  54713. this._normal.z = this._fixedNormal32[idx + 2];
  54714. 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]);
  54715. 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]);
  54716. 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]);
  54717. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54718. 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;
  54719. 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;
  54720. }
  54721. if (this._computeParticleColor) {
  54722. this._colors32[colidx] = this._particle.color.r;
  54723. this._colors32[colidx + 1] = this._particle.color.g;
  54724. this._colors32[colidx + 2] = this._particle.color.b;
  54725. this._colors32[colidx + 3] = this._particle.color.a;
  54726. }
  54727. if (this._computeParticleTexture) {
  54728. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54729. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54730. }
  54731. }
  54732. }
  54733. else {
  54734. for (pt = 0; pt < this._shape.length; pt++) {
  54735. idx = index + pt * 3;
  54736. colidx = colorIndex + pt * 4;
  54737. uvidx = uvIndex + pt * 2;
  54738. this._positions32[idx] = this._camera.position.x;
  54739. this._positions32[idx + 1] = this._camera.position.y;
  54740. this._positions32[idx + 2] = this._camera.position.z;
  54741. this._normals32[idx] = 0.0;
  54742. this._normals32[idx + 1] = 0.0;
  54743. this._normals32[idx + 2] = 0.0;
  54744. if (this._computeParticleColor) {
  54745. this._colors32[colidx] = this._particle.color.r;
  54746. this._colors32[colidx + 1] = this._particle.color.g;
  54747. this._colors32[colidx + 2] = this._particle.color.b;
  54748. this._colors32[colidx + 3] = this._particle.color.a;
  54749. }
  54750. if (this._computeParticleTexture) {
  54751. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54752. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54753. }
  54754. }
  54755. }
  54756. // if the particle intersections must be computed : update the bbInfo
  54757. if (this._particlesIntersect) {
  54758. var bInfo = this._particle._boundingInfo;
  54759. var bBox = bInfo.boundingBox;
  54760. var bSphere = bInfo.boundingSphere;
  54761. if (!this._bSphereOnly) {
  54762. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54763. for (var b = 0; b < bBox.vectors.length; b++) {
  54764. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54765. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54766. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54767. 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];
  54768. 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;
  54769. 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;
  54770. 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;
  54771. 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;
  54772. 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;
  54773. 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;
  54774. }
  54775. bBox._update(this.mesh._worldMatrix);
  54776. }
  54777. // place and scale the particle bouding sphere in the SPS local system, then update it
  54778. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54779. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54780. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54781. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54782. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54783. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54784. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54785. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54786. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54787. 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));
  54788. bSphere._update(this.mesh._worldMatrix);
  54789. }
  54790. // increment indexes for the next particle
  54791. index = idx + 3;
  54792. colorIndex = colidx + 4;
  54793. uvIndex = uvidx + 2;
  54794. }
  54795. // if the VBO must be updated
  54796. if (update) {
  54797. if (this._computeParticleColor) {
  54798. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54799. }
  54800. if (this._computeParticleTexture) {
  54801. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54802. }
  54803. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54804. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54805. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54806. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54807. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54808. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  54809. for (var i = 0; i < this._normals32.length; i++) {
  54810. this._fixedNormal32[i] = this._normals32[i];
  54811. }
  54812. }
  54813. if (!this.mesh.areNormalsFrozen) {
  54814. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54815. }
  54816. }
  54817. }
  54818. if (this._computeBoundingBox) {
  54819. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54820. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54821. }
  54822. this.afterUpdateParticles(start, end, update);
  54823. return this;
  54824. };
  54825. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54826. this._halfroll = this._roll * 0.5;
  54827. this._halfpitch = this._pitch * 0.5;
  54828. this._halfyaw = this._yaw * 0.5;
  54829. this._sinRoll = Math.sin(this._halfroll);
  54830. this._cosRoll = Math.cos(this._halfroll);
  54831. this._sinPitch = Math.sin(this._halfpitch);
  54832. this._cosPitch = Math.cos(this._halfpitch);
  54833. this._sinYaw = Math.sin(this._halfyaw);
  54834. this._cosYaw = Math.cos(this._halfyaw);
  54835. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54836. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54837. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54838. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54839. };
  54840. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54841. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54842. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54843. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54844. this._rotMatrix.m[3] = 0;
  54845. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54846. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54847. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54848. this._rotMatrix.m[7] = 0;
  54849. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54850. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54851. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54852. this._rotMatrix.m[11] = 0;
  54853. this._rotMatrix.m[12] = 0;
  54854. this._rotMatrix.m[13] = 0;
  54855. this._rotMatrix.m[14] = 0;
  54856. this._rotMatrix.m[15] = 1.0;
  54857. };
  54858. /**
  54859. * Disposes the SPS.
  54860. * Returns nothing.
  54861. */
  54862. SolidParticleSystem.prototype.dispose = function () {
  54863. this.mesh.dispose();
  54864. this.vars = null;
  54865. // drop references to internal big arrays for the GC
  54866. this._positions = null;
  54867. this._indices = null;
  54868. this._normals = null;
  54869. this._uvs = null;
  54870. this._colors = null;
  54871. this._positions32 = null;
  54872. this._normals32 = null;
  54873. this._fixedNormal32 = null;
  54874. this._uvs32 = null;
  54875. this._colors32 = null;
  54876. this.pickedParticles = null;
  54877. };
  54878. /**
  54879. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54880. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54881. * Returns the SPS.
  54882. */
  54883. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54884. if (!this._isVisibilityBoxLocked) {
  54885. this.mesh.refreshBoundingInfo();
  54886. }
  54887. return this;
  54888. };
  54889. /**
  54890. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54891. * @param size the size (float) of the visibility box
  54892. * note : this doesn't lock the SPS mesh bounding box.
  54893. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54894. */
  54895. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54896. var vis = size / 2;
  54897. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54898. };
  54899. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54900. // getter and setter
  54901. get: function () {
  54902. return this._alwaysVisible;
  54903. },
  54904. /**
  54905. * Sets the SPS as always visible or not
  54906. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54907. */
  54908. set: function (val) {
  54909. this._alwaysVisible = val;
  54910. this.mesh.alwaysSelectAsActiveMesh = val;
  54911. },
  54912. enumerable: true,
  54913. configurable: true
  54914. });
  54915. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54916. get: function () {
  54917. return this._isVisibilityBoxLocked;
  54918. },
  54919. /**
  54920. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54921. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54922. */
  54923. set: function (val) {
  54924. this._isVisibilityBoxLocked = val;
  54925. this.mesh.getBoundingInfo().isLocked = val;
  54926. },
  54927. enumerable: true,
  54928. configurable: true
  54929. });
  54930. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54931. // getters
  54932. get: function () {
  54933. return this._computeParticleRotation;
  54934. },
  54935. // Optimizer setters
  54936. /**
  54937. * Tells to `setParticles()` to compute the particle rotations or not.
  54938. * Default value : true. The SPS is faster when it's set to false.
  54939. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54940. */
  54941. set: function (val) {
  54942. this._computeParticleRotation = val;
  54943. },
  54944. enumerable: true,
  54945. configurable: true
  54946. });
  54947. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54948. get: function () {
  54949. return this._computeParticleColor;
  54950. },
  54951. /**
  54952. * Tells to `setParticles()` to compute the particle colors or not.
  54953. * Default value : true. The SPS is faster when it's set to false.
  54954. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54955. */
  54956. set: function (val) {
  54957. this._computeParticleColor = val;
  54958. },
  54959. enumerable: true,
  54960. configurable: true
  54961. });
  54962. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54963. get: function () {
  54964. return this._computeParticleTexture;
  54965. },
  54966. /**
  54967. * Tells to `setParticles()` to compute the particle textures or not.
  54968. * Default value : true. The SPS is faster when it's set to false.
  54969. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54970. */
  54971. set: function (val) {
  54972. this._computeParticleTexture = val;
  54973. },
  54974. enumerable: true,
  54975. configurable: true
  54976. });
  54977. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54978. get: function () {
  54979. return this._computeParticleVertex;
  54980. },
  54981. /**
  54982. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54983. * Default value : false. The SPS is faster when it's set to false.
  54984. * Note : the particle custom vertex positions aren't stored values.
  54985. */
  54986. set: function (val) {
  54987. this._computeParticleVertex = val;
  54988. },
  54989. enumerable: true,
  54990. configurable: true
  54991. });
  54992. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54993. get: function () {
  54994. return this._computeBoundingBox;
  54995. },
  54996. /**
  54997. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54998. */
  54999. set: function (val) {
  55000. this._computeBoundingBox = val;
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. // =======================================================================
  55006. // Particle behavior logic
  55007. // these following methods may be overwritten by the user to fit his needs
  55008. /**
  55009. * This function does nothing. It may be overwritten to set all the particle first values.
  55010. * The SPS doesn't call this function, you may have to call it by your own.
  55011. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55012. */
  55013. SolidParticleSystem.prototype.initParticles = function () {
  55014. };
  55015. /**
  55016. * This function does nothing. It may be overwritten to recycle a particle.
  55017. * The SPS doesn't call this function, you may have to call it by your own.
  55018. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55019. */
  55020. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55021. return particle;
  55022. };
  55023. /**
  55024. * Updates a particle : this function should be overwritten by the user.
  55025. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55026. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55027. * ex : just set a particle position or velocity and recycle conditions
  55028. */
  55029. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55030. return particle;
  55031. };
  55032. /**
  55033. * Updates a vertex of a particle : it can be overwritten by the user.
  55034. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55035. * @param particle the current particle
  55036. * @param vertex the current index of the current particle
  55037. * @param pt the index of the current vertex in the particle shape
  55038. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55039. * ex : just set a vertex particle position
  55040. */
  55041. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55042. return vertex;
  55043. };
  55044. /**
  55045. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55046. * This does nothing and may be overwritten by the user.
  55047. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55048. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55049. * @param update the boolean update value actually passed to setParticles()
  55050. */
  55051. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55052. };
  55053. /**
  55054. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55055. * This will be passed three parameters.
  55056. * This does nothing and may be overwritten by the user.
  55057. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55058. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55059. * @param update the boolean update value actually passed to setParticles()
  55060. */
  55061. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55062. };
  55063. return SolidParticleSystem;
  55064. }());
  55065. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55066. })(BABYLON || (BABYLON = {}));
  55067. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55068. var BABYLON;
  55069. (function (BABYLON) {
  55070. var Internals;
  55071. (function (Internals) {
  55072. var FileFaceOrientation = (function () {
  55073. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  55074. this.name = name;
  55075. this.worldAxisForNormal = worldAxisForNormal;
  55076. this.worldAxisForFileX = worldAxisForFileX;
  55077. this.worldAxisForFileY = worldAxisForFileY;
  55078. }
  55079. return FileFaceOrientation;
  55080. }());
  55081. ;
  55082. /**
  55083. * Helper class dealing with the extraction of spherical polynomial dataArray
  55084. * from a cube map.
  55085. */
  55086. var CubeMapToSphericalPolynomialTools = (function () {
  55087. function CubeMapToSphericalPolynomialTools() {
  55088. }
  55089. /**
  55090. * Converts a cubemap to the according Spherical Polynomial data.
  55091. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55092. *
  55093. * @param cubeInfo The Cube map to extract the information from.
  55094. * @return The Spherical Polynomial data.
  55095. */
  55096. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  55097. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  55098. var totalSolidAngle = 0.0;
  55099. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  55100. var du = 2.0 / cubeInfo.size;
  55101. var dv = du;
  55102. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  55103. var minUV = du * 0.5 - 1.0;
  55104. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55105. var fileFace = this.FileFaces[faceIndex];
  55106. var dataArray = cubeInfo[fileFace.name];
  55107. var v = minUV;
  55108. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  55109. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  55110. // Because SP is still linear, so summation is fine in that basis.
  55111. for (var y = 0; y < cubeInfo.size; y++) {
  55112. var u = minUV;
  55113. for (var x = 0; x < cubeInfo.size; x++) {
  55114. // World direction (not normalised)
  55115. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  55116. worldDirection.normalize();
  55117. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55118. if (1) {
  55119. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  55120. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  55121. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  55122. var color = new BABYLON.Color3(r, g, b);
  55123. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55124. }
  55125. else {
  55126. if (faceIndex == 0) {
  55127. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55128. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55129. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55130. }
  55131. else if (faceIndex == 1) {
  55132. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55133. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55134. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55135. }
  55136. else if (faceIndex == 2) {
  55137. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55138. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55139. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55140. }
  55141. else if (faceIndex == 3) {
  55142. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55143. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55144. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55145. }
  55146. else if (faceIndex == 4) {
  55147. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55148. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55149. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55150. }
  55151. else if (faceIndex == 5) {
  55152. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55153. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55154. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55155. }
  55156. 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]);
  55157. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55158. }
  55159. totalSolidAngle += deltaSolidAngle;
  55160. u += du;
  55161. }
  55162. v += dv;
  55163. }
  55164. }
  55165. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  55166. var correction = correctSolidAngle / totalSolidAngle;
  55167. sphericalHarmonics.scale(correction);
  55168. // Additionally scale by pi -- audit needed
  55169. sphericalHarmonics.scale(1.0 / Math.PI);
  55170. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55171. };
  55172. return CubeMapToSphericalPolynomialTools;
  55173. }());
  55174. CubeMapToSphericalPolynomialTools.FileFaces = [
  55175. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55176. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55177. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55178. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55179. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55180. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55181. ];
  55182. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55184. })(BABYLON || (BABYLON = {}));
  55185. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  55186. var BABYLON;
  55187. (function (BABYLON) {
  55188. var Internals;
  55189. (function (Internals) {
  55190. /**
  55191. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55192. */
  55193. var PanoramaToCubeMapTools = (function () {
  55194. function PanoramaToCubeMapTools() {
  55195. }
  55196. /**
  55197. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55198. *
  55199. * @param float32Array The source data.
  55200. * @param inputWidth The width of the input panorama.
  55201. * @param inputhHeight The height of the input panorama.
  55202. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55203. * @return The cubemap data
  55204. */
  55205. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55206. if (!float32Array) {
  55207. throw "ConvertPanoramaToCubemap: input cannot be null";
  55208. }
  55209. if (float32Array.length != inputWidth * inputHeight * 3) {
  55210. throw "ConvertPanoramaToCubemap: input size is wrong";
  55211. }
  55212. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55213. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55214. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55215. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55216. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55217. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55218. return {
  55219. front: textureFront,
  55220. back: textureBack,
  55221. left: textureLeft,
  55222. right: textureRight,
  55223. up: textureUp,
  55224. down: textureDown,
  55225. size: size
  55226. };
  55227. };
  55228. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55229. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55230. var textureArray = new Float32Array(buffer);
  55231. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55232. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55233. var dy = 1 / texSize;
  55234. var fy = 0;
  55235. for (var y = 0; y < texSize; y++) {
  55236. var xv1 = faceData[0];
  55237. var xv2 = faceData[2];
  55238. for (var x = 0; x < texSize; x++) {
  55239. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55240. v.normalize();
  55241. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55242. // 3 channels per pixels
  55243. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55244. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55245. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55246. xv1 = xv1.add(rotDX1);
  55247. xv2 = xv2.add(rotDX2);
  55248. }
  55249. fy += dy;
  55250. }
  55251. return textureArray;
  55252. };
  55253. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55254. var theta = Math.atan2(vDir.z, vDir.x);
  55255. var phi = Math.acos(vDir.y);
  55256. while (theta < -Math.PI)
  55257. theta += 2 * Math.PI;
  55258. while (theta > Math.PI)
  55259. theta -= 2 * Math.PI;
  55260. var dx = theta / Math.PI;
  55261. var dy = phi / Math.PI;
  55262. // recenter.
  55263. dx = dx * 0.5 + 0.5;
  55264. var px = Math.round(dx * inputWidth);
  55265. if (px < 0)
  55266. px = 0;
  55267. else if (px >= inputWidth)
  55268. px = inputWidth - 1;
  55269. var py = Math.round(dy * inputHeight);
  55270. if (py < 0)
  55271. py = 0;
  55272. else if (py >= inputHeight)
  55273. py = inputHeight - 1;
  55274. var inputY = (inputHeight - py - 1);
  55275. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55276. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55277. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55278. return {
  55279. r: r,
  55280. g: g,
  55281. b: b
  55282. };
  55283. };
  55284. return PanoramaToCubeMapTools;
  55285. }());
  55286. PanoramaToCubeMapTools.FACE_FRONT = [
  55287. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55288. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55289. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55290. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55291. ];
  55292. PanoramaToCubeMapTools.FACE_BACK = [
  55293. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55294. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55295. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55296. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55297. ];
  55298. PanoramaToCubeMapTools.FACE_RIGHT = [
  55299. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55300. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55301. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55302. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55303. ];
  55304. PanoramaToCubeMapTools.FACE_LEFT = [
  55305. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55306. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55307. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55308. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55309. ];
  55310. PanoramaToCubeMapTools.FACE_DOWN = [
  55311. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55312. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55313. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55314. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55315. ];
  55316. PanoramaToCubeMapTools.FACE_UP = [
  55317. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55318. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55319. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55320. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55321. ];
  55322. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55323. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55324. })(BABYLON || (BABYLON = {}));
  55325. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  55326. var BABYLON;
  55327. (function (BABYLON) {
  55328. var Internals;
  55329. (function (Internals) {
  55330. ;
  55331. /**
  55332. * This groups tools to convert HDR texture to native colors array.
  55333. */
  55334. var HDRTools = (function () {
  55335. function HDRTools() {
  55336. }
  55337. HDRTools.Ldexp = function (mantissa, exponent) {
  55338. if (exponent > 1023) {
  55339. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55340. }
  55341. if (exponent < -1074) {
  55342. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55343. }
  55344. return mantissa * Math.pow(2, exponent);
  55345. };
  55346. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55347. if (exponent > 0) {
  55348. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55349. float32array[index + 0] = red * exponent;
  55350. float32array[index + 1] = green * exponent;
  55351. float32array[index + 2] = blue * exponent;
  55352. }
  55353. else {
  55354. float32array[index + 0] = 0;
  55355. float32array[index + 1] = 0;
  55356. float32array[index + 2] = 0;
  55357. }
  55358. };
  55359. HDRTools.readStringLine = function (uint8array, startIndex) {
  55360. var line = "";
  55361. var character = "";
  55362. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55363. character = String.fromCharCode(uint8array[i]);
  55364. if (character == "\n") {
  55365. break;
  55366. }
  55367. line += character;
  55368. }
  55369. return line;
  55370. };
  55371. /**
  55372. * Reads header information from an RGBE texture stored in a native array.
  55373. * More information on this format are available here:
  55374. * https://en.wikipedia.org/wiki/RGBE_image_format
  55375. *
  55376. * @param uint8array The binary file stored in native array.
  55377. * @return The header information.
  55378. */
  55379. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55380. var height = 0;
  55381. var width = 0;
  55382. var line = this.readStringLine(uint8array, 0);
  55383. if (line[0] != '#' || line[1] != '?') {
  55384. throw "Bad HDR Format.";
  55385. }
  55386. var endOfHeader = false;
  55387. var findFormat = false;
  55388. var lineIndex = 0;
  55389. do {
  55390. lineIndex += (line.length + 1);
  55391. line = this.readStringLine(uint8array, lineIndex);
  55392. if (line == "FORMAT=32-bit_rle_rgbe") {
  55393. findFormat = true;
  55394. }
  55395. else if (line.length == 0) {
  55396. endOfHeader = true;
  55397. }
  55398. } while (!endOfHeader);
  55399. if (!findFormat) {
  55400. throw "HDR Bad header format, unsupported FORMAT";
  55401. }
  55402. lineIndex += (line.length + 1);
  55403. line = this.readStringLine(uint8array, lineIndex);
  55404. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55405. var match = sizeRegexp.exec(line);
  55406. // TODO. Support +Y and -X if needed.
  55407. if (match.length < 3) {
  55408. throw "HDR Bad header format, no size";
  55409. }
  55410. width = parseInt(match[2]);
  55411. height = parseInt(match[1]);
  55412. if (width < 8 || width > 0x7fff) {
  55413. throw "HDR Bad header format, unsupported size";
  55414. }
  55415. lineIndex += (line.length + 1);
  55416. return {
  55417. height: height,
  55418. width: width,
  55419. dataPosition: lineIndex
  55420. };
  55421. };
  55422. /**
  55423. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55424. * This RGBE texture needs to store the information as a panorama.
  55425. *
  55426. * More information on this format are available here:
  55427. * https://en.wikipedia.org/wiki/RGBE_image_format
  55428. *
  55429. * @param buffer The binary file stored in an array buffer.
  55430. * @param size The expected size of the extracted cubemap.
  55431. * @return The Cube Map information.
  55432. */
  55433. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55434. var uint8array = new Uint8Array(buffer);
  55435. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55436. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55437. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55438. return cubeMapData;
  55439. };
  55440. /**
  55441. * Returns the pixels data extracted from an RGBE texture.
  55442. * This pixels will be stored left to right up to down in the R G B order in one array.
  55443. *
  55444. * More information on this format are available here:
  55445. * https://en.wikipedia.org/wiki/RGBE_image_format
  55446. *
  55447. * @param uint8array The binary file stored in an array buffer.
  55448. * @param hdrInfo The header information of the file.
  55449. * @return The pixels data in RGB right to left up to down order.
  55450. */
  55451. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55452. // Keep for multi format supports.
  55453. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55454. };
  55455. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55456. var num_scanlines = hdrInfo.height;
  55457. var scanline_width = hdrInfo.width;
  55458. var a, b, c, d, count;
  55459. var dataIndex = hdrInfo.dataPosition;
  55460. var index = 0, endIndex = 0, i = 0;
  55461. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55462. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55463. // 3 channels of 4 bytes per pixel in float.
  55464. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55465. var resultArray = new Float32Array(resultBuffer);
  55466. // read in each successive scanline
  55467. while (num_scanlines > 0) {
  55468. a = uint8array[dataIndex++];
  55469. b = uint8array[dataIndex++];
  55470. c = uint8array[dataIndex++];
  55471. d = uint8array[dataIndex++];
  55472. if (a != 2 || b != 2 || (c & 0x80)) {
  55473. // this file is not run length encoded
  55474. throw "HDR Bad header format, not RLE";
  55475. }
  55476. if (((c << 8) | d) != scanline_width) {
  55477. throw "HDR Bad header format, wrong scan line width";
  55478. }
  55479. index = 0;
  55480. // read each of the four channels for the scanline into the buffer
  55481. for (i = 0; i < 4; i++) {
  55482. endIndex = (i + 1) * scanline_width;
  55483. while (index < endIndex) {
  55484. a = uint8array[dataIndex++];
  55485. b = uint8array[dataIndex++];
  55486. if (a > 128) {
  55487. // a run of the same value
  55488. count = a - 128;
  55489. if ((count == 0) || (count > endIndex - index)) {
  55490. throw "HDR Bad Format, bad scanline data (run)";
  55491. }
  55492. while (count-- > 0) {
  55493. scanLineArray[index++] = b;
  55494. }
  55495. }
  55496. else {
  55497. // a non-run
  55498. count = a;
  55499. if ((count == 0) || (count > endIndex - index)) {
  55500. throw "HDR Bad Format, bad scanline data (non-run)";
  55501. }
  55502. scanLineArray[index++] = b;
  55503. if (--count > 0) {
  55504. for (var j = 0; j < count; j++) {
  55505. scanLineArray[index++] = uint8array[dataIndex++];
  55506. }
  55507. }
  55508. }
  55509. }
  55510. }
  55511. // now convert data from buffer into floats
  55512. for (i = 0; i < scanline_width; i++) {
  55513. a = scanLineArray[i];
  55514. b = scanLineArray[i + scanline_width];
  55515. c = scanLineArray[i + 2 * scanline_width];
  55516. d = scanLineArray[i + 3 * scanline_width];
  55517. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55518. }
  55519. num_scanlines--;
  55520. }
  55521. return resultArray;
  55522. };
  55523. return HDRTools;
  55524. }());
  55525. Internals.HDRTools = HDRTools;
  55526. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55527. })(BABYLON || (BABYLON = {}));
  55528. //# sourceMappingURL=babylon.tools.hdr.js.map
  55529. //_______________________________________________________________
  55530. // Extracted from CubeMapGen:
  55531. // https://code.google.com/archive/p/cubemapgen/
  55532. //
  55533. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55534. //_______________________________________________________________
  55535. var BABYLON;
  55536. (function (BABYLON) {
  55537. var Internals;
  55538. (function (Internals) {
  55539. /**
  55540. * The bounding box information used during the conversion process.
  55541. */
  55542. var CMGBoundinBox = (function () {
  55543. function CMGBoundinBox() {
  55544. this.min = new BABYLON.Vector3(0, 0, 0);
  55545. this.max = new BABYLON.Vector3(0, 0, 0);
  55546. this.clear();
  55547. }
  55548. CMGBoundinBox.prototype.clear = function () {
  55549. this.min.x = CMGBoundinBox.MAX;
  55550. this.min.y = CMGBoundinBox.MAX;
  55551. this.min.z = CMGBoundinBox.MAX;
  55552. this.max.x = CMGBoundinBox.MIN;
  55553. this.max.y = CMGBoundinBox.MIN;
  55554. this.max.z = CMGBoundinBox.MIN;
  55555. };
  55556. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55557. this.min.x = Math.min(this.min.x, x);
  55558. this.min.y = Math.min(this.min.y, y);
  55559. this.min.z = Math.min(this.min.z, z);
  55560. this.max.x = Math.max(this.max.x, x);
  55561. this.max.y = Math.max(this.max.y, y);
  55562. this.max.z = Math.max(this.max.z, z);
  55563. };
  55564. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55565. this.min.x = Math.max(this.min.x, x);
  55566. this.min.y = Math.max(this.min.y, y);
  55567. this.min.z = Math.max(this.min.z, z);
  55568. };
  55569. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55570. this.max.x = Math.min(this.max.x, x);
  55571. this.max.y = Math.min(this.max.y, y);
  55572. this.max.z = Math.min(this.max.z, z);
  55573. };
  55574. CMGBoundinBox.prototype.empty = function () {
  55575. if ((this.min.x > this.max.y) ||
  55576. (this.min.y > this.max.y) ||
  55577. (this.min.z > this.max.y)) {
  55578. return true;
  55579. }
  55580. else {
  55581. return false;
  55582. }
  55583. };
  55584. return CMGBoundinBox;
  55585. }());
  55586. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55587. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55588. /**
  55589. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55590. * required by the glossinees of a material.
  55591. *
  55592. * This only supports the cosine drop power as well as Warp fixup generation method.
  55593. *
  55594. * This is using the process from CubeMapGen described here:
  55595. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55596. */
  55597. var PMREMGenerator = (function () {
  55598. /**
  55599. * Constructor of the generator.
  55600. *
  55601. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55602. * @param inputSize The size of the cubemap faces
  55603. * @param outputSize The size of the output cubemap faces
  55604. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55605. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55606. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55607. * @param specularPower The max specular level of the desired cubemap
  55608. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55609. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55610. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55611. */
  55612. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55613. this.input = input;
  55614. this.inputSize = inputSize;
  55615. this.outputSize = outputSize;
  55616. this.maxNumMipLevels = maxNumMipLevels;
  55617. this.numChannels = numChannels;
  55618. this.isFloat = isFloat;
  55619. this.specularPower = specularPower;
  55620. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55621. this.excludeBase = excludeBase;
  55622. this.fixup = fixup;
  55623. this._outputSurface = [];
  55624. this._numMipLevels = 0;
  55625. }
  55626. /**
  55627. * Launches the filter process and return the result.
  55628. *
  55629. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55630. */
  55631. PMREMGenerator.prototype.filterCubeMap = function () {
  55632. // Init cubemap processor
  55633. this.init();
  55634. // Filters the cubemap
  55635. this.filterCubeMapMipChain();
  55636. // Returns the filtered mips.
  55637. return this._outputSurface;
  55638. };
  55639. PMREMGenerator.prototype.init = function () {
  55640. var i;
  55641. var j;
  55642. var mipLevelSize;
  55643. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55644. if (this.maxNumMipLevels == 0) {
  55645. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55646. }
  55647. //first miplevel size
  55648. mipLevelSize = this.outputSize;
  55649. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55650. for (j = 0; j < this.maxNumMipLevels; j++) {
  55651. this._outputSurface.length++;
  55652. this._outputSurface[j] = [];
  55653. //Iterate over faces for output images
  55654. for (i = 0; i < 6; i++) {
  55655. this._outputSurface[j].length++;
  55656. // Initializes a new array for the output.
  55657. if (this.isFloat) {
  55658. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55659. }
  55660. else {
  55661. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55662. }
  55663. }
  55664. //next mip level is half size
  55665. mipLevelSize >>= 1;
  55666. this._numMipLevels++;
  55667. //terminate if mip chain becomes too small
  55668. if (mipLevelSize == 0) {
  55669. this.maxNumMipLevels = j;
  55670. return;
  55671. }
  55672. }
  55673. };
  55674. //--------------------------------------------------------------------------------------
  55675. //Cube map filtering and mip chain generation.
  55676. // the cube map filtereing is specified using a number of parameters:
  55677. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55678. // indicates the region of the hemisphere to filter over for each tap.
  55679. //
  55680. // Note that the top mip level is also a filtered version of the original input images
  55681. // as well in order to create mip chains for diffuse environment illumination.
  55682. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55683. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55684. //
  55685. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55686. // is a_InitialMipAngle
  55687. //
  55688. // The angle for the subsequent levels of the mip chain are specified by their parents
  55689. // filtering angle and a per-level scale and bias
  55690. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55691. //
  55692. //--------------------------------------------------------------------------------------
  55693. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55694. // First, take count of the lighting model to modify SpecularPower
  55695. // 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;
  55696. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55697. //Cone angle start (for generating subsequent mip levels)
  55698. var currentSpecularPower = this.specularPower;
  55699. //Build filter lookup tables based on the source miplevel size
  55700. this.precomputeFilterLookupTables(this.inputSize);
  55701. // Note that we need to filter the first level before generating mipmap
  55702. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55703. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55704. // TODO : Write a function to copy and scale the base mipmap in output
  55705. // I am just lazy here and just put a high specular power value, and do some if.
  55706. if (this.excludeBase && (levelIndex == 0)) {
  55707. // 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).
  55708. currentSpecularPower = 100000.0;
  55709. }
  55710. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55711. var srcCubeImage = this.input;
  55712. var dstCubeImage = this._outputSurface[levelIndex];
  55713. var dstSize = this.outputSize >> levelIndex;
  55714. // Compute required angle.
  55715. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55716. // filter cube surfaces
  55717. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55718. // fix seams
  55719. if (this.fixup) {
  55720. this.fixupCubeEdges(dstCubeImage, dstSize);
  55721. }
  55722. // Decrease the specular power to generate the mipmap chain
  55723. // TODO : Use another method for Exclude (see first comment at start of the function
  55724. if (this.excludeBase && (levelIndex == 0)) {
  55725. currentSpecularPower = this.specularPower;
  55726. }
  55727. currentSpecularPower *= this.cosinePowerDropPerMip;
  55728. }
  55729. };
  55730. //--------------------------------------------------------------------------------------
  55731. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55732. // It allow to optimize the texel to access base on the specular power.
  55733. //--------------------------------------------------------------------------------------
  55734. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55735. // We want to find the alpha such that:
  55736. // cos(alpha)^cosinePower = epsilon
  55737. // That's: acos(epsilon^(1/cosinePower))
  55738. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55739. var angle = 180.0;
  55740. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55741. angle *= 180.0 / Math.PI; // Convert to degree
  55742. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55743. return angle;
  55744. };
  55745. //--------------------------------------------------------------------------------------
  55746. //Builds the following lookup tables prior to filtering:
  55747. // -normalizer cube map
  55748. // -tap weight lookup table
  55749. //
  55750. //--------------------------------------------------------------------------------------
  55751. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55752. var srcTexelAngle;
  55753. var iCubeFace;
  55754. //clear pre-existing normalizer cube map
  55755. this._normCubeMap = [];
  55756. //Normalized vectors per cubeface and per-texel solid angle
  55757. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55758. };
  55759. //--------------------------------------------------------------------------------------
  55760. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55761. //
  55762. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55763. //
  55764. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55765. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55766. // below
  55767. //--------------------------------------------------------------------------------------
  55768. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55769. var iCubeFace;
  55770. var u;
  55771. var v;
  55772. //iterate over cube faces
  55773. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55774. //First three channels for norm cube, and last channel for solid angle
  55775. this._normCubeMap.push(new Float32Array(size * size * 4));
  55776. //fast texture walk, build normalizer cube map
  55777. var facesData = this.input[iCubeFace];
  55778. for (v = 0; v < size; v++) {
  55779. for (u = 0; u < size; u++) {
  55780. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55781. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55782. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55783. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55784. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55785. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55786. }
  55787. }
  55788. }
  55789. };
  55790. //--------------------------------------------------------------------------------------
  55791. // Convert cubemap face texel coordinates and face idx to 3D vector
  55792. // note the U and V coords are integer coords and range from 0 to size-1
  55793. // this routine can be used to generate a normalizer cube map
  55794. //--------------------------------------------------------------------------------------
  55795. // SL BEGIN
  55796. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55797. var nvcU;
  55798. var nvcV;
  55799. var tempVec;
  55800. // Change from original AMD code
  55801. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55802. // + 0.5f is for texel center addressing
  55803. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55804. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55805. // warp fixup
  55806. if (fixup && size > 1) {
  55807. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55808. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55809. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55810. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55811. }
  55812. // Get current vector
  55813. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55814. // U contribution
  55815. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55816. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55817. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55818. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55819. // V contribution and Sum
  55820. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55821. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55822. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55823. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55824. //add face axis
  55825. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55826. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55827. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55828. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55829. //normalize vector
  55830. PMREMGenerator._vectorTemp.normalize();
  55831. return PMREMGenerator._vectorTemp;
  55832. };
  55833. //--------------------------------------------------------------------------------------
  55834. // Convert 3D vector to cubemap face texel coordinates and face idx
  55835. // note the U and V coords are integer coords and range from 0 to size-1
  55836. // this routine can be used to generate a normalizer cube map
  55837. //
  55838. // returns face IDX and texel coords
  55839. //--------------------------------------------------------------------------------------
  55840. // SL BEGIN
  55841. /*
  55842. Mapping Texture Coordinates to Cube Map Faces
  55843. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55844. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55845. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55846. map arrangement in Pixar's RenderMan package.
  55847. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55848. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55849. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55850. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55851. the major axis direction). The target column in the table below explains how the major axis direction
  55852. maps to the 2D image of a particular cube map target.
  55853. major axis
  55854. direction target sc tc ma
  55855. ---------- --------------------------------- --- --- ---
  55856. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55857. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55858. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55859. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55860. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55861. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55862. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55863. an updated (s,t) is calculated as follows
  55864. s = ( sc/|ma| + 1 ) / 2
  55865. t = ( tc/|ma| + 1 ) / 2
  55866. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55867. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55868. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55869. */
  55870. // Note this method return U and V in range from 0 to size-1
  55871. // SL END
  55872. // Store the information in vector3 for convenience (faceindex, u, v)
  55873. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55874. var maxCoord;
  55875. var faceIdx;
  55876. //absolute value 3
  55877. var absX = Math.abs(x);
  55878. var absY = Math.abs(y);
  55879. var absZ = Math.abs(z);
  55880. if (absX >= absY && absX >= absZ) {
  55881. maxCoord = absX;
  55882. if (x >= 0) {
  55883. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55884. }
  55885. else {
  55886. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55887. }
  55888. }
  55889. else if (absY >= absX && absY >= absZ) {
  55890. maxCoord = absY;
  55891. if (y >= 0) {
  55892. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55893. }
  55894. else {
  55895. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55896. }
  55897. }
  55898. else {
  55899. maxCoord = absZ;
  55900. if (z >= 0) {
  55901. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55902. }
  55903. else {
  55904. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55905. }
  55906. }
  55907. //divide through by max coord so face vector lies on cube face
  55908. var scale = 1 / maxCoord;
  55909. x *= scale;
  55910. y *= scale;
  55911. z *= scale;
  55912. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55913. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55914. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55915. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55916. // Modify original AMD code to return value from 0 to Size - 1
  55917. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55918. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55919. PMREMGenerator._vectorTemp.x = faceIdx;
  55920. PMREMGenerator._vectorTemp.y = u;
  55921. PMREMGenerator._vectorTemp.z = v;
  55922. return PMREMGenerator._vectorTemp;
  55923. };
  55924. //--------------------------------------------------------------------------------------
  55925. //Original code from Ignacio CastaÒo
  55926. // This formula is from Manne ÷hrstrˆm's thesis.
  55927. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55928. // cube face and return the area of the projection of that portion on the
  55929. // surface of the sphere.
  55930. //--------------------------------------------------------------------------------------
  55931. PMREMGenerator.prototype.areaElement = function (x, y) {
  55932. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55933. };
  55934. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55935. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55936. // (+ 0.5f is for texel center addressing)
  55937. u = (2.0 * (u + 0.5) / size) - 1.0;
  55938. v = (2.0 * (v + 0.5) / size) - 1.0;
  55939. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55940. var invResolution = 1.0 / size;
  55941. // U and V are the -1..1 texture coordinate on the current face.
  55942. // Get projected area for this texel
  55943. var x0 = u - invResolution;
  55944. var y0 = v - invResolution;
  55945. var x1 = u + invResolution;
  55946. var y1 = v + invResolution;
  55947. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55948. return solidAngle;
  55949. };
  55950. //--------------------------------------------------------------------------------------
  55951. //The key to the speed of these filtering routines is to quickly define a per-face
  55952. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55953. // Later these pixels are selectively processed based on their dot products to see if
  55954. // they reside within the filtering cone.
  55955. //
  55956. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55957. // of the number of texels needed to be covered in width and height order to filter the
  55958. // region. the bounding box for the center taps face is defined first, and if the
  55959. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55960. // defined next
  55961. //--------------------------------------------------------------------------------------
  55962. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55963. // note that pixels within these regions may be rejected
  55964. // based on the anlge
  55965. var iCubeFace;
  55966. var u;
  55967. var v;
  55968. // bounding box per face to specify region to process
  55969. var filterExtents = [];
  55970. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55971. filterExtents.push(new CMGBoundinBox());
  55972. }
  55973. // min angle a src texel can cover (in degrees)
  55974. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55975. // angle about center tap to define filter cone
  55976. // filter angle is 1/2 the cone angle
  55977. var filterAngle = filterConeAngle / 2.0;
  55978. //ensure filter angle is larger than a texel
  55979. if (filterAngle < srcTexelAngle) {
  55980. filterAngle = srcTexelAngle;
  55981. }
  55982. //ensure filter cone is always smaller than the hemisphere
  55983. if (filterAngle > 90.0) {
  55984. filterAngle = 90.0;
  55985. }
  55986. // the maximum number of texels in 1D the filter cone angle will cover
  55987. // used to determine bounding box size for filter extents
  55988. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55989. // ensure conservative region always covers at least one texel
  55990. if (filterSize < 1) {
  55991. filterSize = 1;
  55992. }
  55993. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55994. // reside within the cone angle
  55995. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55996. // process required faces
  55997. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55998. //iterate over dst cube map face texel
  55999. for (v = 0; v < dstSize; v++) {
  56000. for (u = 0; u < dstSize; u++) {
  56001. //get center tap direction
  56002. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  56003. //clear old per-face filter extents
  56004. this.clearFilterExtents(filterExtents);
  56005. //define per-face filter extents
  56006. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  56007. //perform filtering of src faces using filter extents
  56008. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  56009. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  56010. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  56011. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  56012. }
  56013. }
  56014. }
  56015. };
  56016. //--------------------------------------------------------------------------------------
  56017. //Clear filter extents for the 6 cube map faces
  56018. //--------------------------------------------------------------------------------------
  56019. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  56020. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  56021. filterExtents[iCubeFaces].clear();
  56022. }
  56023. };
  56024. //--------------------------------------------------------------------------------------
  56025. //Define per-face bounding box filter extents
  56026. //
  56027. // These define conservative texel regions in each of the faces the filter can possibly
  56028. // process. When the pixels in the regions are actually processed, the dot product
  56029. // between the tap vector and the center tap vector is used to determine the weight of
  56030. // the tap and whether or not the tap is within the cone.
  56031. //
  56032. //--------------------------------------------------------------------------------------
  56033. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  56034. //neighboring face and bleed over amount, and width of BBOX for
  56035. // left, right, top, and bottom edges of this face
  56036. var bleedOverAmount = [0, 0, 0, 0];
  56037. var bleedOverBBoxMin = [0, 0, 0, 0];
  56038. var bleedOverBBoxMax = [0, 0, 0, 0];
  56039. var neighborFace;
  56040. var neighborEdge;
  56041. var oppositeFaceIdx;
  56042. //get face idx, and u, v info from center tap dir
  56043. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  56044. var faceIdx = result.x;
  56045. var u = result.y;
  56046. var v = result.z;
  56047. //define bbox size within face
  56048. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  56049. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  56050. filterExtents[faceIdx].clampMin(0, 0, 0);
  56051. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  56052. //u and v extent in face corresponding to center tap
  56053. var minU = filterExtents[faceIdx].min.x;
  56054. var minV = filterExtents[faceIdx].min.y;
  56055. var maxU = filterExtents[faceIdx].max.x;
  56056. var maxV = filterExtents[faceIdx].max.y;
  56057. //bleed over amounts for face across u=0 edge (left)
  56058. bleedOverAmount[0] = (bboxSize - u);
  56059. bleedOverBBoxMin[0] = minV;
  56060. bleedOverBBoxMax[0] = maxV;
  56061. //bleed over amounts for face across u=1 edge (right)
  56062. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  56063. bleedOverBBoxMin[1] = minV;
  56064. bleedOverBBoxMax[1] = maxV;
  56065. //bleed over to face across v=0 edge (up)
  56066. bleedOverAmount[2] = (bboxSize - v);
  56067. bleedOverBBoxMin[2] = minU;
  56068. bleedOverBBoxMax[2] = maxU;
  56069. //bleed over to face across v=1 edge (down)
  56070. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  56071. bleedOverBBoxMin[3] = minU;
  56072. bleedOverBBoxMax[3] = maxU;
  56073. //compute bleed over regions in neighboring faces
  56074. for (var i = 0; i < 4; i++) {
  56075. if (bleedOverAmount[i] > 0) {
  56076. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  56077. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  56078. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  56079. // be flipped: the cases are
  56080. // if a left edge mates with a left or bottom edge on the neighbor
  56081. // if a top edge mates with a top or right edge on the neighbor
  56082. // if a right edge mates with a right or top edge on the neighbor
  56083. // if a bottom edge mates with a bottom or left edge on the neighbor
  56084. //Seeing as the edges are enumerated as follows
  56085. // left =0
  56086. // right =1
  56087. // top =2
  56088. // bottom =3
  56089. //
  56090. // so if the edge enums are the same, or the sum of the enums == 3,
  56091. // the bbox needs to be flipped
  56092. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  56093. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  56094. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  56095. }
  56096. //The way the bounding box is extended onto the neighboring face
  56097. // depends on which edge of neighboring face abuts with this one
  56098. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  56099. case PMREMGenerator.CP_EDGE_LEFT:
  56100. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  56101. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56102. break;
  56103. case PMREMGenerator.CP_EDGE_RIGHT:
  56104. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  56105. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56106. break;
  56107. case PMREMGenerator.CP_EDGE_TOP:
  56108. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  56109. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  56110. break;
  56111. case PMREMGenerator.CP_EDGE_BOTTOM:
  56112. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  56113. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  56114. break;
  56115. }
  56116. //clamp filter extents in non-center tap faces to remain within surface
  56117. filterExtents[neighborFace].clampMin(0, 0, 0);
  56118. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  56119. }
  56120. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  56121. // from the center tap face, then process the opposite face entirely for now.
  56122. //Note that the cases in which this happens, what usually happens is that
  56123. // more than one edge bleeds onto the opposite face, and the bounding box
  56124. // encompasses the entire cube map face.
  56125. if (bleedOverAmount[i] > srcSize) {
  56126. //determine opposite face
  56127. switch (faceIdx) {
  56128. case PMREMGenerator.CP_FACE_X_POS:
  56129. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56130. break;
  56131. case PMREMGenerator.CP_FACE_X_NEG:
  56132. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  56133. break;
  56134. case PMREMGenerator.CP_FACE_Y_POS:
  56135. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56136. break;
  56137. case PMREMGenerator.CP_FACE_Y_NEG:
  56138. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56139. break;
  56140. case PMREMGenerator.CP_FACE_Z_POS:
  56141. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56142. break;
  56143. case PMREMGenerator.CP_FACE_Z_NEG:
  56144. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56145. break;
  56146. default:
  56147. break;
  56148. }
  56149. //just encompass entire face for now
  56150. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  56151. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  56152. }
  56153. }
  56154. };
  56155. //--------------------------------------------------------------------------------------
  56156. //ProcessFilterExtents
  56157. // Process bounding box in each cube face
  56158. //
  56159. //--------------------------------------------------------------------------------------
  56160. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  56161. //accumulators are 64-bit floats in order to have the precision needed
  56162. // over a summation of a large number of pixels
  56163. var dstAccum = [0, 0, 0, 0];
  56164. var weightAccum = 0;
  56165. var k = 0;
  56166. var nSrcChannels = this.numChannels;
  56167. // norm cube map and srcCubeMap have same face width
  56168. var faceWidth = srcSize;
  56169. //amount to add to pointer to move to next scanline in images
  56170. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  56171. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  56172. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  56173. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  56174. // iterate over cubefaces
  56175. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56176. //if bbox is non empty
  56177. if (!filterExtents[iFaceIdx].empty()) {
  56178. var uStart = filterExtents[iFaceIdx].min.x;
  56179. var vStart = filterExtents[iFaceIdx].min.y;
  56180. var uEnd = filterExtents[iFaceIdx].max.x;
  56181. var vEnd = filterExtents[iFaceIdx].max.y;
  56182. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56183. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56184. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56185. for (var v = vStart; v <= vEnd; v++) {
  56186. var normCubeRowWalk = 0;
  56187. var srcCubeRowWalk = 0;
  56188. for (var u = uStart; u <= uEnd; u++) {
  56189. //pointer to direction in cube map associated with texel
  56190. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56191. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56192. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56193. //check dot product to see if texel is within cone
  56194. var tapDotProd = texelVectX * centerTapDir.x +
  56195. texelVectY * centerTapDir.y +
  56196. texelVectZ * centerTapDir.z;
  56197. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56198. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56199. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56200. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56201. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56202. // so just adding one to specularpower do the trick.
  56203. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56204. //iterate over channels
  56205. for (k = 0; k < nSrcChannels; k++) {
  56206. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56207. srcCubeRowWalk++;
  56208. }
  56209. weightAccum += weight; //accumulate weight
  56210. }
  56211. else {
  56212. //step across source pixel
  56213. srcCubeRowWalk += nSrcChannels;
  56214. }
  56215. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56216. }
  56217. startIndexNormCubeMap += normCubePitch;
  56218. startIndexSrcCubeMap += srcCubePitch;
  56219. }
  56220. }
  56221. }
  56222. //divide through by weights if weight is non zero
  56223. if (weightAccum != 0.0) {
  56224. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56225. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56226. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56227. if (this.numChannels > 3) {
  56228. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56229. }
  56230. }
  56231. else {
  56232. // otherwise sample nearest
  56233. // get face idx and u, v texel coordinate in face
  56234. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56235. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56236. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56237. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56238. if (this.numChannels > 3) {
  56239. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56240. }
  56241. }
  56242. return PMREMGenerator._vectorTemp;
  56243. };
  56244. //--------------------------------------------------------------------------------------
  56245. // Fixup cube edges
  56246. //
  56247. // average texels on cube map faces across the edges
  56248. // WARP/BENT Method Only.
  56249. //--------------------------------------------------------------------------------------
  56250. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56251. var k;
  56252. var j;
  56253. var i;
  56254. var iFace;
  56255. var iCorner = 0;
  56256. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56257. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56258. // note that if functionality to filter across the three texels for each corner, then
  56259. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56260. var cornerPtr = [
  56261. [[], [], []],
  56262. [[], [], []],
  56263. [[], [], []],
  56264. [[], [], []],
  56265. [[], [], []],
  56266. [[], [], []],
  56267. [[], [], []],
  56268. [[], [], []]
  56269. ];
  56270. //if there is no fixup, or fixup width = 0, do nothing
  56271. if (cubeMapSize < 1) {
  56272. return;
  56273. }
  56274. //special case 1x1 cubemap, average face colors
  56275. if (cubeMapSize == 1) {
  56276. //iterate over channels
  56277. for (k = 0; k < this.numChannels; k++) {
  56278. var accum = 0.0;
  56279. //iterate over faces to accumulate face colors
  56280. for (iFace = 0; iFace < 6; iFace++) {
  56281. accum += cubeMap[iFace][k];
  56282. }
  56283. //compute average over 6 face colors
  56284. accum /= 6.0;
  56285. //iterate over faces to distribute face colors
  56286. for (iFace = 0; iFace < 6; iFace++) {
  56287. cubeMap[iFace][k] = accum;
  56288. }
  56289. }
  56290. return;
  56291. }
  56292. //iterate over faces to collect list of corner texel pointers
  56293. for (iFace = 0; iFace < 6; iFace++) {
  56294. //the 4 corner pointers for this face
  56295. faceCornerStartIndicies[0] = [iFace, 0];
  56296. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56297. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56298. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56299. //iterate over face corners to collect cube corner pointers
  56300. for (iCorner = 0; iCorner < 4; iCorner++) {
  56301. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56302. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56303. cornerNumPtrs[corner]++;
  56304. }
  56305. }
  56306. //iterate over corners to average across corner tap values
  56307. for (iCorner = 0; iCorner < 8; iCorner++) {
  56308. for (k = 0; k < this.numChannels; k++) {
  56309. var cornerTapAccum = 0.0;
  56310. //iterate over corner texels and average results
  56311. for (i = 0; i < 3; i++) {
  56312. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56313. }
  56314. //divide by 3 to compute average of corner tap values
  56315. cornerTapAccum *= (1.0 / 3.0);
  56316. //iterate over corner texels and average results
  56317. for (i = 0; i < 3; i++) {
  56318. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56319. }
  56320. }
  56321. }
  56322. //iterate over the twelve edges of the cube to average across edges
  56323. for (i = 0; i < 12; i++) {
  56324. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56325. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56326. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56327. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56328. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56329. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56330. var edgeWalk = 0;
  56331. var neighborEdgeWalk = 0;
  56332. //Determine walking pointers based on edge type
  56333. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56334. switch (edge) {
  56335. case PMREMGenerator.CP_EDGE_LEFT:
  56336. // no change to faceEdgeStartPtr
  56337. edgeWalk = this.numChannels * cubeMapSize;
  56338. break;
  56339. case PMREMGenerator.CP_EDGE_RIGHT:
  56340. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56341. edgeWalk = this.numChannels * cubeMapSize;
  56342. break;
  56343. case PMREMGenerator.CP_EDGE_TOP:
  56344. // no change to faceEdgeStartPtr
  56345. edgeWalk = this.numChannels;
  56346. break;
  56347. case PMREMGenerator.CP_EDGE_BOTTOM:
  56348. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56349. edgeWalk = this.numChannels;
  56350. break;
  56351. }
  56352. //For certain types of edge abutments, the neighbor edge walk needs to
  56353. // be flipped: the cases are
  56354. // if a left edge mates with a left or bottom edge on the neighbor
  56355. // if a top edge mates with a top or right edge on the neighbor
  56356. // if a right edge mates with a right or top edge on the neighbor
  56357. // if a bottom edge mates with a bottom or left edge on the neighbor
  56358. //Seeing as the edges are enumerated as follows
  56359. // left =0
  56360. // right =1
  56361. // top =2
  56362. // bottom =3
  56363. //
  56364. //If the edge enums are the same, or the sum of the enums == 3,
  56365. // the neighbor edge walk needs to be flipped
  56366. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56367. switch (neighborEdge) {
  56368. case PMREMGenerator.CP_EDGE_LEFT:
  56369. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56370. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56371. break;
  56372. case PMREMGenerator.CP_EDGE_RIGHT:
  56373. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56374. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56375. break;
  56376. case PMREMGenerator.CP_EDGE_TOP:
  56377. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56378. neighborEdgeWalk = -this.numChannels;
  56379. break;
  56380. case PMREMGenerator.CP_EDGE_BOTTOM:
  56381. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56382. neighborEdgeWalk = -this.numChannels;
  56383. break;
  56384. }
  56385. }
  56386. else {
  56387. //swapped direction neighbor edge walk
  56388. switch (neighborEdge) {
  56389. case PMREMGenerator.CP_EDGE_LEFT:
  56390. //no change to neighborEdgeStartPtr for this case since it points
  56391. // to the upper left corner already
  56392. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56393. break;
  56394. case PMREMGenerator.CP_EDGE_RIGHT:
  56395. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56396. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56397. break;
  56398. case PMREMGenerator.CP_EDGE_TOP:
  56399. //no change to neighborEdgeStartPtr for this case since it points
  56400. // to the upper left corner already
  56401. neighborEdgeWalk = this.numChannels;
  56402. break;
  56403. case PMREMGenerator.CP_EDGE_BOTTOM:
  56404. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56405. neighborEdgeWalk = this.numChannels;
  56406. break;
  56407. }
  56408. }
  56409. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56410. //nearby neighborhood
  56411. //step ahead one texel on edge
  56412. edgeStartIndex += edgeWalk;
  56413. neighborEdgeStartIndex += neighborEdgeWalk;
  56414. // note that this loop does not process the corner texels, since they have already been
  56415. // averaged across faces across earlier
  56416. for (j = 1; j < (cubeMapSize - 1); j++) {
  56417. //for each set of taps along edge, average them
  56418. // and rewrite the results into the edges
  56419. for (k = 0; k < this.numChannels; k++) {
  56420. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56421. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56422. //compute average of tap intensity values
  56423. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56424. //propagate average of taps to edge taps
  56425. cubeMap[face][edgeStartIndex + k] = avgTap;
  56426. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56427. }
  56428. edgeStartIndex += edgeWalk;
  56429. neighborEdgeStartIndex += neighborEdgeWalk;
  56430. }
  56431. }
  56432. };
  56433. return PMREMGenerator;
  56434. }());
  56435. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56436. PMREMGenerator.CP_UDIR = 0;
  56437. PMREMGenerator.CP_VDIR = 1;
  56438. PMREMGenerator.CP_FACEAXIS = 2;
  56439. //used to index cube faces
  56440. PMREMGenerator.CP_FACE_X_POS = 0;
  56441. PMREMGenerator.CP_FACE_X_NEG = 1;
  56442. PMREMGenerator.CP_FACE_Y_POS = 2;
  56443. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56444. PMREMGenerator.CP_FACE_Z_POS = 4;
  56445. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56446. //used to index image edges
  56447. // NOTE.. the actual number corresponding to the edge is important
  56448. // do not change these, or the code will break
  56449. //
  56450. // CP_EDGE_LEFT is u = 0
  56451. // CP_EDGE_RIGHT is u = width-1
  56452. // CP_EDGE_TOP is v = 0
  56453. // CP_EDGE_BOTTOM is v = height-1
  56454. PMREMGenerator.CP_EDGE_LEFT = 0;
  56455. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56456. PMREMGenerator.CP_EDGE_TOP = 2;
  56457. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56458. //corners of CUBE map (P or N specifys if it corresponds to the
  56459. // positive or negative direction each of X, Y, and Z
  56460. PMREMGenerator.CP_CORNER_NNN = 0;
  56461. PMREMGenerator.CP_CORNER_NNP = 1;
  56462. PMREMGenerator.CP_CORNER_NPN = 2;
  56463. PMREMGenerator.CP_CORNER_NPP = 3;
  56464. PMREMGenerator.CP_CORNER_PNN = 4;
  56465. PMREMGenerator.CP_CORNER_PNP = 5;
  56466. PMREMGenerator.CP_CORNER_PPN = 6;
  56467. PMREMGenerator.CP_CORNER_PPP = 7;
  56468. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56469. //3x2 matrices that map cube map indexing vectors in 3d
  56470. // (after face selection and divide through by the
  56471. // _ABSOLUTE VALUE_ of the max coord)
  56472. // into NVC space
  56473. //Note this currently assumes the D3D cube face ordering and orientation
  56474. PMREMGenerator._sgFace2DMapping = [
  56475. //XPOS face
  56476. [[0, 0, -1],
  56477. [0, -1, 0],
  56478. [1, 0, 0]],
  56479. //XNEG face
  56480. [[0, 0, 1],
  56481. [0, -1, 0],
  56482. [-1, 0, 0]],
  56483. //YPOS face
  56484. [[1, 0, 0],
  56485. [0, 0, 1],
  56486. [0, 1, 0]],
  56487. //YNEG face
  56488. [[1, 0, 0],
  56489. [0, 0, -1],
  56490. [0, -1, 0]],
  56491. //ZPOS face
  56492. [[1, 0, 0],
  56493. [0, -1, 0],
  56494. [0, 0, 1]],
  56495. //ZNEG face
  56496. [[-1, 0, 0],
  56497. [0, -1, 0],
  56498. [0, 0, -1]],
  56499. ];
  56500. //------------------------------------------------------------------------------
  56501. // D3D cube map face specification
  56502. // mapping from 3D x,y,z cube map lookup coordinates
  56503. // to 2D within face u,v coordinates
  56504. //
  56505. // --------------------> U direction
  56506. // | (within-face texture space)
  56507. // | _____
  56508. // | | |
  56509. // | | +Y |
  56510. // | _____|_____|_____ _____
  56511. // | | | | | |
  56512. // | | -X | +Z | +X | -Z |
  56513. // | |_____|_____|_____|_____|
  56514. // | | |
  56515. // | | -Y |
  56516. // | |_____|
  56517. // |
  56518. // v V direction
  56519. // (within-face texture space)
  56520. //------------------------------------------------------------------------------
  56521. //Information about neighbors and how texture coorrdinates change across faces
  56522. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56523. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56524. //Note this currently assumes the D3D cube face ordering and orientation
  56525. PMREMGenerator._sgCubeNgh = [
  56526. //XPOS face
  56527. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56528. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56529. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56530. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56531. //XNEG face
  56532. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56533. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56534. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56535. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56536. //YPOS face
  56537. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56538. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56539. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56540. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56541. //YNEG face
  56542. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56543. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56544. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56545. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56546. //ZPOS face
  56547. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56548. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56549. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56550. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56551. //ZNEG face
  56552. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56553. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56554. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56555. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56556. ];
  56557. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56558. // this table is used to average over the edges.
  56559. PMREMGenerator._sgCubeEdgeList = [
  56560. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56561. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56562. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56563. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56564. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56565. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56566. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56567. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56568. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56569. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56570. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56571. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56572. ];
  56573. //Information about which of the 8 cube corners are correspond to the
  56574. // the 4 corners in each cube face
  56575. // the order is upper left, upper right, lower left, lower right
  56576. PMREMGenerator._sgCubeCornerList = [
  56577. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56578. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56579. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56580. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56581. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56582. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56583. ];
  56584. Internals.PMREMGenerator = PMREMGenerator;
  56585. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56586. })(BABYLON || (BABYLON = {}));
  56587. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  56588. var BABYLON;
  56589. (function (BABYLON) {
  56590. /**
  56591. * This represents a texture coming from an HDR input.
  56592. *
  56593. * The only supported format is currently panorama picture stored in RGBE format.
  56594. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56595. */
  56596. var HDRCubeTexture = (function (_super) {
  56597. __extends(HDRCubeTexture, _super);
  56598. /**
  56599. * Instantiates an HDRTexture from the following parameters.
  56600. *
  56601. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56602. * @param scene The scene the texture will be used in
  56603. * @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.
  56604. * @param noMipmap Forces to not generate the mipmap if true
  56605. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56606. * @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)
  56607. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56608. */
  56609. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56610. if (noMipmap === void 0) { noMipmap = false; }
  56611. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56612. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56613. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56614. if (onLoad === void 0) { onLoad = null; }
  56615. if (onError === void 0) { onError = null; }
  56616. var _this = _super.call(this, scene) || this;
  56617. _this._useInGammaSpace = false;
  56618. _this._generateHarmonics = true;
  56619. _this._isBABYLONPreprocessed = false;
  56620. _this._onLoad = null;
  56621. _this._onError = null;
  56622. /**
  56623. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56624. */
  56625. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56626. /**
  56627. * The spherical polynomial data extracted from the texture.
  56628. */
  56629. _this.sphericalPolynomial = null;
  56630. /**
  56631. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56632. * This is usefull at run time to apply the good shader.
  56633. */
  56634. _this.isPMREM = false;
  56635. if (!url) {
  56636. return _this;
  56637. }
  56638. _this.name = url;
  56639. _this.url = url;
  56640. _this.hasAlpha = false;
  56641. _this.isCube = true;
  56642. _this._textureMatrix = BABYLON.Matrix.Identity();
  56643. _this._onLoad = onLoad;
  56644. _this._onError = onError;
  56645. if (size) {
  56646. _this._isBABYLONPreprocessed = false;
  56647. _this._noMipmap = noMipmap;
  56648. _this._size = size;
  56649. _this._useInGammaSpace = useInGammaSpace;
  56650. _this._usePMREMGenerator = usePMREMGenerator &&
  56651. scene.getEngine().getCaps().textureLOD &&
  56652. _this.getScene().getEngine().getCaps().textureFloat &&
  56653. !_this._useInGammaSpace;
  56654. }
  56655. else {
  56656. _this._isBABYLONPreprocessed = true;
  56657. _this._noMipmap = false;
  56658. _this._useInGammaSpace = false;
  56659. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56660. _this.getScene().getEngine().getCaps().textureFloat &&
  56661. !_this._useInGammaSpace;
  56662. }
  56663. _this.isPMREM = _this._usePMREMGenerator;
  56664. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56665. if (!_this._texture) {
  56666. if (!scene.useDelayedTextureLoading) {
  56667. _this.loadTexture();
  56668. }
  56669. else {
  56670. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56671. }
  56672. }
  56673. return _this;
  56674. }
  56675. /**
  56676. * Occurs when the file is a preprocessed .babylon.hdr file.
  56677. */
  56678. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56679. var _this = this;
  56680. var mipLevels = 0;
  56681. var floatArrayView = null;
  56682. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56683. var mips = [];
  56684. var startIndex = 30;
  56685. for (var level = 0; level < mipLevels; level++) {
  56686. mips.push([]);
  56687. // Fill each pixel of the mip level.
  56688. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56689. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56690. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56691. mips[level].push(faceData);
  56692. startIndex += faceSize;
  56693. }
  56694. }
  56695. return mips;
  56696. } : null;
  56697. var callback = function (buffer) {
  56698. // Create Native Array Views
  56699. var intArrayView = new Int32Array(buffer);
  56700. floatArrayView = new Float32Array(buffer);
  56701. // Fill header.
  56702. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56703. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56704. // Update Texture Information.
  56705. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56706. // Fill polynomial information.
  56707. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56708. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56709. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56710. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56711. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56712. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56713. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56714. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56715. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56716. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56717. // Fill pixel data.
  56718. mipLevels = intArrayView[29]; // Number of mip levels.
  56719. var startIndex = 30;
  56720. var data = [];
  56721. var faceSize = Math.pow(_this._size, 2) * 3;
  56722. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56723. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56724. startIndex += faceSize;
  56725. }
  56726. var results = [];
  56727. var byteArray = null;
  56728. // Push each faces.
  56729. for (var k = 0; k < 6; k++) {
  56730. var dataFace = null;
  56731. // If special cases.
  56732. if (!mipmapGenerator) {
  56733. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56734. dataFace = data[j];
  56735. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56736. // 3 channels of 1 bytes per pixel in bytes.
  56737. var byteBuffer = new ArrayBuffer(faceSize);
  56738. byteArray = new Uint8Array(byteBuffer);
  56739. }
  56740. for (var i = 0; i < _this._size * _this._size; i++) {
  56741. // Put in gamma space if requested.
  56742. if (_this._useInGammaSpace) {
  56743. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56744. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56745. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56746. }
  56747. // Convert to int texture for fallback.
  56748. if (byteArray) {
  56749. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56750. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56751. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56752. // May use luminance instead if the result is not accurate.
  56753. var max = Math.max(Math.max(r, g), b);
  56754. if (max > 255) {
  56755. var scale = 255 / max;
  56756. r *= scale;
  56757. g *= scale;
  56758. b *= scale;
  56759. }
  56760. byteArray[(i * 3) + 0] = r;
  56761. byteArray[(i * 3) + 1] = g;
  56762. byteArray[(i * 3) + 2] = b;
  56763. }
  56764. }
  56765. }
  56766. else {
  56767. dataFace = data[k];
  56768. }
  56769. // Fill the array accordingly.
  56770. if (byteArray) {
  56771. results.push(byteArray);
  56772. }
  56773. else {
  56774. results.push(dataFace);
  56775. }
  56776. }
  56777. return results;
  56778. };
  56779. 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);
  56780. };
  56781. /**
  56782. * Occurs when the file is raw .hdr file.
  56783. */
  56784. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56785. var _this = this;
  56786. var callback = function (buffer) {
  56787. // Extract the raw linear data.
  56788. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56789. // Generate harmonics if needed.
  56790. if (_this._generateHarmonics) {
  56791. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56792. }
  56793. var results = [];
  56794. var byteArray = null;
  56795. // Push each faces.
  56796. for (var j = 0; j < 6; j++) {
  56797. // Create uintarray fallback.
  56798. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56799. // 3 channels of 1 bytes per pixel in bytes.
  56800. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56801. byteArray = new Uint8Array(byteBuffer);
  56802. }
  56803. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56804. // If special cases.
  56805. if (_this._useInGammaSpace || byteArray) {
  56806. for (var i = 0; i < _this._size * _this._size; i++) {
  56807. // Put in gamma space if requested.
  56808. if (_this._useInGammaSpace) {
  56809. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56810. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56811. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56812. }
  56813. // Convert to int texture for fallback.
  56814. if (byteArray) {
  56815. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56816. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56817. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56818. // May use luminance instead if the result is not accurate.
  56819. var max = Math.max(Math.max(r, g), b);
  56820. if (max > 255) {
  56821. var scale = 255 / max;
  56822. r *= scale;
  56823. g *= scale;
  56824. b *= scale;
  56825. }
  56826. byteArray[(i * 3) + 0] = r;
  56827. byteArray[(i * 3) + 1] = g;
  56828. byteArray[(i * 3) + 2] = b;
  56829. }
  56830. }
  56831. }
  56832. if (byteArray) {
  56833. results.push(byteArray);
  56834. }
  56835. else {
  56836. results.push(dataFace);
  56837. }
  56838. }
  56839. return results;
  56840. };
  56841. var mipmapGenerator = null;
  56842. if (!this._noMipmap &&
  56843. this._usePMREMGenerator) {
  56844. mipmapGenerator = function (data) {
  56845. // Custom setup of the generator matching with the PBR shader values.
  56846. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56847. return generator.filterCubeMap();
  56848. };
  56849. }
  56850. 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);
  56851. };
  56852. /**
  56853. * Starts the loading process of the texture.
  56854. */
  56855. HDRCubeTexture.prototype.loadTexture = function () {
  56856. if (this._isBABYLONPreprocessed) {
  56857. this.loadBabylonTexture();
  56858. }
  56859. else {
  56860. this.loadHDRTexture();
  56861. }
  56862. };
  56863. HDRCubeTexture.prototype.clone = function () {
  56864. var size = this._isBABYLONPreprocessed ? null : this._size;
  56865. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56866. // Base texture
  56867. newTexture.level = this.level;
  56868. newTexture.wrapU = this.wrapU;
  56869. newTexture.wrapV = this.wrapV;
  56870. newTexture.coordinatesIndex = this.coordinatesIndex;
  56871. newTexture.coordinatesMode = this.coordinatesMode;
  56872. return newTexture;
  56873. };
  56874. // Methods
  56875. HDRCubeTexture.prototype.delayLoad = function () {
  56876. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56877. return;
  56878. }
  56879. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56880. this._texture = this._getFromCache(this.url, this._noMipmap);
  56881. if (!this._texture) {
  56882. this.loadTexture();
  56883. }
  56884. };
  56885. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56886. return this._textureMatrix;
  56887. };
  56888. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56889. var texture = null;
  56890. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56891. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56892. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56893. texture.name = parsedTexture.name;
  56894. texture.hasAlpha = parsedTexture.hasAlpha;
  56895. texture.level = parsedTexture.level;
  56896. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56897. }
  56898. return texture;
  56899. };
  56900. HDRCubeTexture.prototype.serialize = function () {
  56901. if (!this.name) {
  56902. return null;
  56903. }
  56904. var serializationObject = {};
  56905. serializationObject.name = this.name;
  56906. serializationObject.hasAlpha = this.hasAlpha;
  56907. serializationObject.isCube = true;
  56908. serializationObject.level = this.level;
  56909. serializationObject.size = this._size;
  56910. serializationObject.coordinatesMode = this.coordinatesMode;
  56911. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56912. serializationObject.generateHarmonics = this._generateHarmonics;
  56913. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56914. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56915. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56916. serializationObject.noMipmap = this._noMipmap;
  56917. return serializationObject;
  56918. };
  56919. /**
  56920. * Saves as a file the data contained in the texture in a binary format.
  56921. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56922. * as the spherical used in the lighting.
  56923. * @param url The HDR file url.
  56924. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56925. * @param onError Method called if any error happens during download.
  56926. * @return The packed binary data.
  56927. */
  56928. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56929. if (onError === void 0) { onError = null; }
  56930. var callback = function (buffer) {
  56931. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56932. // Returns a URL you can use as a href.
  56933. var objUrl = window.URL.createObjectURL(data);
  56934. // Simulates a link to it and click to dowload.
  56935. var a = document.createElement("a");
  56936. document.body.appendChild(a);
  56937. a.style.display = "none";
  56938. a.href = objUrl;
  56939. a.download = "envmap.babylon.hdr";
  56940. a.click();
  56941. };
  56942. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56943. };
  56944. /**
  56945. * Serializes the data contained in the texture in a binary format.
  56946. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56947. * as the spherical used in the lighting.
  56948. * @param url The HDR file url.
  56949. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56950. * @param onError Method called if any error happens during download.
  56951. * @return The packed binary data.
  56952. */
  56953. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56954. if (onError === void 0) { onError = null; }
  56955. // Needs the url tho create the texture.
  56956. if (!url) {
  56957. return null;
  56958. }
  56959. // Check Power of two size.
  56960. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56961. return null;
  56962. }
  56963. var getDataCallback = function (dataBuffer) {
  56964. // Extract the raw linear data.
  56965. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56966. // Generate harmonics if needed.
  56967. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56968. // Generate seamless faces
  56969. var mipGeneratorArray = [];
  56970. // Data are known to be in +X +Y +Z -X -Y -Z
  56971. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56972. mipGeneratorArray.push(cubeData.right); // +X
  56973. mipGeneratorArray.push(cubeData.left); // -X
  56974. mipGeneratorArray.push(cubeData.up); // +Y
  56975. mipGeneratorArray.push(cubeData.down); // -Y
  56976. mipGeneratorArray.push(cubeData.front); // +Z
  56977. mipGeneratorArray.push(cubeData.back); // -Z
  56978. // Custom setup of the generator matching with the PBR shader values.
  56979. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56980. var mippedData = generator.filterCubeMap();
  56981. // Compute required byte length.
  56982. var byteLength = 1 * 4; // Raw Data Version int32.
  56983. byteLength += 4; // CubeMap max mip face size int32.
  56984. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56985. // Add data size.
  56986. byteLength += 4; // Number of mip levels int32.
  56987. for (var level = 0; level < mippedData.length; level++) {
  56988. var mipSize = size >> level;
  56989. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56990. }
  56991. // Prepare binary structure.
  56992. var buffer = new ArrayBuffer(byteLength);
  56993. var intArrayView = new Int32Array(buffer);
  56994. var floatArrayView = new Float32Array(buffer);
  56995. // Fill header.
  56996. intArrayView[0] = 1; // Version 1.
  56997. intArrayView[1] = size; // CubeMap max mip face size.
  56998. // Fill polynomial information.
  56999. sphericalPolynomial.x.toArray(floatArrayView, 2);
  57000. sphericalPolynomial.y.toArray(floatArrayView, 5);
  57001. sphericalPolynomial.z.toArray(floatArrayView, 8);
  57002. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  57003. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  57004. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  57005. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  57006. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  57007. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  57008. // Fill pixel data.
  57009. intArrayView[29] = mippedData.length; // Number of mip levels.
  57010. var startIndex = 30;
  57011. for (var level = 0; level < mippedData.length; level++) {
  57012. // Fill each pixel of the mip level.
  57013. var faceSize = Math.pow(size >> level, 2) * 3;
  57014. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57015. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  57016. startIndex += faceSize;
  57017. }
  57018. }
  57019. // Callback.
  57020. callback(buffer);
  57021. };
  57022. // Download and process.
  57023. BABYLON.Tools.LoadFile(url, function (data) {
  57024. getDataCallback(data);
  57025. }, null, null, true, onError);
  57026. };
  57027. return HDRCubeTexture;
  57028. }(BABYLON.BaseTexture));
  57029. HDRCubeTexture._facesMapping = [
  57030. "right",
  57031. "up",
  57032. "front",
  57033. "left",
  57034. "down",
  57035. "back"
  57036. ];
  57037. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57038. })(BABYLON || (BABYLON = {}));
  57039. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  57040. var BABYLON;
  57041. (function (BABYLON) {
  57042. var Debug;
  57043. (function (Debug) {
  57044. /**
  57045. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  57046. */
  57047. var SkeletonViewer = (function () {
  57048. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  57049. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  57050. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  57051. this.skeleton = skeleton;
  57052. this.mesh = mesh;
  57053. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  57054. this.renderingGroupId = renderingGroupId;
  57055. this.color = BABYLON.Color3.White();
  57056. this._debugLines = [];
  57057. this._isEnabled = false;
  57058. this._scene = scene;
  57059. this.update();
  57060. this._renderFunction = this.update.bind(this);
  57061. }
  57062. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  57063. get: function () {
  57064. return this._isEnabled;
  57065. },
  57066. set: function (value) {
  57067. if (this._isEnabled === value) {
  57068. return;
  57069. }
  57070. this._isEnabled = value;
  57071. if (value) {
  57072. this._scene.registerBeforeRender(this._renderFunction);
  57073. }
  57074. else {
  57075. this._scene.unregisterBeforeRender(this._renderFunction);
  57076. }
  57077. },
  57078. enumerable: true,
  57079. configurable: true
  57080. });
  57081. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  57082. if (x === void 0) { x = 0; }
  57083. if (y === void 0) { y = 0; }
  57084. if (z === void 0) { z = 0; }
  57085. var tmat = BABYLON.Tmp.Matrix[0];
  57086. var parentBone = bone.getParent();
  57087. tmat.copyFrom(bone.getLocalMatrix());
  57088. if (x !== 0 || y !== 0 || z !== 0) {
  57089. var tmat2 = BABYLON.Tmp.Matrix[1];
  57090. BABYLON.Matrix.IdentityToRef(tmat2);
  57091. tmat2.m[12] = x;
  57092. tmat2.m[13] = y;
  57093. tmat2.m[14] = z;
  57094. tmat2.multiplyToRef(tmat, tmat);
  57095. }
  57096. if (parentBone) {
  57097. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  57098. }
  57099. tmat.multiplyToRef(meshMat, tmat);
  57100. position.x = tmat.m[12];
  57101. position.y = tmat.m[13];
  57102. position.z = tmat.m[14];
  57103. };
  57104. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  57105. var len = bones.length;
  57106. for (var i = 0; i < len; i++) {
  57107. var bone = bones[i];
  57108. var points = this._debugLines[i];
  57109. if (!points) {
  57110. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57111. this._debugLines[i] = points;
  57112. }
  57113. this._getBonePosition(points[0], bone, meshMat);
  57114. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  57115. }
  57116. };
  57117. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  57118. var len = bones.length;
  57119. var boneNum = 0;
  57120. for (var i = len - 1; i >= 0; i--) {
  57121. var childBone = bones[i];
  57122. var parentBone = childBone.getParent();
  57123. if (!parentBone) {
  57124. continue;
  57125. }
  57126. var points = this._debugLines[boneNum];
  57127. if (!points) {
  57128. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57129. this._debugLines[boneNum] = points;
  57130. }
  57131. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  57132. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  57133. boneNum++;
  57134. }
  57135. };
  57136. SkeletonViewer.prototype.update = function () {
  57137. if (this.autoUpdateBonesMatrices) {
  57138. this.skeleton.computeAbsoluteTransforms();
  57139. }
  57140. if (this.skeleton.bones[0].length === undefined) {
  57141. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57142. }
  57143. else {
  57144. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57145. }
  57146. if (!this._debugMesh) {
  57147. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  57148. this._debugMesh.renderingGroupId = this.renderingGroupId;
  57149. }
  57150. else {
  57151. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  57152. }
  57153. this._debugMesh.color = this.color;
  57154. };
  57155. SkeletonViewer.prototype.dispose = function () {
  57156. if (this._debugMesh) {
  57157. this.isEnabled = false;
  57158. this._debugMesh.dispose();
  57159. this._debugMesh = null;
  57160. }
  57161. };
  57162. return SkeletonViewer;
  57163. }());
  57164. Debug.SkeletonViewer = SkeletonViewer;
  57165. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57166. })(BABYLON || (BABYLON = {}));
  57167. //# sourceMappingURL=babylon.skeletonViewer.js.map
  57168. var BABYLON;
  57169. (function (BABYLON) {
  57170. var Debug;
  57171. (function (Debug) {
  57172. var AxesViewer = (function () {
  57173. function AxesViewer(scene, scaleLines) {
  57174. if (scaleLines === void 0) { scaleLines = 1; }
  57175. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57176. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57177. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57178. this.scaleLines = 1;
  57179. this.scaleLines = scaleLines;
  57180. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  57181. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  57182. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  57183. this._xmesh.renderingGroupId = 2;
  57184. this._ymesh.renderingGroupId = 2;
  57185. this._zmesh.renderingGroupId = 2;
  57186. this._xmesh.material.checkReadyOnlyOnce = true;
  57187. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  57188. this._ymesh.material.checkReadyOnlyOnce = true;
  57189. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  57190. this._zmesh.material.checkReadyOnlyOnce = true;
  57191. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  57192. this.scene = scene;
  57193. }
  57194. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  57195. var scaleLines = this.scaleLines;
  57196. var point1 = this._xline[0];
  57197. var point2 = this._xline[1];
  57198. point1.x = position.x;
  57199. point1.y = position.y;
  57200. point1.z = position.z;
  57201. point2.x = point1.x + xaxis.x * scaleLines;
  57202. point2.y = point1.y + xaxis.y * scaleLines;
  57203. point2.z = point1.z + xaxis.z * scaleLines;
  57204. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57205. point1 = this._yline[0];
  57206. point2 = this._yline[1];
  57207. point1.x = position.x;
  57208. point1.y = position.y;
  57209. point1.z = position.z;
  57210. point2.x = point1.x + yaxis.x * scaleLines;
  57211. point2.y = point1.y + yaxis.y * scaleLines;
  57212. point2.z = point1.z + yaxis.z * scaleLines;
  57213. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57214. point1 = this._zline[0];
  57215. point2 = this._zline[1];
  57216. point1.x = position.x;
  57217. point1.y = position.y;
  57218. point1.z = position.z;
  57219. point2.x = point1.x + zaxis.x * scaleLines;
  57220. point2.y = point1.y + zaxis.y * scaleLines;
  57221. point2.z = point1.z + zaxis.z * scaleLines;
  57222. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57223. };
  57224. AxesViewer.prototype.dispose = function () {
  57225. if (this._xmesh) {
  57226. this._xmesh.dispose();
  57227. this._ymesh.dispose();
  57228. this._zmesh.dispose();
  57229. this._xmesh = null;
  57230. this._ymesh = null;
  57231. this._zmesh = null;
  57232. this._xline = null;
  57233. this._yline = null;
  57234. this._zline = null;
  57235. this.scene = null;
  57236. }
  57237. };
  57238. return AxesViewer;
  57239. }());
  57240. Debug.AxesViewer = AxesViewer;
  57241. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57242. })(BABYLON || (BABYLON = {}));
  57243. //# sourceMappingURL=babylon.axesViewer.js.map
  57244. var BABYLON;
  57245. (function (BABYLON) {
  57246. var Debug;
  57247. (function (Debug) {
  57248. var BoneAxesViewer = (function (_super) {
  57249. __extends(BoneAxesViewer, _super);
  57250. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57251. if (scaleLines === void 0) { scaleLines = 1; }
  57252. var _this = _super.call(this, scene, scaleLines) || this;
  57253. _this.pos = BABYLON.Vector3.Zero();
  57254. _this.xaxis = BABYLON.Vector3.Zero();
  57255. _this.yaxis = BABYLON.Vector3.Zero();
  57256. _this.zaxis = BABYLON.Vector3.Zero();
  57257. _this.mesh = mesh;
  57258. _this.bone = bone;
  57259. return _this;
  57260. }
  57261. BoneAxesViewer.prototype.update = function () {
  57262. var bone = this.bone;
  57263. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57264. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57265. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57266. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57267. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57268. };
  57269. BoneAxesViewer.prototype.dispose = function () {
  57270. if (this.pos) {
  57271. this.pos = null;
  57272. this.xaxis = null;
  57273. this.yaxis = null;
  57274. this.zaxis = null;
  57275. this.mesh = null;
  57276. this.bone = null;
  57277. _super.prototype.dispose.call(this);
  57278. }
  57279. };
  57280. return BoneAxesViewer;
  57281. }(Debug.AxesViewer));
  57282. Debug.BoneAxesViewer = BoneAxesViewer;
  57283. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57284. })(BABYLON || (BABYLON = {}));
  57285. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57286. var BABYLON;
  57287. (function (BABYLON) {
  57288. /**
  57289. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57290. * It can help converting any input color in a desired output one. This can then be used to create effects
  57291. * from sepia, black and white to sixties or futuristic rendering...
  57292. *
  57293. * The only supported format is currently 3dl.
  57294. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57295. */
  57296. var ColorGradingTexture = (function (_super) {
  57297. __extends(ColorGradingTexture, _super);
  57298. /**
  57299. * Instantiates a ColorGradingTexture from the following parameters.
  57300. *
  57301. * @param url The location of the color gradind data (currently only supporting 3dl)
  57302. * @param scene The scene the texture will be used in
  57303. */
  57304. function ColorGradingTexture(url, scene) {
  57305. var _this = _super.call(this, scene) || this;
  57306. if (!url) {
  57307. return _this;
  57308. }
  57309. _this._textureMatrix = BABYLON.Matrix.Identity();
  57310. _this.name = url;
  57311. _this.url = url;
  57312. _this.hasAlpha = false;
  57313. _this.isCube = false;
  57314. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57315. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57316. _this.anisotropicFilteringLevel = 1;
  57317. _this._texture = _this._getFromCache(url, true);
  57318. if (!_this._texture) {
  57319. if (!scene.useDelayedTextureLoading) {
  57320. _this.loadTexture();
  57321. }
  57322. else {
  57323. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57324. }
  57325. }
  57326. return _this;
  57327. }
  57328. /**
  57329. * Returns the texture matrix used in most of the material.
  57330. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57331. */
  57332. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57333. return this._textureMatrix;
  57334. };
  57335. /**
  57336. * Occurs when the file being loaded is a .3dl LUT file.
  57337. */
  57338. ColorGradingTexture.prototype.load3dlTexture = function () {
  57339. var _this = this;
  57340. var mipLevels = 0;
  57341. var floatArrayView = null;
  57342. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57343. this._texture = texture;
  57344. var callback = function (text) {
  57345. var data;
  57346. var tempData;
  57347. var line;
  57348. var lines = text.split('\n');
  57349. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57350. var maxColor = 0;
  57351. for (var i = 0; i < lines.length; i++) {
  57352. line = lines[i];
  57353. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57354. continue;
  57355. if (line.indexOf('#') === 0)
  57356. continue;
  57357. var words = line.split(" ");
  57358. if (size === 0) {
  57359. // Number of space + one
  57360. size = words.length;
  57361. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57362. tempData = new Float32Array(size * size * size * 4);
  57363. continue;
  57364. }
  57365. if (size != 0) {
  57366. var r = Math.max(parseInt(words[0]), 0);
  57367. var g = Math.max(parseInt(words[1]), 0);
  57368. var b = Math.max(parseInt(words[2]), 0);
  57369. maxColor = Math.max(r, maxColor);
  57370. maxColor = Math.max(g, maxColor);
  57371. maxColor = Math.max(b, maxColor);
  57372. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57373. tempData[pixelStorageIndex + 0] = r;
  57374. tempData[pixelStorageIndex + 1] = g;
  57375. tempData[pixelStorageIndex + 2] = b;
  57376. tempData[pixelStorageIndex + 3] = 0;
  57377. pixelIndexSlice++;
  57378. if (pixelIndexSlice % size == 0) {
  57379. pixelIndexH++;
  57380. pixelIndexSlice = 0;
  57381. if (pixelIndexH % size == 0) {
  57382. pixelIndexW++;
  57383. pixelIndexH = 0;
  57384. }
  57385. }
  57386. }
  57387. }
  57388. for (var i = 0; i < tempData.length; i++) {
  57389. var value = tempData[i];
  57390. data[i] = (value / maxColor * 255);
  57391. }
  57392. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57393. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57394. };
  57395. BABYLON.Tools.LoadFile(this.url, callback);
  57396. return this._texture;
  57397. };
  57398. /**
  57399. * Starts the loading process of the texture.
  57400. */
  57401. ColorGradingTexture.prototype.loadTexture = function () {
  57402. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57403. this.load3dlTexture();
  57404. }
  57405. };
  57406. /**
  57407. * Clones the color gradind texture.
  57408. */
  57409. ColorGradingTexture.prototype.clone = function () {
  57410. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57411. // Base texture
  57412. newTexture.level = this.level;
  57413. return newTexture;
  57414. };
  57415. /**
  57416. * Called during delayed load for textures.
  57417. */
  57418. ColorGradingTexture.prototype.delayLoad = function () {
  57419. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57420. return;
  57421. }
  57422. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57423. this._texture = this._getFromCache(this.url, true);
  57424. if (!this._texture) {
  57425. this.loadTexture();
  57426. }
  57427. };
  57428. /**
  57429. * Binds the color grading to the shader.
  57430. * @param colorGrading The texture to bind
  57431. * @param effect The effect to bind to
  57432. */
  57433. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57434. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57435. var x = colorGrading.level; // Texture Level
  57436. var y = colorGrading.getSize().height; // Texture Size example with 8
  57437. var z = y - 1.0; // SizeMinusOne 8 - 1
  57438. var w = 1 / y; // Space of 1 slice 1 / 8
  57439. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57440. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57441. 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
  57442. 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
  57443. 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
  57444. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57445. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57446. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57447. };
  57448. /**
  57449. * Prepare the list of uniforms associated with the ColorGrading effects.
  57450. * @param uniformsList The list of uniforms used in the effect
  57451. * @param samplersList The list of samplers used in the effect
  57452. */
  57453. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57454. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57455. samplersList.push("cameraColorGrading2DSampler");
  57456. };
  57457. /**
  57458. * Parses a color grading texture serialized by Babylon.
  57459. * @param parsedTexture The texture information being parsedTexture
  57460. * @param scene The scene to load the texture in
  57461. * @param rootUrl The root url of the data assets to load
  57462. * @return A color gradind texture
  57463. */
  57464. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57465. var texture = null;
  57466. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57467. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57468. texture.name = parsedTexture.name;
  57469. texture.level = parsedTexture.level;
  57470. }
  57471. return texture;
  57472. };
  57473. /**
  57474. * Serializes the LUT texture to json format.
  57475. */
  57476. ColorGradingTexture.prototype.serialize = function () {
  57477. if (!this.name) {
  57478. return null;
  57479. }
  57480. var serializationObject = {};
  57481. serializationObject.name = this.name;
  57482. serializationObject.level = this.level;
  57483. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57484. return serializationObject;
  57485. };
  57486. return ColorGradingTexture;
  57487. }(BABYLON.BaseTexture));
  57488. /**
  57489. * Empty line regex stored for GC.
  57490. */
  57491. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57492. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57493. })(BABYLON || (BABYLON = {}));
  57494. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57495. var BABYLON;
  57496. (function (BABYLON) {
  57497. /**
  57498. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57499. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57500. * 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;
  57501. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57502. */
  57503. var ColorCurves = (function () {
  57504. function ColorCurves() {
  57505. this._dirty = true;
  57506. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57507. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57508. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57509. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57510. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57511. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57512. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57513. this._globalHue = 30;
  57514. this._globalDensity = 0;
  57515. this._globalSaturation = 0;
  57516. this._globalExposure = 0;
  57517. this._highlightsHue = 30;
  57518. this._highlightsDensity = 0;
  57519. this._highlightsSaturation = 0;
  57520. this._highlightsExposure = 0;
  57521. this._midtonesHue = 30;
  57522. this._midtonesDensity = 0;
  57523. this._midtonesSaturation = 0;
  57524. this._midtonesExposure = 0;
  57525. this._shadowsHue = 30;
  57526. this._shadowsDensity = 0;
  57527. this._shadowsSaturation = 0;
  57528. this._shadowsExposure = 0;
  57529. }
  57530. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57531. /**
  57532. * Gets the global Hue value.
  57533. * 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).
  57534. */
  57535. get: function () {
  57536. return this._globalHue;
  57537. },
  57538. /**
  57539. * Sets the global Hue value.
  57540. * 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).
  57541. */
  57542. set: function (value) {
  57543. this._globalHue = value;
  57544. this._dirty = true;
  57545. },
  57546. enumerable: true,
  57547. configurable: true
  57548. });
  57549. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57550. /**
  57551. * Gets the global Density value.
  57552. * 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.
  57553. * Values less than zero provide a filter of opposite hue.
  57554. */
  57555. get: function () {
  57556. return this._globalDensity;
  57557. },
  57558. /**
  57559. * Sets the global Density value.
  57560. * 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.
  57561. * Values less than zero provide a filter of opposite hue.
  57562. */
  57563. set: function (value) {
  57564. this._globalDensity = value;
  57565. this._dirty = true;
  57566. },
  57567. enumerable: true,
  57568. configurable: true
  57569. });
  57570. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57571. /**
  57572. * Gets the global Saturation value.
  57573. * 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.
  57574. */
  57575. get: function () {
  57576. return this._globalSaturation;
  57577. },
  57578. /**
  57579. * Sets the global Saturation value.
  57580. * 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.
  57581. */
  57582. set: function (value) {
  57583. this._globalSaturation = value;
  57584. this._dirty = true;
  57585. },
  57586. enumerable: true,
  57587. configurable: true
  57588. });
  57589. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57590. /**
  57591. * Gets the highlights Hue value.
  57592. * 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).
  57593. */
  57594. get: function () {
  57595. return this._highlightsHue;
  57596. },
  57597. /**
  57598. * Sets the highlights Hue value.
  57599. * 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).
  57600. */
  57601. set: function (value) {
  57602. this._highlightsHue = value;
  57603. this._dirty = true;
  57604. },
  57605. enumerable: true,
  57606. configurable: true
  57607. });
  57608. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57609. /**
  57610. * Gets the highlights Density value.
  57611. * 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.
  57612. * Values less than zero provide a filter of opposite hue.
  57613. */
  57614. get: function () {
  57615. return this._highlightsDensity;
  57616. },
  57617. /**
  57618. * Sets the highlights Density value.
  57619. * 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.
  57620. * Values less than zero provide a filter of opposite hue.
  57621. */
  57622. set: function (value) {
  57623. this._highlightsDensity = value;
  57624. this._dirty = true;
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57630. /**
  57631. * Gets the highlights Saturation value.
  57632. * 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.
  57633. */
  57634. get: function () {
  57635. return this._highlightsSaturation;
  57636. },
  57637. /**
  57638. * Sets the highlights Saturation value.
  57639. * 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.
  57640. */
  57641. set: function (value) {
  57642. this._highlightsSaturation = value;
  57643. this._dirty = true;
  57644. },
  57645. enumerable: true,
  57646. configurable: true
  57647. });
  57648. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57649. /**
  57650. * Gets the highlights Exposure value.
  57651. * 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.
  57652. */
  57653. get: function () {
  57654. return this._highlightsExposure;
  57655. },
  57656. /**
  57657. * Sets the highlights Exposure value.
  57658. * 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.
  57659. */
  57660. set: function (value) {
  57661. this._highlightsExposure = value;
  57662. this._dirty = true;
  57663. },
  57664. enumerable: true,
  57665. configurable: true
  57666. });
  57667. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57668. /**
  57669. * Gets the midtones Hue value.
  57670. * 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).
  57671. */
  57672. get: function () {
  57673. return this._midtonesHue;
  57674. },
  57675. /**
  57676. * Sets the midtones Hue value.
  57677. * 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).
  57678. */
  57679. set: function (value) {
  57680. this._midtonesHue = value;
  57681. this._dirty = true;
  57682. },
  57683. enumerable: true,
  57684. configurable: true
  57685. });
  57686. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57687. /**
  57688. * Gets the midtones Density value.
  57689. * 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.
  57690. * Values less than zero provide a filter of opposite hue.
  57691. */
  57692. get: function () {
  57693. return this._midtonesDensity;
  57694. },
  57695. /**
  57696. * Sets the midtones Density value.
  57697. * 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.
  57698. * Values less than zero provide a filter of opposite hue.
  57699. */
  57700. set: function (value) {
  57701. this._midtonesDensity = value;
  57702. this._dirty = true;
  57703. },
  57704. enumerable: true,
  57705. configurable: true
  57706. });
  57707. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57708. /**
  57709. * Gets the midtones Saturation value.
  57710. * 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.
  57711. */
  57712. get: function () {
  57713. return this._midtonesSaturation;
  57714. },
  57715. /**
  57716. * Sets the midtones Saturation value.
  57717. * 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.
  57718. */
  57719. set: function (value) {
  57720. this._midtonesSaturation = value;
  57721. this._dirty = true;
  57722. },
  57723. enumerable: true,
  57724. configurable: true
  57725. });
  57726. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57727. /**
  57728. * Gets the midtones Exposure value.
  57729. * 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.
  57730. */
  57731. get: function () {
  57732. return this._midtonesExposure;
  57733. },
  57734. /**
  57735. * Sets the midtones Exposure value.
  57736. * 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.
  57737. */
  57738. set: function (value) {
  57739. this._midtonesExposure = value;
  57740. this._dirty = true;
  57741. },
  57742. enumerable: true,
  57743. configurable: true
  57744. });
  57745. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57746. /**
  57747. * Gets the shadows Hue value.
  57748. * 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).
  57749. */
  57750. get: function () {
  57751. return this._shadowsHue;
  57752. },
  57753. /**
  57754. * Sets the shadows Hue value.
  57755. * 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).
  57756. */
  57757. set: function (value) {
  57758. this._shadowsHue = value;
  57759. this._dirty = true;
  57760. },
  57761. enumerable: true,
  57762. configurable: true
  57763. });
  57764. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57765. /**
  57766. * Gets the shadows Density value.
  57767. * 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.
  57768. * Values less than zero provide a filter of opposite hue.
  57769. */
  57770. get: function () {
  57771. return this._shadowsDensity;
  57772. },
  57773. /**
  57774. * Sets the shadows Density value.
  57775. * 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.
  57776. * Values less than zero provide a filter of opposite hue.
  57777. */
  57778. set: function (value) {
  57779. this._shadowsDensity = value;
  57780. this._dirty = true;
  57781. },
  57782. enumerable: true,
  57783. configurable: true
  57784. });
  57785. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57786. /**
  57787. * Gets the shadows Saturation value.
  57788. * 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.
  57789. */
  57790. get: function () {
  57791. return this._shadowsSaturation;
  57792. },
  57793. /**
  57794. * Sets the shadows Saturation value.
  57795. * 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.
  57796. */
  57797. set: function (value) {
  57798. this._shadowsSaturation = value;
  57799. this._dirty = true;
  57800. },
  57801. enumerable: true,
  57802. configurable: true
  57803. });
  57804. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57805. /**
  57806. * Gets the shadows Exposure value.
  57807. * 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.
  57808. */
  57809. get: function () {
  57810. return this._shadowsExposure;
  57811. },
  57812. /**
  57813. * Sets the shadows Exposure value.
  57814. * 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.
  57815. */
  57816. set: function (value) {
  57817. this._shadowsExposure = value;
  57818. this._dirty = true;
  57819. },
  57820. enumerable: true,
  57821. configurable: true
  57822. });
  57823. /**
  57824. * Binds the color curves to the shader.
  57825. * @param colorCurves The color curve to bind
  57826. * @param effect The effect to bind to
  57827. */
  57828. ColorCurves.Bind = function (colorCurves, effect) {
  57829. if (colorCurves._dirty) {
  57830. colorCurves._dirty = false;
  57831. // Fill in global info.
  57832. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57833. // Compute highlights info.
  57834. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57835. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57836. // Compute midtones info.
  57837. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57838. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57839. // Compute shadows info.
  57840. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57841. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57842. // Compute deltas (neutral is midtones).
  57843. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57844. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57845. }
  57846. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57847. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57848. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57849. };
  57850. /**
  57851. * Prepare the list of uniforms associated with the ColorCurves effects.
  57852. * @param uniformsList The list of uniforms used in the effect
  57853. */
  57854. ColorCurves.PrepareUniforms = function (uniformsList) {
  57855. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57856. };
  57857. /**
  57858. * Returns color grading data based on a hue, density, saturation and exposure value.
  57859. * @param filterHue The hue of the color filter.
  57860. * @param filterDensity The density of the color filter.
  57861. * @param saturation The saturation.
  57862. * @param exposure The exposure.
  57863. * @param result The result data container.
  57864. */
  57865. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57866. if (hue == null) {
  57867. return;
  57868. }
  57869. hue = ColorCurves.clamp(hue, 0, 360);
  57870. density = ColorCurves.clamp(density, -100, 100);
  57871. saturation = ColorCurves.clamp(saturation, -100, 100);
  57872. exposure = ColorCurves.clamp(exposure, -100, 100);
  57873. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57874. // so that the maximum filter density is only 50% control. This provides fine control
  57875. // for small values and reasonable range.
  57876. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57877. density *= 0.5;
  57878. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57879. if (density < 0) {
  57880. density *= -1;
  57881. hue = (hue + 180) % 360;
  57882. }
  57883. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57884. result.scaleToRef(2, result);
  57885. result.a = 1 + 0.01 * saturation;
  57886. };
  57887. /**
  57888. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57889. * @param value The input slider value in range [-100,100].
  57890. * @returns Adjusted value.
  57891. */
  57892. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57893. value /= 100;
  57894. var x = Math.abs(value);
  57895. x = Math.pow(x, 2);
  57896. if (value < 0) {
  57897. x *= -1;
  57898. }
  57899. x *= 100;
  57900. return x;
  57901. };
  57902. /**
  57903. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57904. * @param hue The hue (H) input.
  57905. * @param saturation The saturation (S) input.
  57906. * @param brightness The brightness (B) input.
  57907. * @result An RGBA color represented as Vector4.
  57908. */
  57909. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57910. var h = ColorCurves.clamp(hue, 0, 360);
  57911. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57912. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57913. if (s === 0) {
  57914. result.r = v;
  57915. result.g = v;
  57916. result.b = v;
  57917. }
  57918. else {
  57919. // sector 0 to 5
  57920. h /= 60;
  57921. var i = Math.floor(h);
  57922. // fractional part of h
  57923. var f = h - i;
  57924. var p = v * (1 - s);
  57925. var q = v * (1 - s * f);
  57926. var t = v * (1 - s * (1 - f));
  57927. switch (i) {
  57928. case 0:
  57929. result.r = v;
  57930. result.g = t;
  57931. result.b = p;
  57932. break;
  57933. case 1:
  57934. result.r = q;
  57935. result.g = v;
  57936. result.b = p;
  57937. break;
  57938. case 2:
  57939. result.r = p;
  57940. result.g = v;
  57941. result.b = t;
  57942. break;
  57943. case 3:
  57944. result.r = p;
  57945. result.g = q;
  57946. result.b = v;
  57947. break;
  57948. case 4:
  57949. result.r = t;
  57950. result.g = p;
  57951. result.b = v;
  57952. break;
  57953. default:
  57954. result.r = v;
  57955. result.g = p;
  57956. result.b = q;
  57957. break;
  57958. }
  57959. }
  57960. result.a = 1;
  57961. };
  57962. /**
  57963. * Returns a value clamped between min and max
  57964. * @param value The value to clamp
  57965. * @param min The minimum of value
  57966. * @param max The maximum of value
  57967. * @returns The clamped value.
  57968. */
  57969. ColorCurves.clamp = function (value, min, max) {
  57970. return Math.min(Math.max(value, min), max);
  57971. };
  57972. /**
  57973. * Clones the current color curve instance.
  57974. * @return The cloned curves
  57975. */
  57976. ColorCurves.prototype.clone = function () {
  57977. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57978. };
  57979. /**
  57980. * Serializes the current color curve instance to a json representation.
  57981. * @return a JSON representation
  57982. */
  57983. ColorCurves.prototype.serialize = function () {
  57984. return BABYLON.SerializationHelper.Serialize(this);
  57985. };
  57986. /**
  57987. * Parses the color curve from a json representation.
  57988. * @param source the JSON source to parse
  57989. * @return The parsed curves
  57990. */
  57991. ColorCurves.Parse = function (source) {
  57992. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57993. };
  57994. return ColorCurves;
  57995. }());
  57996. __decorate([
  57997. BABYLON.serialize()
  57998. ], ColorCurves.prototype, "_globalHue", void 0);
  57999. __decorate([
  58000. BABYLON.serialize()
  58001. ], ColorCurves.prototype, "_globalDensity", void 0);
  58002. __decorate([
  58003. BABYLON.serialize()
  58004. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58005. __decorate([
  58006. BABYLON.serialize()
  58007. ], ColorCurves.prototype, "_globalExposure", void 0);
  58008. __decorate([
  58009. BABYLON.serialize()
  58010. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58011. __decorate([
  58012. BABYLON.serialize()
  58013. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58014. __decorate([
  58015. BABYLON.serialize()
  58016. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58017. __decorate([
  58018. BABYLON.serialize()
  58019. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58020. __decorate([
  58021. BABYLON.serialize()
  58022. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58023. __decorate([
  58024. BABYLON.serialize()
  58025. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58026. __decorate([
  58027. BABYLON.serialize()
  58028. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58029. __decorate([
  58030. BABYLON.serialize()
  58031. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58032. BABYLON.ColorCurves = ColorCurves;
  58033. })(BABYLON || (BABYLON = {}));
  58034. //# sourceMappingURL=babylon.colorCurves.js.map
  58035. var BABYLON;
  58036. (function (BABYLON) {
  58037. var PBRMaterialDefines = (function (_super) {
  58038. __extends(PBRMaterialDefines, _super);
  58039. function PBRMaterialDefines() {
  58040. var _this = _super.call(this) || this;
  58041. _this.ALBEDO = false;
  58042. _this.AMBIENT = false;
  58043. _this.OPACITY = false;
  58044. _this.OPACITYRGB = false;
  58045. _this.REFLECTION = false;
  58046. _this.EMISSIVE = false;
  58047. _this.REFLECTIVITY = false;
  58048. _this.BUMP = false;
  58049. _this.PARALLAX = false;
  58050. _this.PARALLAXOCCLUSION = false;
  58051. _this.SPECULAROVERALPHA = false;
  58052. _this.CLIPPLANE = false;
  58053. _this.ALPHATEST = false;
  58054. _this.ALPHAFROMALBEDO = false;
  58055. _this.POINTSIZE = false;
  58056. _this.FOG = false;
  58057. _this.SPECULARTERM = false;
  58058. _this.OPACITYFRESNEL = false;
  58059. _this.EMISSIVEFRESNEL = false;
  58060. _this.FRESNEL = false;
  58061. _this.NORMAL = false;
  58062. _this.TANGENT = false;
  58063. _this.UV1 = false;
  58064. _this.UV2 = false;
  58065. _this.VERTEXCOLOR = false;
  58066. _this.VERTEXALPHA = false;
  58067. _this.NUM_BONE_INFLUENCERS = 0;
  58068. _this.BonesPerMesh = 0;
  58069. _this.INSTANCES = false;
  58070. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58071. _this.MICROSURFACEAUTOMATIC = false;
  58072. _this.EMISSIVEASILLUMINATION = false;
  58073. _this.LINKEMISSIVEWITHALBEDO = false;
  58074. _this.LIGHTMAP = false;
  58075. _this.USELIGHTMAPASSHADOWMAP = false;
  58076. _this.REFLECTIONMAP_3D = false;
  58077. _this.REFLECTIONMAP_SPHERICAL = false;
  58078. _this.REFLECTIONMAP_PLANAR = false;
  58079. _this.REFLECTIONMAP_CUBIC = false;
  58080. _this.REFLECTIONMAP_PROJECTION = false;
  58081. _this.REFLECTIONMAP_SKYBOX = false;
  58082. _this.REFLECTIONMAP_EXPLICIT = false;
  58083. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58084. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  58085. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  58086. _this.INVERTCUBICMAP = false;
  58087. _this.LOGARITHMICDEPTH = false;
  58088. _this.CAMERATONEMAP = false;
  58089. _this.CAMERACONTRAST = false;
  58090. _this.CAMERACOLORGRADING = false;
  58091. _this.CAMERACOLORCURVES = false;
  58092. _this.OVERLOADEDVALUES = false;
  58093. _this.OVERLOADEDSHADOWVALUES = false;
  58094. _this.USESPHERICALFROMREFLECTIONMAP = false;
  58095. _this.REFRACTION = false;
  58096. _this.REFRACTIONMAP_3D = false;
  58097. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  58098. _this.REFRACTIONMAPINLINEARSPACE = false;
  58099. _this.LODBASEDMICROSFURACE = false;
  58100. _this.USEPHYSICALLIGHTFALLOFF = false;
  58101. _this.RADIANCEOVERALPHA = false;
  58102. _this.USEPMREMREFLECTION = false;
  58103. _this.USEPMREMREFRACTION = false;
  58104. _this.INVERTNORMALMAPX = false;
  58105. _this.INVERTNORMALMAPY = false;
  58106. _this.TWOSIDEDLIGHTING = false;
  58107. _this.SHADOWFULLFLOAT = false;
  58108. _this.METALLICWORKFLOW = false;
  58109. _this.METALLICROUGHNESSMAP = false;
  58110. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  58111. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  58112. _this.rebuild();
  58113. return _this;
  58114. }
  58115. return PBRMaterialDefines;
  58116. }(BABYLON.MaterialDefines));
  58117. /**
  58118. * The Physically based material of BJS.
  58119. *
  58120. * This offers the main features of a standard PBR material.
  58121. * For more information, please refer to the documentation :
  58122. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58123. */
  58124. var PBRMaterial = (function (_super) {
  58125. __extends(PBRMaterial, _super);
  58126. /**
  58127. * Instantiates a new PBRMaterial instance.
  58128. *
  58129. * @param name The material name
  58130. * @param scene The scene the material will be use in.
  58131. */
  58132. function PBRMaterial(name, scene) {
  58133. var _this = _super.call(this, name, scene) || this;
  58134. /**
  58135. * Intensity of the direct lights e.g. the four lights available in your scene.
  58136. * This impacts both the direct diffuse and specular highlights.
  58137. */
  58138. _this.directIntensity = 1.0;
  58139. /**
  58140. * Intensity of the emissive part of the material.
  58141. * This helps controlling the emissive effect without modifying the emissive color.
  58142. */
  58143. _this.emissiveIntensity = 1.0;
  58144. /**
  58145. * Intensity of the environment e.g. how much the environment will light the object
  58146. * either through harmonics for rough material or through the refelction for shiny ones.
  58147. */
  58148. _this.environmentIntensity = 1.0;
  58149. /**
  58150. * This is a special control allowing the reduction of the specular highlights coming from the
  58151. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58152. */
  58153. _this.specularIntensity = 1.0;
  58154. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  58155. /**
  58156. * Debug Control allowing disabling the bump map on this material.
  58157. */
  58158. _this.disableBumpMap = false;
  58159. /**
  58160. * Debug Control helping enforcing or dropping the darkness of shadows.
  58161. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58162. */
  58163. _this.overloadedShadowIntensity = 1.0;
  58164. /**
  58165. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58166. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58167. */
  58168. _this.overloadedShadeIntensity = 1.0;
  58169. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  58170. /**
  58171. * The camera exposure used on this material.
  58172. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58173. * This corresponds to a photographic exposure.
  58174. */
  58175. _this.cameraExposure = 1.0;
  58176. /**
  58177. * The camera contrast used on this material.
  58178. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58179. */
  58180. _this.cameraContrast = 1.0;
  58181. /**
  58182. * Color Grading 2D Lookup Texture.
  58183. * This allows special effects like sepia, black and white to sixties rendering style.
  58184. */
  58185. _this.cameraColorGradingTexture = null;
  58186. /**
  58187. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58188. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58189. * 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;
  58190. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58191. */
  58192. _this.cameraColorCurves = null;
  58193. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58194. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58195. /**
  58196. * Debug Control allowing to overload the ambient color.
  58197. * This as to be use with the overloadedAmbientIntensity parameter.
  58198. */
  58199. _this.overloadedAmbient = BABYLON.Color3.White();
  58200. /**
  58201. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58202. */
  58203. _this.overloadedAmbientIntensity = 0.0;
  58204. /**
  58205. * Debug Control allowing to overload the albedo color.
  58206. * This as to be use with the overloadedAlbedoIntensity parameter.
  58207. */
  58208. _this.overloadedAlbedo = BABYLON.Color3.White();
  58209. /**
  58210. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58211. */
  58212. _this.overloadedAlbedoIntensity = 0.0;
  58213. /**
  58214. * Debug Control allowing to overload the reflectivity color.
  58215. * This as to be use with the overloadedReflectivityIntensity parameter.
  58216. */
  58217. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58218. /**
  58219. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58220. */
  58221. _this.overloadedReflectivityIntensity = 0.0;
  58222. /**
  58223. * Debug Control allowing to overload the emissive color.
  58224. * This as to be use with the overloadedEmissiveIntensity parameter.
  58225. */
  58226. _this.overloadedEmissive = BABYLON.Color3.White();
  58227. /**
  58228. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58229. */
  58230. _this.overloadedEmissiveIntensity = 0.0;
  58231. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  58232. /**
  58233. * Debug Control allowing to overload the reflection color.
  58234. * This as to be use with the overloadedReflectionIntensity parameter.
  58235. */
  58236. _this.overloadedReflection = BABYLON.Color3.White();
  58237. /**
  58238. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58239. */
  58240. _this.overloadedReflectionIntensity = 0.0;
  58241. /**
  58242. * Debug Control allowing to overload the microsurface.
  58243. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58244. */
  58245. _this.overloadedMicroSurface = 0.0;
  58246. /**
  58247. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58248. */
  58249. _this.overloadedMicroSurfaceIntensity = 0.0;
  58250. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  58251. /**
  58252. * AKA Occlusion Texture Intensity in other nomenclature.
  58253. */
  58254. _this.ambientTextureStrength = 1.0;
  58255. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58256. /**
  58257. * AKA Diffuse Color in other nomenclature.
  58258. */
  58259. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58260. /**
  58261. * AKA Specular Color in other nomenclature.
  58262. */
  58263. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58264. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58265. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58266. /**
  58267. * AKA Glossiness in other nomenclature.
  58268. */
  58269. _this.microSurface = 0.9;
  58270. /**
  58271. * source material index of refraction (IOR)' / 'destination material IOR.
  58272. */
  58273. _this.indexOfRefraction = 0.66;
  58274. /**
  58275. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58276. */
  58277. _this.invertRefractionY = false;
  58278. /**
  58279. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58280. * Materials half opaque for instance using refraction could benefit from this control.
  58281. */
  58282. _this.linkRefractionWithTransparency = false;
  58283. /**
  58284. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58285. */
  58286. _this.linkEmissiveWithAlbedo = false;
  58287. _this.useLightmapAsShadowmap = false;
  58288. /**
  58289. * In this mode, the emissive informtaion will always be added to the lighting once.
  58290. * A light for instance can be thought as emissive.
  58291. */
  58292. _this.useEmissiveAsIllumination = false;
  58293. /**
  58294. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58295. */
  58296. _this.useAlphaFromAlbedoTexture = false;
  58297. /**
  58298. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58299. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58300. */
  58301. _this.useSpecularOverAlpha = true;
  58302. /**
  58303. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58304. */
  58305. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58306. /**
  58307. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  58308. */
  58309. _this.useRoughnessFromMetallicTextureAlpha = true;
  58310. /**
  58311. * Specifies if the metallic texture contains the roughness information in its green channel.
  58312. */
  58313. _this.useRoughnessFromMetallicTextureGreen = false;
  58314. /**
  58315. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58316. * The material will try to infer what glossiness each pixel should be.
  58317. */
  58318. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  58319. /**
  58320. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58321. * the creation of the material.
  58322. */
  58323. _this.useScalarInLinearSpace = false;
  58324. /**
  58325. * BJS is using an harcoded light falloff based on a manually sets up range.
  58326. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58327. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58328. */
  58329. _this.usePhysicalLightFalloff = true;
  58330. /**
  58331. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58332. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58333. */
  58334. _this.useRadianceOverAlpha = true;
  58335. /**
  58336. * Allows using the bump map in parallax mode.
  58337. */
  58338. _this.useParallax = false;
  58339. /**
  58340. * Allows using the bump map in parallax occlusion mode.
  58341. */
  58342. _this.useParallaxOcclusion = false;
  58343. /**
  58344. * Controls the scale bias of the parallax mode.
  58345. */
  58346. _this.parallaxScaleBias = 0.05;
  58347. /**
  58348. * If sets to true, disables all the lights affecting the material.
  58349. */
  58350. _this.disableLighting = false;
  58351. /**
  58352. * Number of Simultaneous lights allowed on the material.
  58353. */
  58354. _this.maxSimultaneousLights = 4;
  58355. /**
  58356. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58357. */
  58358. _this.invertNormalMapX = false;
  58359. /**
  58360. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58361. */
  58362. _this.invertNormalMapY = false;
  58363. /**
  58364. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  58365. */
  58366. _this.twoSidedLighting = false;
  58367. _this._renderTargets = new BABYLON.SmartArray(16);
  58368. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58369. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58370. _this._tempColor = new BABYLON.Color3();
  58371. _this._defines = new PBRMaterialDefines();
  58372. _this._cachedDefines = new PBRMaterialDefines();
  58373. _this._myScene = null;
  58374. _this._myShadowGenerator = null;
  58375. _this._cachedDefines.BonesPerMesh = -1;
  58376. _this.getRenderTargetTextures = function () {
  58377. _this._renderTargets.reset();
  58378. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58379. _this._renderTargets.push(_this.reflectionTexture);
  58380. }
  58381. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58382. _this._renderTargets.push(_this.refractionTexture);
  58383. }
  58384. return _this._renderTargets;
  58385. };
  58386. return _this;
  58387. }
  58388. PBRMaterial.prototype.getClassName = function () {
  58389. return "PBRMaterial";
  58390. };
  58391. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58392. get: function () {
  58393. return this._useLogarithmicDepth;
  58394. },
  58395. set: function (value) {
  58396. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58397. },
  58398. enumerable: true,
  58399. configurable: true
  58400. });
  58401. PBRMaterial.prototype.needAlphaBlending = function () {
  58402. if (this.linkRefractionWithTransparency) {
  58403. return false;
  58404. }
  58405. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58406. };
  58407. PBRMaterial.prototype.needAlphaTesting = function () {
  58408. if (this.linkRefractionWithTransparency) {
  58409. return false;
  58410. }
  58411. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58412. };
  58413. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58414. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58415. };
  58416. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58417. return this.albedoTexture;
  58418. };
  58419. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58420. if (!mesh) {
  58421. return true;
  58422. }
  58423. if (this._defines.INSTANCES !== useInstances) {
  58424. return false;
  58425. }
  58426. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58427. return true;
  58428. }
  58429. return false;
  58430. };
  58431. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58432. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58433. };
  58434. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58435. if (!useScalarInLinear) {
  58436. color.toLinearSpaceToRef(ref);
  58437. }
  58438. else {
  58439. ref.r = color.r;
  58440. ref.g = color.g;
  58441. ref.b = color.b;
  58442. }
  58443. };
  58444. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58445. var lightIndex = 0;
  58446. var depthValuesAlreadySet = false;
  58447. for (var index = 0; index < scene.lights.length; index++) {
  58448. var light = scene.lights[index];
  58449. if (!light.isEnabled()) {
  58450. continue;
  58451. }
  58452. if (!light.canAffectMesh(mesh)) {
  58453. continue;
  58454. }
  58455. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58456. // GAMMA CORRECTION.
  58457. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58458. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58459. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58460. if (defines["SPECULARTERM"]) {
  58461. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58462. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58463. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58464. }
  58465. // Shadows
  58466. if (scene.shadowsEnabled) {
  58467. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58468. }
  58469. lightIndex++;
  58470. if (lightIndex === maxSimultaneousLights)
  58471. break;
  58472. }
  58473. };
  58474. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58475. if (this.isFrozen) {
  58476. if (this._wasPreviouslyReady) {
  58477. return true;
  58478. }
  58479. }
  58480. var scene = this.getScene();
  58481. var engine = scene.getEngine();
  58482. var needNormals = false;
  58483. var needUVs = false;
  58484. this._defines.reset();
  58485. if (scene.lightsEnabled && !this.disableLighting) {
  58486. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58487. }
  58488. if (!this.checkReadyOnEveryCall) {
  58489. if (this._renderId === scene.getRenderId()) {
  58490. if (this._checkCache(scene, mesh, useInstances)) {
  58491. return true;
  58492. }
  58493. }
  58494. }
  58495. if (scene.texturesEnabled) {
  58496. if (scene.getEngine().getCaps().textureLOD) {
  58497. this._defines.LODBASEDMICROSFURACE = true;
  58498. }
  58499. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58500. if (!this.albedoTexture.isReady()) {
  58501. return false;
  58502. }
  58503. else {
  58504. needUVs = true;
  58505. this._defines.ALBEDO = true;
  58506. }
  58507. }
  58508. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58509. if (!this.ambientTexture.isReady()) {
  58510. return false;
  58511. }
  58512. else {
  58513. needUVs = true;
  58514. this._defines.AMBIENT = true;
  58515. }
  58516. }
  58517. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58518. if (!this.opacityTexture.isReady()) {
  58519. return false;
  58520. }
  58521. else {
  58522. needUVs = true;
  58523. this._defines.OPACITY = true;
  58524. if (this.opacityTexture.getAlphaFromRGB) {
  58525. this._defines.OPACITYRGB = true;
  58526. }
  58527. }
  58528. }
  58529. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58530. if (!this.reflectionTexture.isReady()) {
  58531. return false;
  58532. }
  58533. else {
  58534. needNormals = true;
  58535. this._defines.REFLECTION = true;
  58536. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58537. this._defines.INVERTCUBICMAP = true;
  58538. }
  58539. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58540. switch (this.reflectionTexture.coordinatesMode) {
  58541. case BABYLON.Texture.CUBIC_MODE:
  58542. case BABYLON.Texture.INVCUBIC_MODE:
  58543. this._defines.REFLECTIONMAP_CUBIC = true;
  58544. break;
  58545. case BABYLON.Texture.EXPLICIT_MODE:
  58546. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58547. break;
  58548. case BABYLON.Texture.PLANAR_MODE:
  58549. this._defines.REFLECTIONMAP_PLANAR = true;
  58550. break;
  58551. case BABYLON.Texture.PROJECTION_MODE:
  58552. this._defines.REFLECTIONMAP_PROJECTION = true;
  58553. break;
  58554. case BABYLON.Texture.SKYBOX_MODE:
  58555. this._defines.REFLECTIONMAP_SKYBOX = true;
  58556. break;
  58557. case BABYLON.Texture.SPHERICAL_MODE:
  58558. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58559. break;
  58560. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58561. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58562. break;
  58563. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  58564. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  58565. break;
  58566. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  58567. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  58568. break;
  58569. }
  58570. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58571. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58572. needNormals = true;
  58573. if (this.reflectionTexture.isPMREM) {
  58574. this._defines.USEPMREMREFLECTION = true;
  58575. }
  58576. }
  58577. }
  58578. }
  58579. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58580. if (!this.lightmapTexture.isReady()) {
  58581. return false;
  58582. }
  58583. else {
  58584. needUVs = true;
  58585. this._defines.LIGHTMAP = true;
  58586. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58587. }
  58588. }
  58589. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58590. if (!this.emissiveTexture.isReady()) {
  58591. return false;
  58592. }
  58593. else {
  58594. needUVs = true;
  58595. this._defines.EMISSIVE = true;
  58596. }
  58597. }
  58598. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58599. if (this.metallicTexture) {
  58600. if (!this.metallicTexture.isReady()) {
  58601. return false;
  58602. }
  58603. else {
  58604. needUVs = true;
  58605. this._defines.METALLICWORKFLOW = true;
  58606. this._defines.METALLICROUGHNESSMAP = true;
  58607. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  58608. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  58609. }
  58610. }
  58611. else if (this.reflectivityTexture) {
  58612. if (!this.reflectivityTexture.isReady()) {
  58613. return false;
  58614. }
  58615. else {
  58616. needUVs = true;
  58617. this._defines.REFLECTIVITY = true;
  58618. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58619. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58620. }
  58621. }
  58622. }
  58623. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58624. if (!this.bumpTexture.isReady()) {
  58625. return false;
  58626. }
  58627. else {
  58628. needUVs = true;
  58629. this._defines.BUMP = true;
  58630. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58631. this._defines.PARALLAX = true;
  58632. if (this.useParallaxOcclusion) {
  58633. this._defines.PARALLAXOCCLUSION = true;
  58634. }
  58635. }
  58636. if (this.invertNormalMapX) {
  58637. this._defines.INVERTNORMALMAPX = true;
  58638. }
  58639. if (this.invertNormalMapY) {
  58640. this._defines.INVERTNORMALMAPY = true;
  58641. }
  58642. if (scene._mirroredCameraPosition) {
  58643. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  58644. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  58645. }
  58646. }
  58647. }
  58648. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58649. if (!this.refractionTexture.isReady()) {
  58650. return false;
  58651. }
  58652. else {
  58653. needUVs = true;
  58654. this._defines.REFRACTION = true;
  58655. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58656. if (this.linkRefractionWithTransparency) {
  58657. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58658. }
  58659. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58660. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58661. if (this.refractionTexture.isPMREM) {
  58662. this._defines.USEPMREMREFRACTION = true;
  58663. }
  58664. }
  58665. }
  58666. }
  58667. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58668. if (!this.cameraColorGradingTexture.isReady()) {
  58669. return false;
  58670. }
  58671. else {
  58672. this._defines.CAMERACOLORGRADING = true;
  58673. }
  58674. }
  58675. if (!this.backFaceCulling && this.twoSidedLighting) {
  58676. this._defines.TWOSIDEDLIGHTING = true;
  58677. }
  58678. }
  58679. // Effect
  58680. if (scene.clipPlane) {
  58681. this._defines.CLIPPLANE = true;
  58682. }
  58683. if (engine.getAlphaTesting()) {
  58684. this._defines.ALPHATEST = true;
  58685. }
  58686. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58687. this._defines.ALPHAFROMALBEDO = true;
  58688. }
  58689. if (this.useEmissiveAsIllumination) {
  58690. this._defines.EMISSIVEASILLUMINATION = true;
  58691. }
  58692. if (this.linkEmissiveWithAlbedo) {
  58693. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58694. }
  58695. if (this.useLogarithmicDepth) {
  58696. this._defines.LOGARITHMICDEPTH = true;
  58697. }
  58698. if (this.cameraContrast != 1) {
  58699. this._defines.CAMERACONTRAST = true;
  58700. }
  58701. if (this.cameraExposure != 1) {
  58702. this._defines.CAMERATONEMAP = true;
  58703. }
  58704. if (this.cameraColorCurves) {
  58705. this._defines.CAMERACOLORCURVES = true;
  58706. }
  58707. if (this.overloadedShadeIntensity != 1 ||
  58708. this.overloadedShadowIntensity != 1) {
  58709. this._defines.OVERLOADEDSHADOWVALUES = true;
  58710. }
  58711. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58712. this.overloadedEmissiveIntensity > 0 ||
  58713. this.overloadedReflectivityIntensity > 0 ||
  58714. this.overloadedAlbedoIntensity > 0 ||
  58715. this.overloadedAmbientIntensity > 0 ||
  58716. this.overloadedReflectionIntensity > 0) {
  58717. this._defines.OVERLOADEDVALUES = true;
  58718. }
  58719. // Point size
  58720. if (this.pointsCloud || scene.forcePointsCloud) {
  58721. this._defines.POINTSIZE = true;
  58722. }
  58723. // Fog
  58724. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58725. this._defines.FOG = true;
  58726. }
  58727. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58728. // Fresnel
  58729. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58730. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58731. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58732. this._defines.OPACITYFRESNEL = true;
  58733. }
  58734. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58735. this._defines.EMISSIVEFRESNEL = true;
  58736. }
  58737. needNormals = true;
  58738. this._defines.FRESNEL = true;
  58739. }
  58740. }
  58741. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58742. this._defines.SPECULAROVERALPHA = true;
  58743. }
  58744. if (this.usePhysicalLightFalloff) {
  58745. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58746. }
  58747. if (this.useRadianceOverAlpha) {
  58748. this._defines.RADIANCEOVERALPHA = true;
  58749. }
  58750. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  58751. this._defines.METALLICWORKFLOW = true;
  58752. }
  58753. // Attribs
  58754. if (mesh) {
  58755. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58756. this._defines.NORMAL = true;
  58757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  58758. this._defines.TANGENT = true;
  58759. }
  58760. }
  58761. if (needUVs) {
  58762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58763. this._defines.UV1 = true;
  58764. }
  58765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58766. this._defines.UV2 = true;
  58767. }
  58768. }
  58769. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58770. this._defines.VERTEXCOLOR = true;
  58771. if (mesh.hasVertexAlpha) {
  58772. this._defines.VERTEXALPHA = true;
  58773. }
  58774. }
  58775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58776. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58777. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58778. }
  58779. // Instances
  58780. if (useInstances) {
  58781. this._defines.INSTANCES = true;
  58782. }
  58783. }
  58784. // Get correct effect
  58785. if (!this._defines.isEqual(this._cachedDefines)) {
  58786. this._defines.cloneTo(this._cachedDefines);
  58787. scene.resetCachedMaterial();
  58788. // Fallbacks
  58789. var fallbacks = new BABYLON.EffectFallbacks();
  58790. if (this._defines.REFLECTION) {
  58791. fallbacks.addFallback(0, "REFLECTION");
  58792. }
  58793. if (this._defines.REFRACTION) {
  58794. fallbacks.addFallback(0, "REFRACTION");
  58795. }
  58796. if (this._defines.REFLECTIVITY) {
  58797. fallbacks.addFallback(0, "REFLECTIVITY");
  58798. }
  58799. if (this._defines.BUMP) {
  58800. fallbacks.addFallback(0, "BUMP");
  58801. }
  58802. if (this._defines.PARALLAX) {
  58803. fallbacks.addFallback(1, "PARALLAX");
  58804. }
  58805. if (this._defines.PARALLAXOCCLUSION) {
  58806. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58807. }
  58808. if (this._defines.SPECULAROVERALPHA) {
  58809. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58810. }
  58811. if (this._defines.FOG) {
  58812. fallbacks.addFallback(1, "FOG");
  58813. }
  58814. if (this._defines.POINTSIZE) {
  58815. fallbacks.addFallback(0, "POINTSIZE");
  58816. }
  58817. if (this._defines.LOGARITHMICDEPTH) {
  58818. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58819. }
  58820. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58821. if (this._defines.SPECULARTERM) {
  58822. fallbacks.addFallback(0, "SPECULARTERM");
  58823. }
  58824. if (this._defines.OPACITYFRESNEL) {
  58825. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58826. }
  58827. if (this._defines.EMISSIVEFRESNEL) {
  58828. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58829. }
  58830. if (this._defines.FRESNEL) {
  58831. fallbacks.addFallback(3, "FRESNEL");
  58832. }
  58833. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58834. fallbacks.addCPUSkinningFallback(0, mesh);
  58835. }
  58836. //Attributes
  58837. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58838. if (this._defines.NORMAL) {
  58839. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58840. }
  58841. if (this._defines.TANGENT) {
  58842. attribs.push(BABYLON.VertexBuffer.TangentKind);
  58843. }
  58844. if (this._defines.UV1) {
  58845. attribs.push(BABYLON.VertexBuffer.UVKind);
  58846. }
  58847. if (this._defines.UV2) {
  58848. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58849. }
  58850. if (this._defines.VERTEXCOLOR) {
  58851. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58852. }
  58853. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58854. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58855. // Legacy browser patch
  58856. var join = this._defines.toString();
  58857. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58858. "vFogInfos", "vFogColor", "pointSize",
  58859. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58860. "mBones",
  58861. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58862. "depthValues",
  58863. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58864. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58865. "logarithmicDepthConstant",
  58866. "vSphericalX", "vSphericalY", "vSphericalZ",
  58867. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58868. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58869. "vMicrosurfaceTextureLods",
  58870. "vCameraInfos"
  58871. ];
  58872. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  58873. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58874. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  58875. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58876. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58877. }
  58878. if (!this._effect.isReady()) {
  58879. return false;
  58880. }
  58881. this._renderId = scene.getRenderId();
  58882. this._wasPreviouslyReady = true;
  58883. if (mesh) {
  58884. if (!mesh._materialDefines) {
  58885. mesh._materialDefines = new PBRMaterialDefines();
  58886. }
  58887. this._defines.cloneTo(mesh._materialDefines);
  58888. }
  58889. return true;
  58890. };
  58891. PBRMaterial.prototype.unbind = function () {
  58892. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58893. this._effect.setTexture("reflection2DSampler", null);
  58894. }
  58895. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58896. this._effect.setTexture("refraction2DSampler", null);
  58897. }
  58898. _super.prototype.unbind.call(this);
  58899. };
  58900. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58901. this._effect.setMatrix("world", world);
  58902. };
  58903. PBRMaterial.prototype.bind = function (world, mesh) {
  58904. this._myScene = this.getScene();
  58905. // Matrices
  58906. this.bindOnlyWorldMatrix(world);
  58907. // Bones
  58908. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58909. if (this._myScene.getCachedMaterial() !== this) {
  58910. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58911. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58912. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58913. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58914. }
  58915. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58916. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58917. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58918. }
  58919. }
  58920. // Textures
  58921. if (this._myScene.texturesEnabled) {
  58922. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58923. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58924. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58925. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58926. }
  58927. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58928. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58929. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  58930. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58931. }
  58932. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58933. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58934. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58935. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58936. }
  58937. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58938. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58939. if (this.reflectionTexture.isCube) {
  58940. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58941. }
  58942. else {
  58943. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58944. }
  58945. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58946. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58947. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58948. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58949. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58950. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58951. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58952. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58953. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58954. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58955. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58956. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58957. }
  58958. }
  58959. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58960. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58961. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58962. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58963. }
  58964. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58965. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58966. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58967. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58968. }
  58969. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58970. if (this.metallicTexture) {
  58971. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  58972. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  58973. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  58974. }
  58975. else if (this.reflectivityTexture) {
  58976. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58977. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58978. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58979. }
  58980. }
  58981. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58982. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58983. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58984. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58985. }
  58986. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58987. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58988. var depth = 1.0;
  58989. if (this.refractionTexture.isCube) {
  58990. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58991. }
  58992. else {
  58993. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58994. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58995. if (this.refractionTexture.depth) {
  58996. depth = this.refractionTexture.depth;
  58997. }
  58998. }
  58999. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59000. }
  59001. if ((this.reflectionTexture || this.refractionTexture)) {
  59002. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59003. }
  59004. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59005. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  59006. }
  59007. }
  59008. // Clip plane
  59009. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59010. // Point size
  59011. if (this.pointsCloud) {
  59012. this._effect.setFloat("pointSize", this.pointSize);
  59013. }
  59014. // Colors
  59015. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  59016. if (this._defines.METALLICWORKFLOW) {
  59017. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  59018. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  59019. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  59020. }
  59021. else {
  59022. // GAMMA CORRECTION.
  59023. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  59024. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  59025. }
  59026. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  59027. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  59028. // GAMMA CORRECTION.
  59029. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  59030. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  59031. // GAMMA CORRECTION.
  59032. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  59033. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  59034. }
  59035. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59036. // GAMMA CORRECTION.
  59037. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59038. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59039. // Lights
  59040. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59041. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59042. }
  59043. // View
  59044. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59045. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59046. }
  59047. // Fog
  59048. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59049. this._lightingInfos.x = this.directIntensity;
  59050. this._lightingInfos.y = this.emissiveIntensity;
  59051. this._lightingInfos.z = this.environmentIntensity;
  59052. this._lightingInfos.w = this.specularIntensity;
  59053. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59054. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59055. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59056. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59057. this._cameraInfos.x = this.cameraExposure;
  59058. this._cameraInfos.y = this.cameraContrast;
  59059. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59060. if (this.cameraColorCurves) {
  59061. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59062. }
  59063. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59064. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59065. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59066. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59067. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59068. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  59069. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59070. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59071. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59072. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59073. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59074. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59075. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59076. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59077. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59078. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59079. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59080. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59081. // Log. depth
  59082. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59083. }
  59084. _super.prototype.bind.call(this, world, mesh);
  59085. this._myScene = null;
  59086. };
  59087. PBRMaterial.prototype.getAnimatables = function () {
  59088. var results = [];
  59089. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59090. results.push(this.albedoTexture);
  59091. }
  59092. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59093. results.push(this.ambientTexture);
  59094. }
  59095. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59096. results.push(this.opacityTexture);
  59097. }
  59098. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59099. results.push(this.reflectionTexture);
  59100. }
  59101. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59102. results.push(this.emissiveTexture);
  59103. }
  59104. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  59105. results.push(this.metallicTexture);
  59106. }
  59107. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59108. results.push(this.reflectivityTexture);
  59109. }
  59110. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59111. results.push(this.bumpTexture);
  59112. }
  59113. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59114. results.push(this.lightmapTexture);
  59115. }
  59116. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59117. results.push(this.refractionTexture);
  59118. }
  59119. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59120. results.push(this.cameraColorGradingTexture);
  59121. }
  59122. return results;
  59123. };
  59124. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59125. if (forceDisposeTextures) {
  59126. if (this.albedoTexture) {
  59127. this.albedoTexture.dispose();
  59128. }
  59129. if (this.ambientTexture) {
  59130. this.ambientTexture.dispose();
  59131. }
  59132. if (this.opacityTexture) {
  59133. this.opacityTexture.dispose();
  59134. }
  59135. if (this.reflectionTexture) {
  59136. this.reflectionTexture.dispose();
  59137. }
  59138. if (this.emissiveTexture) {
  59139. this.emissiveTexture.dispose();
  59140. }
  59141. if (this.metallicTexture) {
  59142. this.metallicTexture.dispose();
  59143. }
  59144. if (this.reflectivityTexture) {
  59145. this.reflectivityTexture.dispose();
  59146. }
  59147. if (this.bumpTexture) {
  59148. this.bumpTexture.dispose();
  59149. }
  59150. if (this.lightmapTexture) {
  59151. this.lightmapTexture.dispose();
  59152. }
  59153. if (this.refractionTexture) {
  59154. this.refractionTexture.dispose();
  59155. }
  59156. if (this.cameraColorGradingTexture) {
  59157. this.cameraColorGradingTexture.dispose();
  59158. }
  59159. }
  59160. this._renderTargets.dispose();
  59161. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59162. };
  59163. PBRMaterial.prototype.clone = function (name) {
  59164. var _this = this;
  59165. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59166. };
  59167. PBRMaterial.prototype.serialize = function () {
  59168. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59169. serializationObject.customType = "BABYLON.PBRMaterial";
  59170. return serializationObject;
  59171. };
  59172. // Statics
  59173. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59174. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59175. };
  59176. return PBRMaterial;
  59177. }(BABYLON.Material));
  59178. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59179. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59180. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59181. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59182. __decorate([
  59183. BABYLON.serialize()
  59184. ], PBRMaterial.prototype, "directIntensity", void 0);
  59185. __decorate([
  59186. BABYLON.serialize()
  59187. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59188. __decorate([
  59189. BABYLON.serialize()
  59190. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59191. __decorate([
  59192. BABYLON.serialize()
  59193. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59194. __decorate([
  59195. BABYLON.serialize()
  59196. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59197. __decorate([
  59198. BABYLON.serialize()
  59199. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59200. __decorate([
  59201. BABYLON.serialize()
  59202. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59203. __decorate([
  59204. BABYLON.serialize()
  59205. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59206. __decorate([
  59207. BABYLON.serialize()
  59208. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59209. __decorate([
  59210. BABYLON.serializeAsTexture()
  59211. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59212. __decorate([
  59213. BABYLON.serializeAsColorCurves()
  59214. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59215. __decorate([
  59216. BABYLON.serializeAsColor3()
  59217. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59218. __decorate([
  59219. BABYLON.serialize()
  59220. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59221. __decorate([
  59222. BABYLON.serializeAsColor3()
  59223. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59224. __decorate([
  59225. BABYLON.serialize()
  59226. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59227. __decorate([
  59228. BABYLON.serializeAsColor3()
  59229. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59230. __decorate([
  59231. BABYLON.serialize()
  59232. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59233. __decorate([
  59234. BABYLON.serializeAsColor3()
  59235. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59236. __decorate([
  59237. BABYLON.serialize()
  59238. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59239. __decorate([
  59240. BABYLON.serializeAsColor3()
  59241. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59242. __decorate([
  59243. BABYLON.serialize()
  59244. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59245. __decorate([
  59246. BABYLON.serialize()
  59247. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59248. __decorate([
  59249. BABYLON.serialize()
  59250. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59251. __decorate([
  59252. BABYLON.serializeAsTexture()
  59253. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59254. __decorate([
  59255. BABYLON.serializeAsTexture()
  59256. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59257. __decorate([
  59258. BABYLON.serialize()
  59259. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  59260. __decorate([
  59261. BABYLON.serializeAsTexture()
  59262. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59263. __decorate([
  59264. BABYLON.serializeAsTexture()
  59265. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59266. __decorate([
  59267. BABYLON.serializeAsTexture()
  59268. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59269. __decorate([
  59270. BABYLON.serializeAsTexture()
  59271. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59272. __decorate([
  59273. BABYLON.serializeAsTexture()
  59274. ], PBRMaterial.prototype, "metallicTexture", void 0);
  59275. __decorate([
  59276. BABYLON.serialize()
  59277. ], PBRMaterial.prototype, "metallic", void 0);
  59278. __decorate([
  59279. BABYLON.serialize()
  59280. ], PBRMaterial.prototype, "roughness", void 0);
  59281. __decorate([
  59282. BABYLON.serializeAsTexture()
  59283. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59284. __decorate([
  59285. BABYLON.serializeAsTexture()
  59286. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59287. __decorate([
  59288. BABYLON.serializeAsTexture()
  59289. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59290. __decorate([
  59291. BABYLON.serializeAsColor3("ambient")
  59292. ], PBRMaterial.prototype, "ambientColor", void 0);
  59293. __decorate([
  59294. BABYLON.serializeAsColor3("albedo")
  59295. ], PBRMaterial.prototype, "albedoColor", void 0);
  59296. __decorate([
  59297. BABYLON.serializeAsColor3("reflectivity")
  59298. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59299. __decorate([
  59300. BABYLON.serializeAsColor3("reflection")
  59301. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59302. __decorate([
  59303. BABYLON.serializeAsColor3("emissive")
  59304. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59305. __decorate([
  59306. BABYLON.serialize()
  59307. ], PBRMaterial.prototype, "microSurface", void 0);
  59308. __decorate([
  59309. BABYLON.serialize()
  59310. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59311. __decorate([
  59312. BABYLON.serialize()
  59313. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59314. __decorate([
  59315. BABYLON.serializeAsFresnelParameters()
  59316. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59317. __decorate([
  59318. BABYLON.serializeAsFresnelParameters()
  59319. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59320. __decorate([
  59321. BABYLON.serialize()
  59322. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59323. __decorate([
  59324. BABYLON.serialize()
  59325. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59326. __decorate([
  59327. BABYLON.serialize()
  59328. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59329. __decorate([
  59330. BABYLON.serialize()
  59331. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59332. __decorate([
  59333. BABYLON.serialize()
  59334. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59335. __decorate([
  59336. BABYLON.serialize()
  59337. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59338. __decorate([
  59339. BABYLON.serialize()
  59340. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59341. __decorate([
  59342. BABYLON.serialize()
  59343. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  59344. __decorate([
  59345. BABYLON.serialize()
  59346. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  59347. __decorate([
  59348. BABYLON.serialize()
  59349. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59350. __decorate([
  59351. BABYLON.serialize()
  59352. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59353. __decorate([
  59354. BABYLON.serialize()
  59355. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59356. __decorate([
  59357. BABYLON.serialize()
  59358. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59359. __decorate([
  59360. BABYLON.serialize()
  59361. ], PBRMaterial.prototype, "useParallax", void 0);
  59362. __decorate([
  59363. BABYLON.serialize()
  59364. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59365. __decorate([
  59366. BABYLON.serialize()
  59367. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59368. __decorate([
  59369. BABYLON.serialize()
  59370. ], PBRMaterial.prototype, "disableLighting", void 0);
  59371. __decorate([
  59372. BABYLON.serialize()
  59373. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59374. __decorate([
  59375. BABYLON.serialize()
  59376. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59377. __decorate([
  59378. BABYLON.serialize()
  59379. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59380. __decorate([
  59381. BABYLON.serialize()
  59382. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  59383. __decorate([
  59384. BABYLON.serialize()
  59385. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59386. BABYLON.PBRMaterial = PBRMaterial;
  59387. })(BABYLON || (BABYLON = {}));
  59388. //# sourceMappingURL=babylon.pbrMaterial.js.map
  59389. var BABYLON;
  59390. (function (BABYLON) {
  59391. var DebugLayer = (function () {
  59392. function DebugLayer(scene) {
  59393. this._scene = scene;
  59394. }
  59395. /** Creates the inspector window. */
  59396. DebugLayer.prototype._createInspector = function (config) {
  59397. if (config === void 0) { config = {}; }
  59398. var popup = config.popup || false;
  59399. var initialTab = config.initialTab || 0;
  59400. var parentElement = config.parentElement || null;
  59401. if (!this._inspector) {
  59402. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59403. } // else nothing to do,; instance is already existing
  59404. };
  59405. DebugLayer.prototype.isVisible = function () {
  59406. if (!this._inspector) {
  59407. return false;
  59408. }
  59409. return true;
  59410. };
  59411. DebugLayer.prototype.hide = function () {
  59412. if (this._inspector) {
  59413. this._inspector.dispose();
  59414. this._inspector = null;
  59415. }
  59416. };
  59417. DebugLayer.prototype.show = function (config) {
  59418. if (config === void 0) { config = {}; }
  59419. if (typeof INSPECTOR == 'undefined') {
  59420. // Load inspector and add it to the DOM
  59421. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59422. }
  59423. else {
  59424. // Otherwise creates the inspector
  59425. this._createInspector(config);
  59426. }
  59427. };
  59428. return DebugLayer;
  59429. }());
  59430. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  59431. BABYLON.DebugLayer = DebugLayer;
  59432. })(BABYLON || (BABYLON = {}));
  59433. //# sourceMappingURL=babylon.debugLayer.js.map
  59434. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  59435. var BABYLON;
  59436. (function (BABYLON) {
  59437. var StandardRenderingPipeline = (function (_super) {
  59438. __extends(StandardRenderingPipeline, _super);
  59439. /**
  59440. * @constructor
  59441. * @param {string} name - The rendering pipeline name
  59442. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59443. * @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)
  59444. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59445. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59446. */
  59447. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59448. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59449. var _this = _super.call(this, scene.getEngine(), name) || this;
  59450. _this.downSampleX4PostProcess = null;
  59451. _this.brightPassPostProcess = null;
  59452. _this.gaussianBlurHPostProcesses = [];
  59453. _this.gaussianBlurVPostProcesses = [];
  59454. _this.textureAdderPostProcess = null;
  59455. _this.textureAdderFinalPostProcess = null;
  59456. _this.lensFlareFinalPostProcess = null;
  59457. _this.lensFlarePostProcess = null;
  59458. _this.lensFlareComposePostProcess = null;
  59459. _this.depthOfFieldPostProcess = null;
  59460. // Values
  59461. _this.brightThreshold = 1.0;
  59462. _this.blurWidth = 2.0;
  59463. _this.horizontalBlur = false;
  59464. _this.gaussianCoefficient = 0.25;
  59465. _this.gaussianMean = 1.0;
  59466. _this.gaussianStandardDeviation = 1.0;
  59467. _this.exposure = 1.0;
  59468. _this.lensTexture = null;
  59469. _this.lensColorTexture = null;
  59470. _this.lensFlareStrength = 20.0;
  59471. _this.lensFlareGhostDispersal = 1.4;
  59472. _this.lensFlareHaloWidth = 0.7;
  59473. _this.lensFlareDistortionStrength = 16.0;
  59474. _this.lensStarTexture = null;
  59475. _this.lensFlareDirtTexture = null;
  59476. _this.depthOfFieldDistance = 10.0;
  59477. _this.depthOfFieldBlurWidth = 2.0;
  59478. // IAnimatable
  59479. _this.animations = [];
  59480. _this._depthRenderer = null;
  59481. _this._currentDepthOfFieldSource = null;
  59482. // Getters and setters
  59483. _this._depthOfFieldEnabled = true;
  59484. _this._lensFlareEnabled = true;
  59485. // Initialize
  59486. _this._scene = scene;
  59487. // Create pass post-processe
  59488. if (!originalPostProcess) {
  59489. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  59490. }
  59491. else {
  59492. _this.originalPostProcess = originalPostProcess;
  59493. }
  59494. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59495. // Create down sample X4 post-process
  59496. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  59497. // Create bright pass post-process
  59498. _this._createBrightPassPostProcess(scene, ratio / 2);
  59499. // Create gaussian blur post-processes (down sampling blurs)
  59500. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  59501. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  59502. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  59503. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  59504. // Create texture adder post-process
  59505. _this._createTextureAdderPostProcess(scene, ratio);
  59506. // Create depth-of-field source post-process
  59507. _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);
  59508. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59509. // Create lens flare post-process
  59510. _this._createLensFlarePostProcess(scene, ratio);
  59511. // Create depth-of-field source post-process post lens-flare and disable it now
  59512. _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);
  59513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59514. // Create gaussian blur used by depth-of-field
  59515. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  59516. // Create depth-of-field post-process
  59517. _this._createDepthOfFieldPostProcess(scene, ratio);
  59518. // Finish
  59519. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59520. if (cameras !== null) {
  59521. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59522. }
  59523. // Deactivate
  59524. _this.LensFlareEnabled = false;
  59525. _this.DepthOfFieldEnabled = false;
  59526. return _this;
  59527. }
  59528. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59529. get: function () {
  59530. return this._depthOfFieldEnabled;
  59531. },
  59532. set: function (enabled) {
  59533. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  59534. if (enabled && !this._depthOfFieldEnabled) {
  59535. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59536. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59537. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59538. this._depthRenderer = this._scene.enableDepthRenderer();
  59539. }
  59540. else if (!enabled && this._depthOfFieldEnabled) {
  59541. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59542. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59543. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59544. }
  59545. this._depthOfFieldEnabled = enabled;
  59546. },
  59547. enumerable: true,
  59548. configurable: true
  59549. });
  59550. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59551. get: function () {
  59552. return this._lensFlareEnabled;
  59553. },
  59554. set: function (enabled) {
  59555. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  59556. if (enabled && !this._lensFlareEnabled) {
  59557. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59558. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59559. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59560. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59561. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59562. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  59563. }
  59564. else if (!enabled && this._lensFlareEnabled) {
  59565. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59566. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59567. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59568. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59569. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59570. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  59571. }
  59572. this._lensFlareEnabled = enabled;
  59573. },
  59574. enumerable: true,
  59575. configurable: true
  59576. });
  59577. // Sets depth-of-field save post-process
  59578. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  59579. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  59580. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  59581. switch (name) {
  59582. case "HDRBaseDepthOfFieldSource":
  59583. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  59584. break;
  59585. case "HDRPostLensFlareDepthOfFieldSource":
  59586. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  59587. break;
  59588. default: break;
  59589. }
  59590. };
  59591. // Down Sample X4 Post-Processs
  59592. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59593. var _this = this;
  59594. var downSampleX4Offsets = new Array(32);
  59595. 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);
  59596. this.downSampleX4PostProcess.onApply = function (effect) {
  59597. var id = 0;
  59598. for (var i = -2; i < 2; i++) {
  59599. for (var j = -2; j < 2; j++) {
  59600. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  59601. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  59602. id += 2;
  59603. }
  59604. }
  59605. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59606. };
  59607. // Add to pipeline
  59608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59609. };
  59610. // Brightpass Post-Process
  59611. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59612. var _this = this;
  59613. var brightOffsets = new Array(8);
  59614. 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);
  59615. this.brightPassPostProcess.onApply = function (effect) {
  59616. var sU = (1.0 / _this.brightPassPostProcess.width);
  59617. var sV = (1.0 / _this.brightPassPostProcess.height);
  59618. brightOffsets[0] = -0.5 * sU;
  59619. brightOffsets[1] = 0.5 * sV;
  59620. brightOffsets[2] = 0.5 * sU;
  59621. brightOffsets[3] = 0.5 * sV;
  59622. brightOffsets[4] = -0.5 * sU;
  59623. brightOffsets[5] = -0.5 * sV;
  59624. brightOffsets[6] = 0.5 * sU;
  59625. brightOffsets[7] = -0.5 * sV;
  59626. effect.setArray2("dsOffsets", brightOffsets);
  59627. effect.setFloat("brightThreshold", _this.brightThreshold);
  59628. };
  59629. // Add to pipeline
  59630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59631. };
  59632. // Create gaussian blur H&V post-processes
  59633. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59634. var _this = this;
  59635. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59636. var blurOffsets = new Array(9);
  59637. var blurWeights = new Array(9);
  59638. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  59639. var callback = function (height) {
  59640. return function (effect) {
  59641. // Weights
  59642. var x = 0.0;
  59643. for (var i = 0; i < 9; i++) {
  59644. x = (i - 4.0) / 4.0;
  59645. blurWeights[i] =
  59646. _this.gaussianCoefficient
  59647. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  59648. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  59649. }
  59650. var lastOutputDimensions = {
  59651. width: scene.getEngine().getRenderWidth(),
  59652. height: scene.getEngine().getRenderHeight()
  59653. };
  59654. for (var i = 0; i < 9; i++) {
  59655. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  59656. blurOffsets[i] = value;
  59657. }
  59658. effect.setArray("blurOffsets", blurOffsets);
  59659. effect.setArray("blurWeights", blurWeights);
  59660. if (height) {
  59661. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  59662. }
  59663. else {
  59664. effect.setFloat("blurWidth", _this[blurWidthKey]);
  59665. }
  59666. };
  59667. };
  59668. // Create horizontal gaussian blur post-processes
  59669. 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);
  59670. gaussianBlurHPostProcess.onApply = callback(false);
  59671. // Create vertical gaussian blur post-process
  59672. 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);
  59673. gaussianBlurVPostProcess.onApply = callback(true);
  59674. // Add to pipeline
  59675. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  59676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  59677. // Finish
  59678. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  59679. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  59680. };
  59681. // Create texture adder post-process
  59682. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59683. var _this = this;
  59684. 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);
  59685. this.textureAdderPostProcess.onApply = function (effect) {
  59686. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  59687. effect.setTexture("lensSampler", _this.lensTexture);
  59688. effect.setFloat("exposure", _this.exposure);
  59689. };
  59690. // Add to pipeline
  59691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59692. };
  59693. // Create lens flare post-process
  59694. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59695. var _this = this;
  59696. 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);
  59697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59698. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  59699. 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);
  59700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59701. var resolution = new BABYLON.Vector2(0, 0);
  59702. // Lens flare
  59703. this.lensFlarePostProcess.onApply = function (effect) {
  59704. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  59705. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59706. effect.setFloat("strength", _this.lensFlareStrength);
  59707. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59708. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59709. // Shift
  59710. resolution.x = _this.lensFlarePostProcess.width;
  59711. resolution.y = _this.lensFlarePostProcess.height;
  59712. effect.setVector2("resolution", resolution);
  59713. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59714. };
  59715. // Compose
  59716. 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);
  59717. 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);
  59718. this.lensFlareComposePostProcess.onApply = function (effect) {
  59719. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  59720. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59721. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59722. // Lens start rotation matrix
  59723. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59724. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59725. 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));
  59726. camRot *= 4.0;
  59727. 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);
  59728. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59729. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59730. };
  59731. };
  59732. // Create depth-of-field post-process
  59733. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59734. var _this = this;
  59735. 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);
  59736. this.depthOfFieldPostProcess.onApply = function (effect) {
  59737. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59738. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  59739. effect.setFloat("distance", _this.depthOfFieldDistance);
  59740. };
  59741. // Add to pipeline
  59742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59743. };
  59744. // Dispose
  59745. StandardRenderingPipeline.prototype.dispose = function () {
  59746. for (var i = 0; i < this._scene.cameras.length; i++) {
  59747. var camera = this._scene.cameras[i];
  59748. this.originalPostProcess.dispose(camera);
  59749. this.downSampleX4PostProcess.dispose(camera);
  59750. this.brightPassPostProcess.dispose(camera);
  59751. this.textureAdderPostProcess.dispose(camera);
  59752. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  59753. this.gaussianBlurHPostProcesses[j].dispose(camera);
  59754. }
  59755. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  59756. this.gaussianBlurVPostProcesses[j].dispose(camera);
  59757. }
  59758. this.textureAdderFinalPostProcess.dispose(camera);
  59759. this.lensFlarePostProcess.dispose(camera);
  59760. this.lensFlareComposePostProcess.dispose(camera);
  59761. this.depthOfFieldPostProcess.dispose(camera);
  59762. }
  59763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59764. _super.prototype.dispose.call(this);
  59765. };
  59766. // Serialize rendering pipeline
  59767. StandardRenderingPipeline.prototype.serialize = function () {
  59768. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59769. serializationObject.customType = "StandardRenderingPipeline";
  59770. return serializationObject;
  59771. };
  59772. // Parse serialized pipeline
  59773. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59774. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59775. };
  59776. return StandardRenderingPipeline;
  59777. }(BABYLON.PostProcessRenderPipeline));
  59778. __decorate([
  59779. BABYLON.serialize()
  59780. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59781. __decorate([
  59782. BABYLON.serialize()
  59783. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59784. __decorate([
  59785. BABYLON.serialize()
  59786. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59787. __decorate([
  59788. BABYLON.serialize()
  59789. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  59790. __decorate([
  59791. BABYLON.serialize()
  59792. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  59793. __decorate([
  59794. BABYLON.serialize()
  59795. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  59796. __decorate([
  59797. BABYLON.serialize()
  59798. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59799. __decorate([
  59800. BABYLON.serializeAsTexture("lensTexture")
  59801. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59802. __decorate([
  59803. BABYLON.serializeAsTexture("lensColorTexture")
  59804. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59805. __decorate([
  59806. BABYLON.serialize()
  59807. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59808. __decorate([
  59809. BABYLON.serialize()
  59810. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59811. __decorate([
  59812. BABYLON.serialize()
  59813. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59814. __decorate([
  59815. BABYLON.serialize()
  59816. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59817. __decorate([
  59818. BABYLON.serializeAsTexture("lensStarTexture")
  59819. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59820. __decorate([
  59821. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59822. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59823. __decorate([
  59824. BABYLON.serialize()
  59825. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59826. __decorate([
  59827. BABYLON.serialize()
  59828. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59829. __decorate([
  59830. BABYLON.serialize()
  59831. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59832. __decorate([
  59833. BABYLON.serialize()
  59834. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59835. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59836. })(BABYLON || (BABYLON = {}));
  59837. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59838. 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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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 TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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<shadowsFragmentFunctions>\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#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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#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\nuniform vec2 biasAndScale;\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\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\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}"};
  59839. 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,vPositionW,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(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\nuv=gl_FrontFacing ? uv : -uv;\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(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}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\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 SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\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","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#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\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)\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));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) 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 computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nconst float shadowStrength=80.;\nfloat visibility=1.0-clamp(exp(shadowStrength*shadowPixelDepth)*shadowMapSample-darkness,0.,1.);\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,visibility,vOverloadedShadowIntensity.x);\n#else\nreturn visibility;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\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"};
  59840. 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))<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=t.Vector3.Dot(this._tempVector4,r))>=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)>=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)>=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){if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,.01);for(var t,s=this._collisionCache.getMeshes(),l=Object.keys(s),n=l.length,a=0;a<n;++a)if(t=l[a],parseInt(t)!=r){var c=s[t];c.checkCollisions&&this.checkCollision(c)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=.01?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);o.Matrix.FromArray(e.worldMatrixFromCache).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),new i(t,this._collisionCache,r).collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var s={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},l={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:s};postMessage(l,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){return new r(t.r+(i.r-t.r)*n,t.g+(i.g-t.g)*n,t.b+(i.b-t.b)*n)},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;return new r(.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),.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))},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;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y)},r.Lerp=function(t,i,n){return new r(t.x+(i.x-t.x)*n,t.y+(i.y-t.y)*n)},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){return new r(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},r.Maximize=function(t,i){return new r(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},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;return e/(e-(r.Dot(i,n)-o))},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;return new r(.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),.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),.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))},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;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y,t.z*a+n.z*u+i.z*m+o.z*y)},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){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.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=M.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){return new t(this.width+i.width,this.height+i.height)},t.prototype.subtract=function(i){return new t(this.width-i.width,this.height-i.height)},t.Lerp=function(i,r,n){return new t(i.width+(r.width-i.width)*n,i.height+(r.height-i.height)*n)},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(){return new i(-this.x,-this.y,-this.z,this.w)},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;return m<-.4999999?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>.4999999?(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=M.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,t.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,\nt.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,M.Matrix[0]),a.FromRotationMatrixToRef(M.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,M.Matrix[1]),i.toRotationMatrix(M.Matrix[0]),M.Matrix[1].multiplyToRef(M.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;return new t(n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15])},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){return e.Dot(this.normal,t)<=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;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\",t[t.BONE=2]=\"BONE\"}(t.Space||(t.Space={}));var p=function(){function t(){}return t}();p.X=new e(1,0,0),p.Y=new e(0,1,0),p.Z=new e(0,0,1),t.Axis=p;var f=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;a-=(e*(m*a)+s*m+h*a-t)*(1/(3*e*m+2*s*a+h)),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=f;var x;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(x=t.Orientation||(t.Orientation={}));var l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i);return new t(Math.atan2(n.y,n.x))},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=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=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=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 z(s,h,a),m=u.angle.radians()/e;u.orientation===x.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];t+=this._points[0].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=w;var v=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=v;var d=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){return(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n},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){return(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o},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));return new t(n)},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=d;var g=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=g;var R=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=R;var T=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=T;var _=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=_;var F=function(){function t(){}return t}();F.Color3=[r.Black(),r.Black(),r.Black()],F.Vector2=[o.Zero(),o.Zero(),o.Zero()],F.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],F.Vector4=[s.Zero(),s.Zero(),s.Zero()],F.Quaternion=[a.Zero(),a.Zero()],F.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=F;var M=function(){function t(){}return t}();M.Vector3=[e.Zero()],M.Matrix=[u.Zero(),u.Zero()],M.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  59841. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59842. module.exports = BABYLON;
  59843. };