babylon.max.js 2.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Returns the Color3 hexadecimal code as a string.
  236. */
  237. Color3.prototype.toHexString = function () {
  238. var intR = (this.r * 255) | 0;
  239. var intG = (this.g * 255) | 0;
  240. var intB = (this.b * 255) | 0;
  241. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  242. };
  243. /**
  244. * Returns a new Color3 converted to linear space.
  245. */
  246. Color3.prototype.toLinearSpace = function () {
  247. var convertedColor = new Color3();
  248. this.toLinearSpaceToRef(convertedColor);
  249. return convertedColor;
  250. };
  251. /**
  252. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  253. * Returns the unmodified Color3.
  254. */
  255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  259. return this;
  260. };
  261. /**
  262. * Returns a new Color3 converted to gamma space.
  263. */
  264. Color3.prototype.toGammaSpace = function () {
  265. var convertedColor = new Color3();
  266. this.toGammaSpaceToRef(convertedColor);
  267. return convertedColor;
  268. };
  269. /**
  270. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  271. * Returns the unmodified Color3.
  272. */
  273. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  274. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  275. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  276. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  277. return this;
  278. };
  279. // Statics
  280. /**
  281. * Creates a new Color3 from the string containing valid hexadecimal values.
  282. */
  283. Color3.FromHexString = function (hex) {
  284. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  285. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  286. return new Color3(0, 0, 0);
  287. }
  288. var r = parseInt(hex.substring(1, 3), 16);
  289. var g = parseInt(hex.substring(3, 5), 16);
  290. var b = parseInt(hex.substring(5, 7), 16);
  291. return Color3.FromInts(r, g, b);
  292. };
  293. /**
  294. * Creates a new Vector3 from the startind index of the passed array.
  295. */
  296. Color3.FromArray = function (array, offset) {
  297. if (offset === void 0) { offset = 0; }
  298. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  299. };
  300. /**
  301. * Creates a new Color3 from integer values ( < 256).
  302. */
  303. Color3.FromInts = function (r, g, b) {
  304. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  305. };
  306. /**
  307. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  308. */
  309. Color3.Lerp = function (start, end, amount) {
  310. var r = start.r + ((end.r - start.r) * amount);
  311. var g = start.g + ((end.g - start.g) * amount);
  312. var b = start.b + ((end.b - start.b) * amount);
  313. return new Color3(r, g, b);
  314. };
  315. Color3.Red = function () { return new Color3(1, 0, 0); };
  316. Color3.Green = function () { return new Color3(0, 1, 0); };
  317. Color3.Blue = function () { return new Color3(0, 0, 1); };
  318. Color3.Black = function () { return new Color3(0, 0, 0); };
  319. Color3.White = function () { return new Color3(1, 1, 1); };
  320. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  321. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  322. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  323. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  324. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  325. return Color3;
  326. }());
  327. BABYLON.Color3 = Color3;
  328. var Color4 = (function () {
  329. /**
  330. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  331. */
  332. function Color4(r, g, b, a) {
  333. this.r = r;
  334. this.g = g;
  335. this.b = b;
  336. this.a = a;
  337. }
  338. // Operators
  339. /**
  340. * Adds in place the passed Color4 values to the current Color4.
  341. * Returns the updated Color4.
  342. */
  343. Color4.prototype.addInPlace = function (right) {
  344. this.r += right.r;
  345. this.g += right.g;
  346. this.b += right.b;
  347. this.a += right.a;
  348. return this;
  349. };
  350. /**
  351. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  352. */
  353. Color4.prototype.asArray = function () {
  354. var result = [];
  355. this.toArray(result, 0);
  356. return result;
  357. };
  358. /**
  359. * Stores from the starting index in the passed array the Color4 successive values.
  360. * Returns the Color4.
  361. */
  362. Color4.prototype.toArray = function (array, index) {
  363. if (index === undefined) {
  364. index = 0;
  365. }
  366. array[index] = this.r;
  367. array[index + 1] = this.g;
  368. array[index + 2] = this.b;
  369. array[index + 3] = this.a;
  370. return this;
  371. };
  372. /**
  373. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  374. */
  375. Color4.prototype.add = function (right) {
  376. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  377. };
  378. /**
  379. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  380. */
  381. Color4.prototype.subtract = function (right) {
  382. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  383. };
  384. /**
  385. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  386. * Returns the Color4.
  387. */
  388. Color4.prototype.subtractToRef = function (right, result) {
  389. result.r = this.r - right.r;
  390. result.g = this.g - right.g;
  391. result.b = this.b - right.b;
  392. result.a = this.a - right.a;
  393. return this;
  394. };
  395. /**
  396. * Creates a new Color4 with the current Color4 values multiplied by scale.
  397. */
  398. Color4.prototype.scale = function (scale) {
  399. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  400. };
  401. /**
  402. * Multiplies the current Color4 values by scale and stores the result in "result".
  403. * Returns the Color4.
  404. */
  405. Color4.prototype.scaleToRef = function (scale, result) {
  406. result.r = this.r * scale;
  407. result.g = this.g * scale;
  408. result.b = this.b * scale;
  409. result.a = this.a * scale;
  410. return this;
  411. };
  412. /**
  413. * Multipy an RGBA Color4 value by another and return a new Color4 object
  414. * @param color The Color4 (RGBA) value to multiply by
  415. * @returns A new Color4.
  416. */
  417. Color4.prototype.multiply = function (color) {
  418. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  419. };
  420. /**
  421. * Multipy an RGBA Color4 value by another and push the result in a reference value
  422. * @param color The Color4 (RGBA) value to multiply by
  423. * @param result The Color4 (RGBA) to fill the result in
  424. * @returns the result Color4.
  425. */
  426. Color4.prototype.multiplyToRef = function (color, result) {
  427. result.r = this.r * color.r;
  428. result.g = this.g * color.g;
  429. result.b = this.b * color.b;
  430. result.a = this.a * color.a;
  431. return result;
  432. };
  433. /**
  434. * Returns a string with the Color4 values.
  435. */
  436. Color4.prototype.toString = function () {
  437. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  438. };
  439. /**
  440. * Returns the string "Color4"
  441. */
  442. Color4.prototype.getClassName = function () {
  443. return "Color4";
  444. };
  445. /**
  446. * Return the Color4 hash code as a number.
  447. */
  448. Color4.prototype.getHashCode = function () {
  449. var hash = this.r || 0;
  450. hash = (hash * 397) ^ (this.g || 0);
  451. hash = (hash * 397) ^ (this.b || 0);
  452. hash = (hash * 397) ^ (this.a || 0);
  453. return hash;
  454. };
  455. /**
  456. * Creates a new Color4 copied from the current one.
  457. */
  458. Color4.prototype.clone = function () {
  459. return new Color4(this.r, this.g, this.b, this.a);
  460. };
  461. /**
  462. * Copies the passed Color4 values into the current one.
  463. * Returns the updated Color4.
  464. */
  465. Color4.prototype.copyFrom = function (source) {
  466. this.r = source.r;
  467. this.g = source.g;
  468. this.b = source.b;
  469. this.a = source.a;
  470. return this;
  471. };
  472. /**
  473. * Returns a string containing the hexadecimal Color4 code.
  474. */
  475. Color4.prototype.toHexString = function () {
  476. var intR = (this.r * 255) | 0;
  477. var intG = (this.g * 255) | 0;
  478. var intB = (this.b * 255) | 0;
  479. var intA = (this.a * 255) | 0;
  480. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  481. };
  482. // Statics
  483. /**
  484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  485. */
  486. Color4.FromHexString = function (hex) {
  487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  489. return new Color4(0.0, 0.0, 0.0, 0.0);
  490. }
  491. var r = parseInt(hex.substring(1, 3), 16);
  492. var g = parseInt(hex.substring(3, 5), 16);
  493. var b = parseInt(hex.substring(5, 7), 16);
  494. var a = parseInt(hex.substring(7, 9), 16);
  495. return Color4.FromInts(r, g, b, a);
  496. };
  497. /**
  498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  499. */
  500. Color4.Lerp = function (left, right, amount) {
  501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  502. Color4.LerpToRef(left, right, amount, result);
  503. return result;
  504. };
  505. /**
  506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  507. */
  508. Color4.LerpToRef = function (left, right, amount, result) {
  509. result.r = left.r + (right.r - left.r) * amount;
  510. result.g = left.g + (right.g - left.g) * amount;
  511. result.b = left.b + (right.b - left.b) * amount;
  512. result.a = left.a + (right.a - left.a) * amount;
  513. };
  514. /**
  515. * Creates a new Color4 from the starting index element of the passed array.
  516. */
  517. Color4.FromArray = function (array, offset) {
  518. if (offset === void 0) { offset = 0; }
  519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  520. };
  521. /**
  522. * Creates a new Color4 from the passed integers ( < 256 ).
  523. */
  524. Color4.FromInts = function (r, g, b, a) {
  525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  526. };
  527. Color4.CheckColors4 = function (colors, count) {
  528. // Check if color3 was used
  529. if (colors.length === count * 3) {
  530. var colors4 = [];
  531. for (var index = 0; index < colors.length; index += 3) {
  532. var newIndex = (index / 3) * 4;
  533. colors4[newIndex] = colors[index];
  534. colors4[newIndex + 1] = colors[index + 1];
  535. colors4[newIndex + 2] = colors[index + 2];
  536. colors4[newIndex + 3] = 1.0;
  537. }
  538. return colors4;
  539. }
  540. return colors;
  541. };
  542. return Color4;
  543. }());
  544. BABYLON.Color4 = Color4;
  545. var Vector2 = (function () {
  546. /**
  547. * Creates a new Vector2 from the passed x and y coordinates.
  548. */
  549. function Vector2(x, y) {
  550. this.x = x;
  551. this.y = y;
  552. }
  553. /**
  554. * Returns a string with the Vector2 coordinates.
  555. */
  556. Vector2.prototype.toString = function () {
  557. return "{X: " + this.x + " Y:" + this.y + "}";
  558. };
  559. /**
  560. * Returns the string "Vector2"
  561. */
  562. Vector2.prototype.getClassName = function () {
  563. return "Vector2";
  564. };
  565. /**
  566. * Returns the Vector2 hash code as a number.
  567. */
  568. Vector2.prototype.getHashCode = function () {
  569. var hash = this.x || 0;
  570. hash = (hash * 397) ^ (this.y || 0);
  571. return hash;
  572. };
  573. // Operators
  574. /**
  575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  576. * Returns the Vector2.
  577. */
  578. Vector2.prototype.toArray = function (array, index) {
  579. if (index === void 0) { index = 0; }
  580. array[index] = this.x;
  581. array[index + 1] = this.y;
  582. return this;
  583. };
  584. /**
  585. * Returns a new array with 2 elements : the Vector2 coordinates.
  586. */
  587. Vector2.prototype.asArray = function () {
  588. var result = [];
  589. this.toArray(result, 0);
  590. return result;
  591. };
  592. /**
  593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  594. * Returns the updated Vector2.
  595. */
  596. Vector2.prototype.copyFrom = function (source) {
  597. this.x = source.x;
  598. this.y = source.y;
  599. return this;
  600. };
  601. /**
  602. * Sets the Vector2 coordinates with the passed floats.
  603. * Returns the updated Vector2.
  604. */
  605. Vector2.prototype.copyFromFloats = function (x, y) {
  606. this.x = x;
  607. this.y = y;
  608. return this;
  609. };
  610. /**
  611. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  612. */
  613. Vector2.prototype.add = function (otherVector) {
  614. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  615. };
  616. /**
  617. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  618. * Returns the Vector2.
  619. */
  620. Vector2.prototype.addToRef = function (otherVector, result) {
  621. result.x = this.x + otherVector.x;
  622. result.y = this.y + otherVector.y;
  623. return this;
  624. };
  625. /**
  626. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  627. * Returns the updated Vector2.
  628. */
  629. Vector2.prototype.addInPlace = function (otherVector) {
  630. this.x += otherVector.x;
  631. this.y += otherVector.y;
  632. return this;
  633. };
  634. /**
  635. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  636. */
  637. Vector2.prototype.addVector3 = function (otherVector) {
  638. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  639. };
  640. /**
  641. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  642. */
  643. Vector2.prototype.subtract = function (otherVector) {
  644. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  645. };
  646. /**
  647. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  648. * Returns the Vector2.
  649. */
  650. Vector2.prototype.subtractToRef = function (otherVector, result) {
  651. result.x = this.x - otherVector.x;
  652. result.y = this.y - otherVector.y;
  653. return this;
  654. };
  655. /**
  656. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  657. * Returns the updated Vector2.
  658. */
  659. Vector2.prototype.subtractInPlace = function (otherVector) {
  660. this.x -= otherVector.x;
  661. this.y -= otherVector.y;
  662. return this;
  663. };
  664. /**
  665. * Multiplies in place the current Vector2 coordinates by the passed ones.
  666. * Returns the updated Vector2.
  667. */
  668. Vector2.prototype.multiplyInPlace = function (otherVector) {
  669. this.x *= otherVector.x;
  670. this.y *= otherVector.y;
  671. return this;
  672. };
  673. /**
  674. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  675. */
  676. Vector2.prototype.multiply = function (otherVector) {
  677. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  678. };
  679. /**
  680. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  681. * Returns the Vector2.
  682. */
  683. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  684. result.x = this.x * otherVector.x;
  685. result.y = this.y * otherVector.y;
  686. return this;
  687. };
  688. /**
  689. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  690. */
  691. Vector2.prototype.multiplyByFloats = function (x, y) {
  692. return new Vector2(this.x * x, this.y * y);
  693. };
  694. /**
  695. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  696. */
  697. Vector2.prototype.divide = function (otherVector) {
  698. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  699. };
  700. /**
  701. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  702. * Returns the Vector2.
  703. */
  704. Vector2.prototype.divideToRef = function (otherVector, result) {
  705. result.x = this.x / otherVector.x;
  706. result.y = this.y / otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 with current Vector2 negated coordinates.
  711. */
  712. Vector2.prototype.negate = function () {
  713. return new Vector2(-this.x, -this.y);
  714. };
  715. /**
  716. * Multiply the Vector2 coordinates by scale.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.scaleInPlace = function (scale) {
  720. this.x *= scale;
  721. this.y *= scale;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  726. */
  727. Vector2.prototype.scale = function (scale) {
  728. return new Vector2(this.x * scale, this.y * scale);
  729. };
  730. /**
  731. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  732. */
  733. Vector2.prototype.equals = function (otherVector) {
  734. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  735. };
  736. /**
  737. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  738. */
  739. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  740. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  741. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  742. };
  743. // Properties
  744. /**
  745. * Returns the vector length (float).
  746. */
  747. Vector2.prototype.length = function () {
  748. return Math.sqrt(this.x * this.x + this.y * this.y);
  749. };
  750. /**
  751. * Returns the vector squared length (float);
  752. */
  753. Vector2.prototype.lengthSquared = function () {
  754. return (this.x * this.x + this.y * this.y);
  755. };
  756. // Methods
  757. /**
  758. * Normalize the vector.
  759. * Returns the updated Vector2.
  760. */
  761. Vector2.prototype.normalize = function () {
  762. var len = this.length();
  763. if (len === 0)
  764. return this;
  765. var num = 1.0 / len;
  766. this.x *= num;
  767. this.y *= num;
  768. return this;
  769. };
  770. /**
  771. * Returns a new Vector2 copied from the Vector2.
  772. */
  773. Vector2.prototype.clone = function () {
  774. return new Vector2(this.x, this.y);
  775. };
  776. // Statics
  777. /**
  778. * Returns a new Vector2(0, 0)
  779. */
  780. Vector2.Zero = function () {
  781. return new Vector2(0, 0);
  782. };
  783. /**
  784. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  785. */
  786. Vector2.FromArray = function (array, offset) {
  787. if (offset === void 0) { offset = 0; }
  788. return new Vector2(array[offset], array[offset + 1]);
  789. };
  790. /**
  791. * Sets "result" from the passed index element of the passed array or Float32Array.
  792. * Returns the Vector2.
  793. */
  794. Vector2.FromArrayToRef = function (array, offset, result) {
  795. result.x = array[offset];
  796. result.y = array[offset + 1];
  797. };
  798. /**
  799. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  800. */
  801. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  802. var squared = amount * amount;
  803. var cubed = amount * squared;
  804. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  805. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  806. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  807. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  808. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  809. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  810. return new Vector2(x, y);
  811. };
  812. /**
  813. * 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".
  814. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  815. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  816. */
  817. Vector2.Clamp = function (value, min, max) {
  818. var x = value.x;
  819. x = (x > max.x) ? max.x : x;
  820. x = (x < min.x) ? min.x : x;
  821. var y = value.y;
  822. y = (y > max.y) ? max.y : y;
  823. y = (y < min.y) ? min.y : y;
  824. return new Vector2(x, y);
  825. };
  826. /**
  827. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  828. */
  829. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  830. var squared = amount * amount;
  831. var cubed = amount * squared;
  832. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  833. var part2 = (-2.0 * cubed) + (3.0 * squared);
  834. var part3 = (cubed - (2.0 * squared)) + amount;
  835. var part4 = cubed - squared;
  836. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  837. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  838. return new Vector2(x, y);
  839. };
  840. /**
  841. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  842. */
  843. Vector2.Lerp = function (start, end, amount) {
  844. var x = start.x + ((end.x - start.x) * amount);
  845. var y = start.y + ((end.y - start.y) * amount);
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * Returns the dot product (float) of the vector "left" and the vector "right".
  850. */
  851. Vector2.Dot = function (left, right) {
  852. return left.x * right.x + left.y * right.y;
  853. };
  854. /**
  855. * Returns a new Vector2 equal to the normalized passed vector.
  856. */
  857. Vector2.Normalize = function (vector) {
  858. var newVector = vector.clone();
  859. newVector.normalize();
  860. return newVector;
  861. };
  862. /**
  863. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  864. */
  865. Vector2.Minimize = function (left, right) {
  866. var x = (left.x < right.x) ? left.x : right.x;
  867. var y = (left.y < right.y) ? left.y : right.y;
  868. return new Vector2(x, y);
  869. };
  870. /**
  871. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  872. */
  873. Vector2.Maximize = function (left, right) {
  874. var x = (left.x > right.x) ? left.x : right.x;
  875. var y = (left.y > right.y) ? left.y : right.y;
  876. return new Vector2(x, y);
  877. };
  878. /**
  879. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  880. */
  881. Vector2.Transform = function (vector, transformation) {
  882. var r = Vector2.Zero();
  883. Vector2.TransformToRef(vector, transformation, r);
  884. return r;
  885. };
  886. /**
  887. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  888. */
  889. Vector2.TransformToRef = function (vector, transformation, result) {
  890. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  891. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  892. result.x = x;
  893. result.y = y;
  894. };
  895. /**
  896. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  897. */
  898. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  899. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  900. var sign = a < 0 ? -1 : 1;
  901. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  902. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  903. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  904. };
  905. /**
  906. * Returns the distance (float) between the vectors "value1" and "value2".
  907. */
  908. Vector2.Distance = function (value1, value2) {
  909. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  910. };
  911. /**
  912. * Returns the squared distance (float) between the vectors "value1" and "value2".
  913. */
  914. Vector2.DistanceSquared = function (value1, value2) {
  915. var x = value1.x - value2.x;
  916. var y = value1.y - value2.y;
  917. return (x * x) + (y * y);
  918. };
  919. /**
  920. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  921. */
  922. Vector2.Center = function (value1, value2) {
  923. var center = value1.add(value2);
  924. center.scaleInPlace(0.5);
  925. return center;
  926. };
  927. /**
  928. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  929. */
  930. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  931. var l2 = Vector2.DistanceSquared(segA, segB);
  932. if (l2 === 0.0) {
  933. return Vector2.Distance(p, segA);
  934. }
  935. var v = segB.subtract(segA);
  936. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  937. var proj = segA.add(v.multiplyByFloats(t, t));
  938. return Vector2.Distance(p, proj);
  939. };
  940. return Vector2;
  941. }());
  942. BABYLON.Vector2 = Vector2;
  943. var Vector3 = (function () {
  944. /**
  945. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  946. * A Vector3 is the main object used in 3D geometry.
  947. * It can represent etiher the coordinates of a point the space, either a direction.
  948. */
  949. function Vector3(x, y, z) {
  950. this.x = x;
  951. this.y = y;
  952. this.z = z;
  953. }
  954. /**
  955. * Returns a string with the Vector3 coordinates.
  956. */
  957. Vector3.prototype.toString = function () {
  958. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  959. };
  960. /**
  961. * Returns the string "Vector3"
  962. */
  963. Vector3.prototype.getClassName = function () {
  964. return "Vector3";
  965. };
  966. /**
  967. * Returns the Vector hash code.
  968. */
  969. Vector3.prototype.getHashCode = function () {
  970. var hash = this.x || 0;
  971. hash = (hash * 397) ^ (this.y || 0);
  972. hash = (hash * 397) ^ (this.z || 0);
  973. return hash;
  974. };
  975. // Operators
  976. /**
  977. * Returns a new array with three elements : the coordinates the Vector3.
  978. */
  979. Vector3.prototype.asArray = function () {
  980. var result = [];
  981. this.toArray(result, 0);
  982. return result;
  983. };
  984. /**
  985. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  986. * Returns the Vector3.
  987. */
  988. Vector3.prototype.toArray = function (array, index) {
  989. if (index === void 0) { index = 0; }
  990. array[index] = this.x;
  991. array[index + 1] = this.y;
  992. array[index + 2] = this.z;
  993. return this;
  994. };
  995. /**
  996. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  997. */
  998. Vector3.prototype.toQuaternion = function () {
  999. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1000. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1001. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1002. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1003. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1004. var cosy = Math.cos(this.y * 0.5);
  1005. var siny = Math.sin(this.y * 0.5);
  1006. result.x = coszMinusx * siny;
  1007. result.y = -sinzMinusx * siny;
  1008. result.z = sinxPlusz * cosy;
  1009. result.w = cosxPlusz * cosy;
  1010. return result;
  1011. };
  1012. /**
  1013. * Adds the passed vector to the current Vector3.
  1014. * Returns the updated Vector3.
  1015. */
  1016. Vector3.prototype.addInPlace = function (otherVector) {
  1017. this.x += otherVector.x;
  1018. this.y += otherVector.y;
  1019. this.z += otherVector.z;
  1020. return this;
  1021. };
  1022. /**
  1023. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1024. */
  1025. Vector3.prototype.add = function (otherVector) {
  1026. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1027. };
  1028. /**
  1029. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1030. * Returns the current Vector3.
  1031. */
  1032. Vector3.prototype.addToRef = function (otherVector, result) {
  1033. result.x = this.x + otherVector.x;
  1034. result.y = this.y + otherVector.y;
  1035. result.z = this.z + otherVector.z;
  1036. return this;
  1037. };
  1038. /**
  1039. * Subtract the passed vector from the current Vector3.
  1040. * Returns the updated Vector3.
  1041. */
  1042. Vector3.prototype.subtractInPlace = function (otherVector) {
  1043. this.x -= otherVector.x;
  1044. this.y -= otherVector.y;
  1045. this.z -= otherVector.z;
  1046. return this;
  1047. };
  1048. /**
  1049. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1050. */
  1051. Vector3.prototype.subtract = function (otherVector) {
  1052. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1053. };
  1054. /**
  1055. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1056. * Returns the current Vector3.
  1057. */
  1058. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1059. result.x = this.x - otherVector.x;
  1060. result.y = this.y - otherVector.y;
  1061. result.z = this.z - otherVector.z;
  1062. return this;
  1063. };
  1064. /**
  1065. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1066. */
  1067. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1068. return new Vector3(this.x - x, this.y - y, this.z - z);
  1069. };
  1070. /**
  1071. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1072. * Returns the current Vector3.
  1073. */
  1074. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1075. result.x = this.x - x;
  1076. result.y = this.y - y;
  1077. result.z = this.z - z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1082. */
  1083. Vector3.prototype.negate = function () {
  1084. return new Vector3(-this.x, -this.y, -this.z);
  1085. };
  1086. /**
  1087. * Multiplies the Vector3 coordinates by the float "scale".
  1088. * Returns the updated Vector3.
  1089. */
  1090. Vector3.prototype.scaleInPlace = function (scale) {
  1091. this.x *= scale;
  1092. this.y *= scale;
  1093. this.z *= scale;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1098. */
  1099. Vector3.prototype.scale = function (scale) {
  1100. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1101. };
  1102. /**
  1103. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.scaleToRef = function (scale, result) {
  1107. result.x = this.x * scale;
  1108. result.y = this.y * scale;
  1109. result.z = this.z * scale;
  1110. return this;
  1111. };
  1112. /**
  1113. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1114. */
  1115. Vector3.prototype.equals = function (otherVector) {
  1116. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1117. };
  1118. /**
  1119. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1120. */
  1121. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1122. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1123. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1124. };
  1125. /**
  1126. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1127. */
  1128. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1129. return this.x === x && this.y === y && this.z === z;
  1130. };
  1131. /**
  1132. * Muliplies the current Vector3 coordinates by the passed ones.
  1133. * Returns the updated Vector3.
  1134. */
  1135. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1136. this.x *= otherVector.x;
  1137. this.y *= otherVector.y;
  1138. this.z *= otherVector.z;
  1139. return this;
  1140. };
  1141. /**
  1142. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1143. */
  1144. Vector3.prototype.multiply = function (otherVector) {
  1145. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1146. };
  1147. /**
  1148. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1149. * Returns the current Vector3.
  1150. */
  1151. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1152. result.x = this.x * otherVector.x;
  1153. result.y = this.y * otherVector.y;
  1154. result.z = this.z * otherVector.z;
  1155. return this;
  1156. };
  1157. /**
  1158. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1159. */
  1160. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1161. return new Vector3(this.x * x, this.y * y, this.z * z);
  1162. };
  1163. /**
  1164. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1165. */
  1166. Vector3.prototype.divide = function (otherVector) {
  1167. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1168. };
  1169. /**
  1170. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1171. * Returns the current Vector3.
  1172. */
  1173. Vector3.prototype.divideToRef = function (otherVector, result) {
  1174. result.x = this.x / otherVector.x;
  1175. result.y = this.y / otherVector.y;
  1176. result.z = this.z / otherVector.z;
  1177. return this;
  1178. };
  1179. /**
  1180. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1181. * Returns the updated Vector3.
  1182. */
  1183. Vector3.prototype.MinimizeInPlace = function (other) {
  1184. if (other.x < this.x)
  1185. this.x = other.x;
  1186. if (other.y < this.y)
  1187. this.y = other.y;
  1188. if (other.z < this.z)
  1189. this.z = other.z;
  1190. return this;
  1191. };
  1192. /**
  1193. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1194. * Returns the updated Vector3.
  1195. */
  1196. Vector3.prototype.MaximizeInPlace = function (other) {
  1197. if (other.x > this.x)
  1198. this.x = other.x;
  1199. if (other.y > this.y)
  1200. this.y = other.y;
  1201. if (other.z > this.z)
  1202. this.z = other.z;
  1203. return this;
  1204. };
  1205. // Properties
  1206. /**
  1207. * Returns the length of the Vector3 (float).
  1208. */
  1209. Vector3.prototype.length = function () {
  1210. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1211. };
  1212. /**
  1213. * Returns the squared length of the Vector3 (float).
  1214. */
  1215. Vector3.prototype.lengthSquared = function () {
  1216. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1217. };
  1218. // Methods
  1219. /**
  1220. * Normalize the current Vector3.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.normalize = function () {
  1224. var len = this.length();
  1225. if (len === 0 || len === 1.0)
  1226. return this;
  1227. var num = 1.0 / len;
  1228. this.x *= num;
  1229. this.y *= num;
  1230. this.z *= num;
  1231. return this;
  1232. };
  1233. /**
  1234. * Returns a new Vector3 copied from the current Vector3.
  1235. */
  1236. Vector3.prototype.clone = function () {
  1237. return new Vector3(this.x, this.y, this.z);
  1238. };
  1239. /**
  1240. * Copies the passed vector coordinates to the current Vector3 ones.
  1241. * Returns the updated Vector3.
  1242. */
  1243. Vector3.prototype.copyFrom = function (source) {
  1244. this.x = source.x;
  1245. this.y = source.y;
  1246. this.z = source.z;
  1247. return this;
  1248. };
  1249. /**
  1250. * Copies the passed floats to the current Vector3 coordinates.
  1251. * Returns the updated Vector3.
  1252. */
  1253. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1254. this.x = x;
  1255. this.y = y;
  1256. this.z = z;
  1257. return this;
  1258. };
  1259. // Statics
  1260. /**
  1261. *
  1262. */
  1263. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1264. var d0 = Vector3.Dot(vector0, axis) - size;
  1265. var d1 = Vector3.Dot(vector1, axis) - size;
  1266. var s = d0 / (d0 - d1);
  1267. return s;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1271. */
  1272. Vector3.FromArray = function (array, offset) {
  1273. if (!offset) {
  1274. offset = 0;
  1275. }
  1276. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1277. };
  1278. /**
  1279. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1280. */
  1281. Vector3.FromFloatArray = function (array, offset) {
  1282. if (!offset) {
  1283. offset = 0;
  1284. }
  1285. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1286. };
  1287. /**
  1288. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1289. */
  1290. Vector3.FromArrayToRef = function (array, offset, result) {
  1291. result.x = array[offset];
  1292. result.y = array[offset + 1];
  1293. result.z = array[offset + 2];
  1294. };
  1295. /**
  1296. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1297. */
  1298. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1299. result.x = array[offset];
  1300. result.y = array[offset + 1];
  1301. result.z = array[offset + 2];
  1302. };
  1303. /**
  1304. * Sets the passed vector "result" with the passed floats.
  1305. */
  1306. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1307. result.x = x;
  1308. result.y = y;
  1309. result.z = z;
  1310. };
  1311. /**
  1312. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1313. */
  1314. Vector3.Zero = function () {
  1315. return new Vector3(0.0, 0.0, 0.0);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1319. */
  1320. Vector3.Up = function () {
  1321. return new Vector3(0.0, 1.0, 0.0);
  1322. };
  1323. /**
  1324. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1325. */
  1326. Vector3.Forward = function () {
  1327. return new Vector3(0.0, 0.0, 1.0);
  1328. };
  1329. /**
  1330. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1331. */
  1332. Vector3.Right = function () {
  1333. return new Vector3(1.0, 0.0, 0.0);
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1337. */
  1338. Vector3.Left = function () {
  1339. return new Vector3(-1.0, 0.0, 0.0);
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1343. * This method computes tranformed coordinates only, not transformed direction vectors.
  1344. */
  1345. Vector3.TransformCoordinates = function (vector, transformation) {
  1346. var result = Vector3.Zero();
  1347. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1348. return result;
  1349. };
  1350. /**
  1351. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1352. * This method computes tranformed coordinates only, not transformed direction vectors.
  1353. */
  1354. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1355. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1356. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1357. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1358. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1359. result.x = x / w;
  1360. result.y = y / w;
  1361. result.z = z / w;
  1362. };
  1363. /**
  1364. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1365. * This method computes tranformed coordinates only, not transformed direction vectors.
  1366. */
  1367. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1368. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1369. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1370. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1371. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1372. result.x = rx / rw;
  1373. result.y = ry / rw;
  1374. result.z = rz / rw;
  1375. };
  1376. /**
  1377. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1378. * This methods computes transformed normalized direction vectors only.
  1379. */
  1380. Vector3.TransformNormal = function (vector, transformation) {
  1381. var result = Vector3.Zero();
  1382. Vector3.TransformNormalToRef(vector, transformation, result);
  1383. return result;
  1384. };
  1385. /**
  1386. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1387. * This methods computes transformed normalized direction vectors only.
  1388. */
  1389. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1390. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1391. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1392. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1393. result.x = x;
  1394. result.y = y;
  1395. result.z = z;
  1396. };
  1397. /**
  1398. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1399. * This methods computes transformed normalized direction vectors only.
  1400. */
  1401. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1402. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1403. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1404. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1405. };
  1406. /**
  1407. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1408. */
  1409. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1410. var squared = amount * amount;
  1411. var cubed = amount * squared;
  1412. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1413. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1414. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1415. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1416. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1417. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1418. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1419. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1420. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1421. return new Vector3(x, y, z);
  1422. };
  1423. /**
  1424. * 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".
  1425. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1426. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1427. */
  1428. Vector3.Clamp = function (value, min, max) {
  1429. var x = value.x;
  1430. x = (x > max.x) ? max.x : x;
  1431. x = (x < min.x) ? min.x : x;
  1432. var y = value.y;
  1433. y = (y > max.y) ? max.y : y;
  1434. y = (y < min.y) ? min.y : y;
  1435. var z = value.z;
  1436. z = (z > max.z) ? max.z : z;
  1437. z = (z < min.z) ? min.z : z;
  1438. return new Vector3(x, y, z);
  1439. };
  1440. /**
  1441. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1442. */
  1443. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1444. var squared = amount * amount;
  1445. var cubed = amount * squared;
  1446. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1447. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1448. var part3 = (cubed - (2.0 * squared)) + amount;
  1449. var part4 = cubed - squared;
  1450. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1451. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1452. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1453. return new Vector3(x, y, z);
  1454. };
  1455. /**
  1456. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1457. */
  1458. Vector3.Lerp = function (start, end, amount) {
  1459. var result = new Vector3(0, 0, 0);
  1460. Vector3.LerpToRef(start, end, amount, result);
  1461. return result;
  1462. };
  1463. /**
  1464. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1465. */
  1466. Vector3.LerpToRef = function (start, end, amount, result) {
  1467. result.x = start.x + ((end.x - start.x) * amount);
  1468. result.y = start.y + ((end.y - start.y) * amount);
  1469. result.z = start.z + ((end.z - start.z) * amount);
  1470. };
  1471. /**
  1472. * Returns the dot product (float) between the vectors "left" and "right".
  1473. */
  1474. Vector3.Dot = function (left, right) {
  1475. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1476. };
  1477. /**
  1478. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1479. * The cross product is then orthogonal to both "left" and "right".
  1480. */
  1481. Vector3.Cross = function (left, right) {
  1482. var result = Vector3.Zero();
  1483. Vector3.CrossToRef(left, right, result);
  1484. return result;
  1485. };
  1486. /**
  1487. * Sets the passed vector "result" with the cross product of "left" and "right".
  1488. * The cross product is then orthogonal to both "left" and "right".
  1489. */
  1490. Vector3.CrossToRef = function (left, right, result) {
  1491. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1492. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1493. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1494. result.copyFrom(Tmp.Vector3[0]);
  1495. };
  1496. /**
  1497. * Returns a new Vector3 as the normalization of the passed vector.
  1498. */
  1499. Vector3.Normalize = function (vector) {
  1500. var result = Vector3.Zero();
  1501. Vector3.NormalizeToRef(vector, result);
  1502. return result;
  1503. };
  1504. /**
  1505. * Sets the passed vector "result" with the normalization of the passed first vector.
  1506. */
  1507. Vector3.NormalizeToRef = function (vector, result) {
  1508. result.copyFrom(vector);
  1509. result.normalize();
  1510. };
  1511. Vector3.Project = function (vector, world, transform, viewport) {
  1512. var cw = viewport.width;
  1513. var ch = viewport.height;
  1514. var cx = viewport.x;
  1515. var cy = viewport.y;
  1516. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1517. 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);
  1518. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1519. world.multiplyToRef(transform, matrix);
  1520. matrix.multiplyToRef(viewportMatrix, matrix);
  1521. return Vector3.TransformCoordinates(vector, matrix);
  1522. };
  1523. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1524. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1525. world.multiplyToRef(transform, matrix);
  1526. matrix.invert();
  1527. source.x = source.x / viewportWidth * 2 - 1;
  1528. source.y = -(source.y / viewportHeight * 2 - 1);
  1529. var vector = Vector3.TransformCoordinates(source, matrix);
  1530. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1531. if (MathTools.WithinEpsilon(num, 1.0)) {
  1532. vector = vector.scale(1.0 / num);
  1533. }
  1534. return vector;
  1535. };
  1536. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1537. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1538. world.multiplyToRef(view, matrix);
  1539. matrix.multiplyToRef(projection, matrix);
  1540. matrix.invert();
  1541. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1542. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1543. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1544. if (MathTools.WithinEpsilon(num, 1.0)) {
  1545. vector = vector.scale(1.0 / num);
  1546. }
  1547. return vector;
  1548. };
  1549. Vector3.Minimize = function (left, right) {
  1550. var min = left.clone();
  1551. min.MinimizeInPlace(right);
  1552. return min;
  1553. };
  1554. Vector3.Maximize = function (left, right) {
  1555. var max = left.clone();
  1556. max.MaximizeInPlace(right);
  1557. return max;
  1558. };
  1559. /**
  1560. * Returns the distance (float) between the vectors "value1" and "value2".
  1561. */
  1562. Vector3.Distance = function (value1, value2) {
  1563. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1564. };
  1565. /**
  1566. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1567. */
  1568. Vector3.DistanceSquared = function (value1, value2) {
  1569. var x = value1.x - value2.x;
  1570. var y = value1.y - value2.y;
  1571. var z = value1.z - value2.z;
  1572. return (x * x) + (y * y) + (z * z);
  1573. };
  1574. /**
  1575. * Returns a new Vector3 located at the center between "value1" and "value2".
  1576. */
  1577. Vector3.Center = function (value1, value2) {
  1578. var center = value1.add(value2);
  1579. center.scaleInPlace(0.5);
  1580. return center;
  1581. };
  1582. /**
  1583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1585. * to something in order to rotate it from its local system to the given target system.
  1586. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1587. * Returns a new Vector3.
  1588. */
  1589. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1590. var rotation = Vector3.Zero();
  1591. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1592. return rotation;
  1593. };
  1594. /**
  1595. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1596. */
  1597. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1598. var quat = BABYLON.Tmp.Quaternion[1];
  1599. Quaternion.QuaternionRotationFromAxisToRef(axis1, axis2, axis3, quat);
  1600. quat.toEulerAnglesToRef(ref);
  1601. };
  1602. return Vector3;
  1603. }());
  1604. BABYLON.Vector3 = Vector3;
  1605. //Vector4 class created for EulerAngle class conversion to Quaternion
  1606. var Vector4 = (function () {
  1607. /**
  1608. * Creates a Vector4 object from the passed floats.
  1609. */
  1610. function Vector4(x, y, z, w) {
  1611. this.x = x;
  1612. this.y = y;
  1613. this.z = z;
  1614. this.w = w;
  1615. }
  1616. /**
  1617. * Returns the string with the Vector4 coordinates.
  1618. */
  1619. Vector4.prototype.toString = function () {
  1620. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1621. };
  1622. /**
  1623. * Returns the string "Vector4".
  1624. */
  1625. Vector4.prototype.getClassName = function () {
  1626. return "Vector4";
  1627. };
  1628. /**
  1629. * Returns the Vector4 hash code.
  1630. */
  1631. Vector4.prototype.getHashCode = function () {
  1632. var hash = this.x || 0;
  1633. hash = (hash * 397) ^ (this.y || 0);
  1634. hash = (hash * 397) ^ (this.z || 0);
  1635. hash = (hash * 397) ^ (this.w || 0);
  1636. return hash;
  1637. };
  1638. // Operators
  1639. /**
  1640. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1641. */
  1642. Vector4.prototype.asArray = function () {
  1643. var result = [];
  1644. this.toArray(result, 0);
  1645. return result;
  1646. };
  1647. /**
  1648. * Populates the passed array from the passed index with the Vector4 coordinates.
  1649. * Returns the Vector4.
  1650. */
  1651. Vector4.prototype.toArray = function (array, index) {
  1652. if (index === undefined) {
  1653. index = 0;
  1654. }
  1655. array[index] = this.x;
  1656. array[index + 1] = this.y;
  1657. array[index + 2] = this.z;
  1658. array[index + 3] = this.w;
  1659. return this;
  1660. };
  1661. /**
  1662. * Adds the passed vector to the current Vector4.
  1663. * Returns the updated Vector4.
  1664. */
  1665. Vector4.prototype.addInPlace = function (otherVector) {
  1666. this.x += otherVector.x;
  1667. this.y += otherVector.y;
  1668. this.z += otherVector.z;
  1669. this.w += otherVector.w;
  1670. return this;
  1671. };
  1672. /**
  1673. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1674. */
  1675. Vector4.prototype.add = function (otherVector) {
  1676. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1677. };
  1678. /**
  1679. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1680. * Returns the current Vector4.
  1681. */
  1682. Vector4.prototype.addToRef = function (otherVector, result) {
  1683. result.x = this.x + otherVector.x;
  1684. result.y = this.y + otherVector.y;
  1685. result.z = this.z + otherVector.z;
  1686. result.w = this.w + otherVector.w;
  1687. return this;
  1688. };
  1689. /**
  1690. * Subtract in place the passed vector from the current Vector4.
  1691. * Returns the updated Vector4.
  1692. */
  1693. Vector4.prototype.subtractInPlace = function (otherVector) {
  1694. this.x -= otherVector.x;
  1695. this.y -= otherVector.y;
  1696. this.z -= otherVector.z;
  1697. this.w -= otherVector.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1702. */
  1703. Vector4.prototype.subtract = function (otherVector) {
  1704. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1705. };
  1706. /**
  1707. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1708. * Returns the current Vector4.
  1709. */
  1710. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1711. result.x = this.x - otherVector.x;
  1712. result.y = this.y - otherVector.y;
  1713. result.z = this.z - otherVector.z;
  1714. result.w = this.w - otherVector.w;
  1715. return this;
  1716. };
  1717. /**
  1718. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1719. */
  1720. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1721. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1722. };
  1723. /**
  1724. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1725. * Returns the current Vector4.
  1726. */
  1727. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1728. result.x = this.x - x;
  1729. result.y = this.y - y;
  1730. result.z = this.z - z;
  1731. result.w = this.w - w;
  1732. return this;
  1733. };
  1734. /**
  1735. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1736. */
  1737. Vector4.prototype.negate = function () {
  1738. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1739. };
  1740. /**
  1741. * Multiplies the current Vector4 coordinates by scale (float).
  1742. * Returns the updated Vector4.
  1743. */
  1744. Vector4.prototype.scaleInPlace = function (scale) {
  1745. this.x *= scale;
  1746. this.y *= scale;
  1747. this.z *= scale;
  1748. this.w *= scale;
  1749. return this;
  1750. };
  1751. /**
  1752. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1753. */
  1754. Vector4.prototype.scale = function (scale) {
  1755. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1756. };
  1757. /**
  1758. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1759. * Returns the current Vector4.
  1760. */
  1761. Vector4.prototype.scaleToRef = function (scale, result) {
  1762. result.x = this.x * scale;
  1763. result.y = this.y * scale;
  1764. result.z = this.z * scale;
  1765. result.w = this.w * scale;
  1766. return this;
  1767. };
  1768. /**
  1769. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1770. */
  1771. Vector4.prototype.equals = function (otherVector) {
  1772. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1773. };
  1774. /**
  1775. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1776. */
  1777. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1779. return otherVector
  1780. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1781. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1782. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1783. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1784. };
  1785. /**
  1786. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1787. */
  1788. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1789. return this.x === x && this.y === y && this.z === z && this.w === w;
  1790. };
  1791. /**
  1792. * Multiplies in place the current Vector4 by the passed one.
  1793. * Returns the updated Vector4.
  1794. */
  1795. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1796. this.x *= otherVector.x;
  1797. this.y *= otherVector.y;
  1798. this.z *= otherVector.z;
  1799. this.w *= otherVector.w;
  1800. return this;
  1801. };
  1802. /**
  1803. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1804. */
  1805. Vector4.prototype.multiply = function (otherVector) {
  1806. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1807. };
  1808. /**
  1809. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1810. * Returns the current Vector4.
  1811. */
  1812. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1813. result.x = this.x * otherVector.x;
  1814. result.y = this.y * otherVector.y;
  1815. result.z = this.z * otherVector.z;
  1816. result.w = this.w * otherVector.w;
  1817. return this;
  1818. };
  1819. /**
  1820. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1821. */
  1822. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1823. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1824. };
  1825. /**
  1826. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1827. */
  1828. Vector4.prototype.divide = function (otherVector) {
  1829. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1830. };
  1831. /**
  1832. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1833. * Returns the current Vector4.
  1834. */
  1835. Vector4.prototype.divideToRef = function (otherVector, result) {
  1836. result.x = this.x / otherVector.x;
  1837. result.y = this.y / otherVector.y;
  1838. result.z = this.z / otherVector.z;
  1839. result.w = this.w / otherVector.w;
  1840. return this;
  1841. };
  1842. /**
  1843. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1844. */
  1845. Vector4.prototype.MinimizeInPlace = function (other) {
  1846. if (other.x < this.x)
  1847. this.x = other.x;
  1848. if (other.y < this.y)
  1849. this.y = other.y;
  1850. if (other.z < this.z)
  1851. this.z = other.z;
  1852. if (other.w < this.w)
  1853. this.w = other.w;
  1854. return this;
  1855. };
  1856. /**
  1857. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1858. */
  1859. Vector4.prototype.MaximizeInPlace = function (other) {
  1860. if (other.x > this.x)
  1861. this.x = other.x;
  1862. if (other.y > this.y)
  1863. this.y = other.y;
  1864. if (other.z > this.z)
  1865. this.z = other.z;
  1866. if (other.w > this.w)
  1867. this.w = other.w;
  1868. return this;
  1869. };
  1870. // Properties
  1871. /**
  1872. * Returns the Vector4 length (float).
  1873. */
  1874. Vector4.prototype.length = function () {
  1875. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1876. };
  1877. /**
  1878. * Returns the Vector4 squared length (float).
  1879. */
  1880. Vector4.prototype.lengthSquared = function () {
  1881. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1882. };
  1883. // Methods
  1884. /**
  1885. * Normalizes in place the Vector4.
  1886. * Returns the updated Vector4.
  1887. */
  1888. Vector4.prototype.normalize = function () {
  1889. var len = this.length();
  1890. if (len === 0)
  1891. return this;
  1892. var num = 1.0 / len;
  1893. this.x *= num;
  1894. this.y *= num;
  1895. this.z *= num;
  1896. this.w *= num;
  1897. return this;
  1898. };
  1899. /**
  1900. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1901. */
  1902. Vector4.prototype.toVector3 = function () {
  1903. return new Vector3(this.x, this.y, this.z);
  1904. };
  1905. /**
  1906. * Returns a new Vector4 copied from the current one.
  1907. */
  1908. Vector4.prototype.clone = function () {
  1909. return new Vector4(this.x, this.y, this.z, this.w);
  1910. };
  1911. /**
  1912. * Updates the current Vector4 with the passed one coordinates.
  1913. * Returns the updated Vector4.
  1914. */
  1915. Vector4.prototype.copyFrom = function (source) {
  1916. this.x = source.x;
  1917. this.y = source.y;
  1918. this.z = source.z;
  1919. this.w = source.w;
  1920. return this;
  1921. };
  1922. /**
  1923. * Updates the current Vector4 coordinates with the passed floats.
  1924. * Returns the updated Vector4.
  1925. */
  1926. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1927. this.x = x;
  1928. this.y = y;
  1929. this.z = z;
  1930. this.w = w;
  1931. return this;
  1932. };
  1933. // Statics
  1934. /**
  1935. * Returns a new Vector4 set from the starting index of the passed array.
  1936. */
  1937. Vector4.FromArray = function (array, offset) {
  1938. if (!offset) {
  1939. offset = 0;
  1940. }
  1941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1942. };
  1943. /**
  1944. * Updates the passed vector "result" from the starting index of the passed array.
  1945. */
  1946. Vector4.FromArrayToRef = function (array, offset, result) {
  1947. result.x = array[offset];
  1948. result.y = array[offset + 1];
  1949. result.z = array[offset + 2];
  1950. result.w = array[offset + 3];
  1951. };
  1952. /**
  1953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  1954. */
  1955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1956. result.x = array[offset];
  1957. result.y = array[offset + 1];
  1958. result.z = array[offset + 2];
  1959. result.w = array[offset + 3];
  1960. };
  1961. /**
  1962. * Updates the passed vector "result" coordinates from the passed floats.
  1963. */
  1964. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1965. result.x = x;
  1966. result.y = y;
  1967. result.z = z;
  1968. result.w = w;
  1969. };
  1970. /**
  1971. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  1972. */
  1973. Vector4.Zero = function () {
  1974. return new Vector4(0.0, 0.0, 0.0, 0.0);
  1975. };
  1976. /**
  1977. * Returns a new normalized Vector4 from the passed one.
  1978. */
  1979. Vector4.Normalize = function (vector) {
  1980. var result = Vector4.Zero();
  1981. Vector4.NormalizeToRef(vector, result);
  1982. return result;
  1983. };
  1984. /**
  1985. * Updates the passed vector "result" from the normalization of the passed one.
  1986. */
  1987. Vector4.NormalizeToRef = function (vector, result) {
  1988. result.copyFrom(vector);
  1989. result.normalize();
  1990. };
  1991. Vector4.Minimize = function (left, right) {
  1992. var min = left.clone();
  1993. min.MinimizeInPlace(right);
  1994. return min;
  1995. };
  1996. Vector4.Maximize = function (left, right) {
  1997. var max = left.clone();
  1998. max.MaximizeInPlace(right);
  1999. return max;
  2000. };
  2001. /**
  2002. * Returns the distance (float) between the vectors "value1" and "value2".
  2003. */
  2004. Vector4.Distance = function (value1, value2) {
  2005. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2006. };
  2007. Vector4.DistanceSquared = function (value1, value2) {
  2008. var x = value1.x - value2.x;
  2009. var y = value1.y - value2.y;
  2010. var z = value1.z - value2.z;
  2011. var w = value1.w - value2.w;
  2012. return (x * x) + (y * y) + (z * z) + (w * w);
  2013. };
  2014. /**
  2015. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2016. */
  2017. Vector4.Center = function (value1, value2) {
  2018. var center = value1.add(value2);
  2019. center.scaleInPlace(0.5);
  2020. return center;
  2021. };
  2022. return Vector4;
  2023. }());
  2024. BABYLON.Vector4 = Vector4;
  2025. var Size = (function () {
  2026. /**
  2027. * Creates a Size object from the passed width and height (floats).
  2028. */
  2029. function Size(width, height) {
  2030. this.width = width;
  2031. this.height = height;
  2032. }
  2033. // Returns a string with the Size width and height.
  2034. Size.prototype.toString = function () {
  2035. return "{W: " + this.width + ", H: " + this.height + "}";
  2036. };
  2037. /**
  2038. * Returns the string "Size"
  2039. */
  2040. Size.prototype.getClassName = function () {
  2041. return "Size";
  2042. };
  2043. /**
  2044. * Returns the Size hash code.
  2045. */
  2046. Size.prototype.getHashCode = function () {
  2047. var hash = this.width || 0;
  2048. hash = (hash * 397) ^ (this.height || 0);
  2049. return hash;
  2050. };
  2051. /**
  2052. * Updates the current size from the passed one.
  2053. * Returns the updated Size.
  2054. */
  2055. Size.prototype.copyFrom = function (src) {
  2056. this.width = src.width;
  2057. this.height = src.height;
  2058. };
  2059. /**
  2060. * Updates in place the current Size from the passed floats.
  2061. * Returns the updated Size.
  2062. */
  2063. Size.prototype.copyFromFloats = function (width, height) {
  2064. this.width = width;
  2065. this.height = height;
  2066. return this;
  2067. };
  2068. /**
  2069. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2070. */
  2071. Size.prototype.multiplyByFloats = function (w, h) {
  2072. return new Size(this.width * w, this.height * h);
  2073. };
  2074. /**
  2075. * Returns a new Size copied from the passed one.
  2076. */
  2077. Size.prototype.clone = function () {
  2078. return new Size(this.width, this.height);
  2079. };
  2080. /**
  2081. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2082. */
  2083. Size.prototype.equals = function (other) {
  2084. if (!other) {
  2085. return false;
  2086. }
  2087. return (this.width === other.width) && (this.height === other.height);
  2088. };
  2089. Object.defineProperty(Size.prototype, "surface", {
  2090. /**
  2091. * Returns the surface of the Size : width * height (float).
  2092. */
  2093. get: function () {
  2094. return this.width * this.height;
  2095. },
  2096. enumerable: true,
  2097. configurable: true
  2098. });
  2099. /**
  2100. * Returns a new Size set to (0.0, 0.0)
  2101. */
  2102. Size.Zero = function () {
  2103. return new Size(0.0, 0.0);
  2104. };
  2105. /**
  2106. * Returns a new Size set as the addition result of the current Size and the passed one.
  2107. */
  2108. Size.prototype.add = function (otherSize) {
  2109. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2110. return r;
  2111. };
  2112. /**
  2113. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2114. */
  2115. Size.prototype.subtract = function (otherSize) {
  2116. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2117. return r;
  2118. };
  2119. /**
  2120. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2121. */
  2122. Size.Lerp = function (start, end, amount) {
  2123. var w = start.width + ((end.width - start.width) * amount);
  2124. var h = start.height + ((end.height - start.height) * amount);
  2125. return new Size(w, h);
  2126. };
  2127. return Size;
  2128. }());
  2129. BABYLON.Size = Size;
  2130. var Quaternion = (function () {
  2131. /**
  2132. * Creates a new Quaternion from the passed floats.
  2133. */
  2134. function Quaternion(x, y, z, w) {
  2135. if (x === void 0) { x = 0.0; }
  2136. if (y === void 0) { y = 0.0; }
  2137. if (z === void 0) { z = 0.0; }
  2138. if (w === void 0) { w = 1.0; }
  2139. this.x = x;
  2140. this.y = y;
  2141. this.z = z;
  2142. this.w = w;
  2143. }
  2144. /**
  2145. * Returns a string with the Quaternion coordinates.
  2146. */
  2147. Quaternion.prototype.toString = function () {
  2148. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2149. };
  2150. /**
  2151. * Returns the string "Quaternion".
  2152. */
  2153. Quaternion.prototype.getClassName = function () {
  2154. return "Quaternion";
  2155. };
  2156. /**
  2157. * Returns the Quaternion hash code.
  2158. */
  2159. Quaternion.prototype.getHashCode = function () {
  2160. var hash = this.x || 0;
  2161. hash = (hash * 397) ^ (this.y || 0);
  2162. hash = (hash * 397) ^ (this.z || 0);
  2163. hash = (hash * 397) ^ (this.w || 0);
  2164. return hash;
  2165. };
  2166. /**
  2167. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2168. */
  2169. Quaternion.prototype.asArray = function () {
  2170. return [this.x, this.y, this.z, this.w];
  2171. };
  2172. /**
  2173. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2174. */
  2175. Quaternion.prototype.equals = function (otherQuaternion) {
  2176. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2177. };
  2178. /**
  2179. * Returns a new Quaternion copied from the current one.
  2180. */
  2181. Quaternion.prototype.clone = function () {
  2182. return new Quaternion(this.x, this.y, this.z, this.w);
  2183. };
  2184. /**
  2185. * Updates the current Quaternion from the passed one coordinates.
  2186. * Returns the updated Quaterion.
  2187. */
  2188. Quaternion.prototype.copyFrom = function (other) {
  2189. this.x = other.x;
  2190. this.y = other.y;
  2191. this.z = other.z;
  2192. this.w = other.w;
  2193. return this;
  2194. };
  2195. /**
  2196. * Updates the current Quaternion from the passed float coordinates.
  2197. * Returns the updated Quaterion.
  2198. */
  2199. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2200. this.x = x;
  2201. this.y = y;
  2202. this.z = z;
  2203. this.w = w;
  2204. return this;
  2205. };
  2206. /**
  2207. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2208. */
  2209. Quaternion.prototype.add = function (other) {
  2210. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2211. };
  2212. /**
  2213. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2214. */
  2215. Quaternion.prototype.subtract = function (other) {
  2216. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2217. };
  2218. /**
  2219. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2220. */
  2221. Quaternion.prototype.scale = function (value) {
  2222. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2223. };
  2224. /**
  2225. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2226. */
  2227. Quaternion.prototype.multiply = function (q1) {
  2228. var result = new Quaternion(0, 0, 0, 1.0);
  2229. this.multiplyToRef(q1, result);
  2230. return result;
  2231. };
  2232. /**
  2233. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2234. * Returns the current Quaternion.
  2235. */
  2236. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2237. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2238. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2239. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2240. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2241. result.copyFromFloats(x, y, z, w);
  2242. return this;
  2243. };
  2244. /**
  2245. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2246. * Returns the updated Quaternion.
  2247. */
  2248. Quaternion.prototype.multiplyInPlace = function (q1) {
  2249. this.multiplyToRef(q1, this);
  2250. return this;
  2251. };
  2252. /**
  2253. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2254. * Returns the current Quaternion.
  2255. */
  2256. Quaternion.prototype.conjugateToRef = function (ref) {
  2257. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2258. return this;
  2259. };
  2260. /**
  2261. * Conjugates in place the current Quaternion.
  2262. * Returns the updated Quaternion.
  2263. */
  2264. Quaternion.prototype.conjugateInPlace = function () {
  2265. this.x *= -1;
  2266. this.y *= -1;
  2267. this.z *= -1;
  2268. return this;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2272. */
  2273. Quaternion.prototype.conjugate = function () {
  2274. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2275. return result;
  2276. };
  2277. /**
  2278. * Returns the Quaternion length (float).
  2279. */
  2280. Quaternion.prototype.length = function () {
  2281. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2282. };
  2283. /**
  2284. * Normalize in place the current Quaternion.
  2285. * Returns the updated Quaternion.
  2286. */
  2287. Quaternion.prototype.normalize = function () {
  2288. var length = 1.0 / this.length();
  2289. this.x *= length;
  2290. this.y *= length;
  2291. this.z *= length;
  2292. this.w *= length;
  2293. return this;
  2294. };
  2295. /**
  2296. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2297. */
  2298. Quaternion.prototype.toEulerAngles = function (order) {
  2299. if (order === void 0) { order = "YZX"; }
  2300. var result = Vector3.Zero();
  2301. this.toEulerAnglesToRef(result, order);
  2302. return result;
  2303. };
  2304. /**
  2305. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2306. * Returns the current Quaternion.
  2307. */
  2308. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2309. if (order === void 0) { order = "YZX"; }
  2310. var qz = this.z;
  2311. var qx = this.x;
  2312. var qy = this.y;
  2313. var qw = this.w;
  2314. var sqw = qw * qw;
  2315. var sqz = qz * qz;
  2316. var sqx = qx * qx;
  2317. var sqy = qy * qy;
  2318. var zAxisY = qy * qz - qx * qw;
  2319. var limit = .4999999;
  2320. if (zAxisY < -limit) {
  2321. result.y = 2 * Math.atan2(qy, qw);
  2322. result.x = Math.PI / 2;
  2323. result.z = 0;
  2324. }
  2325. else if (zAxisY > limit) {
  2326. result.y = 2 * Math.atan2(qy, qw);
  2327. result.x = -Math.PI / 2;
  2328. result.z = 0;
  2329. }
  2330. else {
  2331. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2332. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2333. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2334. }
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates the passed rotation matrix with the current Quaternion values.
  2339. * Returns the current Quaternion.
  2340. */
  2341. Quaternion.prototype.toRotationMatrix = function (result) {
  2342. var xx = this.x * this.x;
  2343. var yy = this.y * this.y;
  2344. var zz = this.z * this.z;
  2345. var xy = this.x * this.y;
  2346. var zw = this.z * this.w;
  2347. var zx = this.z * this.x;
  2348. var yw = this.y * this.w;
  2349. var yz = this.y * this.z;
  2350. var xw = this.x * this.w;
  2351. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2352. result.m[1] = 2.0 * (xy + zw);
  2353. result.m[2] = 2.0 * (zx - yw);
  2354. result.m[3] = 0;
  2355. result.m[4] = 2.0 * (xy - zw);
  2356. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2357. result.m[6] = 2.0 * (yz + xw);
  2358. result.m[7] = 0;
  2359. result.m[8] = 2.0 * (zx + yw);
  2360. result.m[9] = 2.0 * (yz - xw);
  2361. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2362. result.m[11] = 0;
  2363. result.m[12] = 0;
  2364. result.m[13] = 0;
  2365. result.m[14] = 0;
  2366. result.m[15] = 1.0;
  2367. return this;
  2368. };
  2369. /**
  2370. * Updates the current Quaternion from the passed rotation matrix values.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2374. Quaternion.FromRotationMatrixToRef(matrix, this);
  2375. return this;
  2376. };
  2377. // Statics
  2378. /**
  2379. * Returns a new Quaternion set from the passed rotation matrix values.
  2380. */
  2381. Quaternion.FromRotationMatrix = function (matrix) {
  2382. var result = new Quaternion();
  2383. Quaternion.FromRotationMatrixToRef(matrix, result);
  2384. return result;
  2385. };
  2386. /**
  2387. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2388. */
  2389. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2390. var data = matrix.m;
  2391. var m11 = data[0], m12 = data[4], m13 = data[8];
  2392. var m21 = data[1], m22 = data[5], m23 = data[9];
  2393. var m31 = data[2], m32 = data[6], m33 = data[10];
  2394. var trace = m11 + m22 + m33;
  2395. var s;
  2396. if (trace > 0) {
  2397. s = 0.5 / Math.sqrt(trace + 1.0);
  2398. result.w = 0.25 / s;
  2399. result.x = (m32 - m23) * s;
  2400. result.y = (m13 - m31) * s;
  2401. result.z = (m21 - m12) * s;
  2402. }
  2403. else if (m11 > m22 && m11 > m33) {
  2404. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2405. result.w = (m32 - m23) / s;
  2406. result.x = 0.25 * s;
  2407. result.y = (m12 + m21) / s;
  2408. result.z = (m13 + m31) / s;
  2409. }
  2410. else if (m22 > m33) {
  2411. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2412. result.w = (m13 - m31) / s;
  2413. result.x = (m12 + m21) / s;
  2414. result.y = 0.25 * s;
  2415. result.z = (m23 + m32) / s;
  2416. }
  2417. else {
  2418. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2419. result.w = (m21 - m12) / s;
  2420. result.x = (m13 + m31) / s;
  2421. result.y = (m23 + m32) / s;
  2422. result.z = 0.25 * s;
  2423. }
  2424. };
  2425. /**
  2426. * Returns a new Quaternion as the inverted current Quaternion.
  2427. */
  2428. Quaternion.Inverse = function (q) {
  2429. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2430. };
  2431. /**
  2432. * Returns the identity Quaternion.
  2433. */
  2434. Quaternion.Identity = function () {
  2435. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2436. };
  2437. /**
  2438. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2439. */
  2440. Quaternion.RotationAxis = function (axis, angle) {
  2441. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2442. };
  2443. /**
  2444. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2445. */
  2446. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2447. var sin = Math.sin(angle / 2);
  2448. axis.normalize();
  2449. result.w = Math.cos(angle / 2);
  2450. result.x = axis.x * sin;
  2451. result.y = axis.y * sin;
  2452. result.z = axis.z * sin;
  2453. return result;
  2454. };
  2455. /**
  2456. * Retuns a new Quaternion set from the starting index of the passed array.
  2457. */
  2458. Quaternion.FromArray = function (array, offset) {
  2459. if (!offset) {
  2460. offset = 0;
  2461. }
  2462. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2463. };
  2464. /**
  2465. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2466. */
  2467. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2468. var q = new Quaternion();
  2469. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2470. return q;
  2471. };
  2472. /**
  2473. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2474. */
  2475. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2476. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2477. var halfRoll = roll * 0.5;
  2478. var halfPitch = pitch * 0.5;
  2479. var halfYaw = yaw * 0.5;
  2480. var sinRoll = Math.sin(halfRoll);
  2481. var cosRoll = Math.cos(halfRoll);
  2482. var sinPitch = Math.sin(halfPitch);
  2483. var cosPitch = Math.cos(halfPitch);
  2484. var sinYaw = Math.sin(halfYaw);
  2485. var cosYaw = Math.cos(halfYaw);
  2486. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2487. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2488. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2489. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2490. };
  2491. /**
  2492. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2493. */
  2494. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2495. var result = new Quaternion();
  2496. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2497. return result;
  2498. };
  2499. /**
  2500. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2501. */
  2502. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2503. // Produces a quaternion from Euler angles in the z-x-z orientation
  2504. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2505. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2506. var halfBeta = beta * 0.5;
  2507. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2508. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2509. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2510. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2511. };
  2512. /**
  2513. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2514. * cf to Vector3.RotationFromAxis() documentation.
  2515. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2516. */
  2517. Quaternion.QuaternionRotationFromAxis = function (axis1, axis2, axis3, ref) {
  2518. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2519. Quaternion.QuaternionRotationFromAxisToRef(axis1, axis2, axis3, quat);
  2520. return quat;
  2521. };
  2522. /**
  2523. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2524. * cf to Vector3.RotationFromAxis() documentation.
  2525. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2526. */
  2527. Quaternion.QuaternionRotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2528. var rotMat = Tmp.Matrix[0];
  2529. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2530. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2531. };
  2532. Quaternion.Slerp = function (left, right, amount) {
  2533. var result = Quaternion.Identity();
  2534. Quaternion.SlerpToRef(left, right, amount, result);
  2535. return result;
  2536. };
  2537. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2538. var num2;
  2539. var num3;
  2540. var num = amount;
  2541. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2542. var flag = false;
  2543. if (num4 < 0) {
  2544. flag = true;
  2545. num4 = -num4;
  2546. }
  2547. if (num4 > 0.999999) {
  2548. num3 = 1 - num;
  2549. num2 = flag ? -num : num;
  2550. }
  2551. else {
  2552. var num5 = Math.acos(num4);
  2553. var num6 = (1.0 / Math.sin(num5));
  2554. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2555. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2556. }
  2557. result.x = (num3 * left.x) + (num2 * right.x);
  2558. result.y = (num3 * left.y) + (num2 * right.y);
  2559. result.z = (num3 * left.z) + (num2 * right.z);
  2560. result.w = (num3 * left.w) + (num2 * right.w);
  2561. };
  2562. return Quaternion;
  2563. }());
  2564. BABYLON.Quaternion = Quaternion;
  2565. var Matrix = (function () {
  2566. function Matrix() {
  2567. this.m = new Float32Array(16);
  2568. }
  2569. // Properties
  2570. /**
  2571. * Boolean : True is the matrix is the identity matrix
  2572. */
  2573. Matrix.prototype.isIdentity = function () {
  2574. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2575. return false;
  2576. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2577. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2578. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2579. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2580. return false;
  2581. return true;
  2582. };
  2583. /**
  2584. * Returns the matrix determinant (float).
  2585. */
  2586. Matrix.prototype.determinant = function () {
  2587. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2588. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2589. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2590. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2591. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2592. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2593. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2594. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2595. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2596. };
  2597. // Methods
  2598. /**
  2599. * Returns the matrix underlying array.
  2600. */
  2601. Matrix.prototype.toArray = function () {
  2602. return this.m;
  2603. };
  2604. /**
  2605. * Returns the matrix underlying array.
  2606. */
  2607. Matrix.prototype.asArray = function () {
  2608. return this.toArray();
  2609. };
  2610. /**
  2611. * Inverts in place the Matrix.
  2612. * Returns the Matrix inverted.
  2613. */
  2614. Matrix.prototype.invert = function () {
  2615. this.invertToRef(this);
  2616. return this;
  2617. };
  2618. /**
  2619. * Sets all the matrix elements to zero.
  2620. * Returns the Matrix.
  2621. */
  2622. Matrix.prototype.reset = function () {
  2623. for (var index = 0; index < 16; index++) {
  2624. this.m[index] = 0.0;
  2625. }
  2626. return this;
  2627. };
  2628. /**
  2629. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2630. */
  2631. Matrix.prototype.add = function (other) {
  2632. var result = new Matrix();
  2633. this.addToRef(other, result);
  2634. return result;
  2635. };
  2636. /**
  2637. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2638. * Returns the Matrix.
  2639. */
  2640. Matrix.prototype.addToRef = function (other, result) {
  2641. for (var index = 0; index < 16; index++) {
  2642. result.m[index] = this.m[index] + other.m[index];
  2643. }
  2644. return this;
  2645. };
  2646. /**
  2647. * Adds in place the passed matrix to the current Matrix.
  2648. * Returns the updated Matrix.
  2649. */
  2650. Matrix.prototype.addToSelf = function (other) {
  2651. for (var index = 0; index < 16; index++) {
  2652. this.m[index] += other.m[index];
  2653. }
  2654. return this;
  2655. };
  2656. /**
  2657. * Sets the passed matrix with the current inverted Matrix.
  2658. * Returns the unmodified current Matrix.
  2659. */
  2660. Matrix.prototype.invertToRef = function (other) {
  2661. var l1 = this.m[0];
  2662. var l2 = this.m[1];
  2663. var l3 = this.m[2];
  2664. var l4 = this.m[3];
  2665. var l5 = this.m[4];
  2666. var l6 = this.m[5];
  2667. var l7 = this.m[6];
  2668. var l8 = this.m[7];
  2669. var l9 = this.m[8];
  2670. var l10 = this.m[9];
  2671. var l11 = this.m[10];
  2672. var l12 = this.m[11];
  2673. var l13 = this.m[12];
  2674. var l14 = this.m[13];
  2675. var l15 = this.m[14];
  2676. var l16 = this.m[15];
  2677. var l17 = (l11 * l16) - (l12 * l15);
  2678. var l18 = (l10 * l16) - (l12 * l14);
  2679. var l19 = (l10 * l15) - (l11 * l14);
  2680. var l20 = (l9 * l16) - (l12 * l13);
  2681. var l21 = (l9 * l15) - (l11 * l13);
  2682. var l22 = (l9 * l14) - (l10 * l13);
  2683. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2684. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2685. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2686. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2687. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2688. var l28 = (l7 * l16) - (l8 * l15);
  2689. var l29 = (l6 * l16) - (l8 * l14);
  2690. var l30 = (l6 * l15) - (l7 * l14);
  2691. var l31 = (l5 * l16) - (l8 * l13);
  2692. var l32 = (l5 * l15) - (l7 * l13);
  2693. var l33 = (l5 * l14) - (l6 * l13);
  2694. var l34 = (l7 * l12) - (l8 * l11);
  2695. var l35 = (l6 * l12) - (l8 * l10);
  2696. var l36 = (l6 * l11) - (l7 * l10);
  2697. var l37 = (l5 * l12) - (l8 * l9);
  2698. var l38 = (l5 * l11) - (l7 * l9);
  2699. var l39 = (l5 * l10) - (l6 * l9);
  2700. other.m[0] = l23 * l27;
  2701. other.m[4] = l24 * l27;
  2702. other.m[8] = l25 * l27;
  2703. other.m[12] = l26 * l27;
  2704. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2705. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2706. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2707. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2708. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2709. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2710. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2711. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2712. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2713. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2714. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2715. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2716. return this;
  2717. };
  2718. /**
  2719. * Inserts the translation vector in the current Matrix.
  2720. * Returns the updated Matrix.
  2721. */
  2722. Matrix.prototype.setTranslation = function (vector3) {
  2723. this.m[12] = vector3.x;
  2724. this.m[13] = vector3.y;
  2725. this.m[14] = vector3.z;
  2726. return this;
  2727. };
  2728. /**
  2729. * Returns a new Vector3 as the extracted translation from the Matrix.
  2730. */
  2731. Matrix.prototype.getTranslation = function () {
  2732. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2733. };
  2734. /**
  2735. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2736. */
  2737. Matrix.prototype.multiply = function (other) {
  2738. var result = new Matrix();
  2739. this.multiplyToRef(other, result);
  2740. return result;
  2741. };
  2742. /**
  2743. * Updates the current Matrix from the passed one values.
  2744. * Returns the updated Matrix.
  2745. */
  2746. Matrix.prototype.copyFrom = function (other) {
  2747. for (var index = 0; index < 16; index++) {
  2748. this.m[index] = other.m[index];
  2749. }
  2750. return this;
  2751. };
  2752. /**
  2753. * Populates the passed array from the starting index with the Matrix values.
  2754. * Returns the Matrix.
  2755. */
  2756. Matrix.prototype.copyToArray = function (array, offset) {
  2757. if (offset === void 0) { offset = 0; }
  2758. for (var index = 0; index < 16; index++) {
  2759. array[offset + index] = this.m[index];
  2760. }
  2761. return this;
  2762. };
  2763. /**
  2764. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2765. */
  2766. Matrix.prototype.multiplyToRef = function (other, result) {
  2767. this.multiplyToArray(other, result.m, 0);
  2768. return this;
  2769. };
  2770. /**
  2771. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2772. */
  2773. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2774. var tm0 = this.m[0];
  2775. var tm1 = this.m[1];
  2776. var tm2 = this.m[2];
  2777. var tm3 = this.m[3];
  2778. var tm4 = this.m[4];
  2779. var tm5 = this.m[5];
  2780. var tm6 = this.m[6];
  2781. var tm7 = this.m[7];
  2782. var tm8 = this.m[8];
  2783. var tm9 = this.m[9];
  2784. var tm10 = this.m[10];
  2785. var tm11 = this.m[11];
  2786. var tm12 = this.m[12];
  2787. var tm13 = this.m[13];
  2788. var tm14 = this.m[14];
  2789. var tm15 = this.m[15];
  2790. var om0 = other.m[0];
  2791. var om1 = other.m[1];
  2792. var om2 = other.m[2];
  2793. var om3 = other.m[3];
  2794. var om4 = other.m[4];
  2795. var om5 = other.m[5];
  2796. var om6 = other.m[6];
  2797. var om7 = other.m[7];
  2798. var om8 = other.m[8];
  2799. var om9 = other.m[9];
  2800. var om10 = other.m[10];
  2801. var om11 = other.m[11];
  2802. var om12 = other.m[12];
  2803. var om13 = other.m[13];
  2804. var om14 = other.m[14];
  2805. var om15 = other.m[15];
  2806. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2807. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2808. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2809. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2810. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2811. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2812. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2813. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2814. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2815. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2816. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2817. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2818. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2819. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2820. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2821. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2822. return this;
  2823. };
  2824. /**
  2825. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2826. */
  2827. Matrix.prototype.equals = function (value) {
  2828. return value &&
  2829. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2830. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2831. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2832. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2833. };
  2834. /**
  2835. * Returns a new Matrix from the current Matrix.
  2836. */
  2837. Matrix.prototype.clone = function () {
  2838. 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]);
  2839. };
  2840. /**
  2841. * Returns the string "Matrix"
  2842. */
  2843. Matrix.prototype.getClassName = function () {
  2844. return "Matrix";
  2845. };
  2846. /**
  2847. * Returns the Matrix hash code.
  2848. */
  2849. Matrix.prototype.getHashCode = function () {
  2850. var hash = this.m[0] || 0;
  2851. for (var i = 1; i < 16; i++) {
  2852. hash = (hash * 397) ^ (this.m[i] || 0);
  2853. }
  2854. return hash;
  2855. };
  2856. /**
  2857. * Decomposes the current Matrix into :
  2858. * - a scale vector3 passed as a reference to update,
  2859. * - a rotation quaternion passed as a reference to update,
  2860. * - a translation vector3 passed as a reference to update.
  2861. * Returns the boolean `true`.
  2862. */
  2863. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2864. translation.x = this.m[12];
  2865. translation.y = this.m[13];
  2866. translation.z = this.m[14];
  2867. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  2868. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  2869. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  2870. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  2871. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  2872. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  2873. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  2874. rotation.x = 0;
  2875. rotation.y = 0;
  2876. rotation.z = 0;
  2877. rotation.w = 1;
  2878. return false;
  2879. }
  2880. 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, Tmp.Matrix[0]);
  2881. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2882. return true;
  2883. };
  2884. /**
  2885. * Returns a new Matrix as the extracted rotation matrix from the current one.
  2886. */
  2887. Matrix.prototype.getRotationMatrix = function () {
  2888. var result = Matrix.Identity();
  2889. this.getRotationMatrixToRef(result);
  2890. return result;
  2891. };
  2892. /**
  2893. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  2894. * Returns the current Matrix.
  2895. */
  2896. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2897. var m = this.m;
  2898. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2899. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2900. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2901. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2902. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2903. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2904. 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);
  2905. return this;
  2906. };
  2907. // Statics
  2908. /**
  2909. * Returns a new Matrix set from the starting index of the passed array.
  2910. */
  2911. Matrix.FromArray = function (array, offset) {
  2912. var result = new Matrix();
  2913. if (!offset) {
  2914. offset = 0;
  2915. }
  2916. Matrix.FromArrayToRef(array, offset, result);
  2917. return result;
  2918. };
  2919. /**
  2920. * Sets the passed "result" matrix from the starting index of the passed array.
  2921. */
  2922. Matrix.FromArrayToRef = function (array, offset, result) {
  2923. for (var index = 0; index < 16; index++) {
  2924. result.m[index] = array[index + offset];
  2925. }
  2926. };
  2927. /**
  2928. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  2929. */
  2930. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2931. for (var index = 0; index < 16; index++) {
  2932. result.m[index] = array[index + offset] * scale;
  2933. }
  2934. };
  2935. /**
  2936. * Sets the passed matrix "result" with the 16 passed floats.
  2937. */
  2938. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2939. result.m[0] = initialM11;
  2940. result.m[1] = initialM12;
  2941. result.m[2] = initialM13;
  2942. result.m[3] = initialM14;
  2943. result.m[4] = initialM21;
  2944. result.m[5] = initialM22;
  2945. result.m[6] = initialM23;
  2946. result.m[7] = initialM24;
  2947. result.m[8] = initialM31;
  2948. result.m[9] = initialM32;
  2949. result.m[10] = initialM33;
  2950. result.m[11] = initialM34;
  2951. result.m[12] = initialM41;
  2952. result.m[13] = initialM42;
  2953. result.m[14] = initialM43;
  2954. result.m[15] = initialM44;
  2955. };
  2956. /**
  2957. * Returns the index-th row of the current matrix as a new Vector4.
  2958. */
  2959. Matrix.prototype.getRow = function (index) {
  2960. if (index < 0 || index > 3) {
  2961. return null;
  2962. }
  2963. var i = index * 4;
  2964. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2965. };
  2966. /**
  2967. * Sets the index-th row of the current matrix with the passed Vector4 values.
  2968. * Returns the updated Matrix.
  2969. */
  2970. Matrix.prototype.setRow = function (index, row) {
  2971. if (index < 0 || index > 3) {
  2972. return this;
  2973. }
  2974. var i = index * 4;
  2975. this.m[i + 0] = row.x;
  2976. this.m[i + 1] = row.y;
  2977. this.m[i + 2] = row.z;
  2978. this.m[i + 3] = row.w;
  2979. return this;
  2980. };
  2981. /**
  2982. * Returns a new Matrix set from the 16 passed floats.
  2983. */
  2984. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2985. var result = new Matrix();
  2986. result.m[0] = initialM11;
  2987. result.m[1] = initialM12;
  2988. result.m[2] = initialM13;
  2989. result.m[3] = initialM14;
  2990. result.m[4] = initialM21;
  2991. result.m[5] = initialM22;
  2992. result.m[6] = initialM23;
  2993. result.m[7] = initialM24;
  2994. result.m[8] = initialM31;
  2995. result.m[9] = initialM32;
  2996. result.m[10] = initialM33;
  2997. result.m[11] = initialM34;
  2998. result.m[12] = initialM41;
  2999. result.m[13] = initialM42;
  3000. result.m[14] = initialM43;
  3001. result.m[15] = initialM44;
  3002. return result;
  3003. };
  3004. /**
  3005. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3006. */
  3007. Matrix.Compose = function (scale, rotation, translation) {
  3008. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  3009. var rotationMatrix = Matrix.Identity();
  3010. rotation.toRotationMatrix(rotationMatrix);
  3011. result = result.multiply(rotationMatrix);
  3012. result.setTranslation(translation);
  3013. return result;
  3014. };
  3015. /**
  3016. * Returns a new indentity Matrix.
  3017. */
  3018. Matrix.Identity = function () {
  3019. 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);
  3020. };
  3021. /**
  3022. * Sets the passed "result" as an identity matrix.
  3023. */
  3024. Matrix.IdentityToRef = function (result) {
  3025. 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);
  3026. };
  3027. /**
  3028. * Returns a new zero Matrix.
  3029. */
  3030. Matrix.Zero = function () {
  3031. 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);
  3032. };
  3033. /**
  3034. * Returns a new rotation matrix for "angle" radians around the X axis.
  3035. */
  3036. Matrix.RotationX = function (angle) {
  3037. var result = new Matrix();
  3038. Matrix.RotationXToRef(angle, result);
  3039. return result;
  3040. };
  3041. /**
  3042. * Returns a new Matrix as the passed inverted one.
  3043. */
  3044. Matrix.Invert = function (source) {
  3045. var result = new Matrix();
  3046. source.invertToRef(result);
  3047. return result;
  3048. };
  3049. /**
  3050. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3051. */
  3052. Matrix.RotationXToRef = function (angle, result) {
  3053. var s = Math.sin(angle);
  3054. var c = Math.cos(angle);
  3055. result.m[0] = 1.0;
  3056. result.m[15] = 1.0;
  3057. result.m[5] = c;
  3058. result.m[10] = c;
  3059. result.m[9] = -s;
  3060. result.m[6] = s;
  3061. result.m[1] = 0.0;
  3062. result.m[2] = 0.0;
  3063. result.m[3] = 0.0;
  3064. result.m[4] = 0.0;
  3065. result.m[7] = 0.0;
  3066. result.m[8] = 0.0;
  3067. result.m[11] = 0.0;
  3068. result.m[12] = 0.0;
  3069. result.m[13] = 0.0;
  3070. result.m[14] = 0.0;
  3071. };
  3072. /**
  3073. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3074. */
  3075. Matrix.RotationY = function (angle) {
  3076. var result = new Matrix();
  3077. Matrix.RotationYToRef(angle, result);
  3078. return result;
  3079. };
  3080. /**
  3081. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3082. */
  3083. Matrix.RotationYToRef = function (angle, result) {
  3084. var s = Math.sin(angle);
  3085. var c = Math.cos(angle);
  3086. result.m[5] = 1.0;
  3087. result.m[15] = 1.0;
  3088. result.m[0] = c;
  3089. result.m[2] = -s;
  3090. result.m[8] = s;
  3091. result.m[10] = c;
  3092. result.m[1] = 0.0;
  3093. result.m[3] = 0.0;
  3094. result.m[4] = 0.0;
  3095. result.m[6] = 0.0;
  3096. result.m[7] = 0.0;
  3097. result.m[9] = 0.0;
  3098. result.m[11] = 0.0;
  3099. result.m[12] = 0.0;
  3100. result.m[13] = 0.0;
  3101. result.m[14] = 0.0;
  3102. };
  3103. /**
  3104. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3105. */
  3106. Matrix.RotationZ = function (angle) {
  3107. var result = new Matrix();
  3108. Matrix.RotationZToRef(angle, result);
  3109. return result;
  3110. };
  3111. /**
  3112. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3113. */
  3114. Matrix.RotationZToRef = function (angle, result) {
  3115. var s = Math.sin(angle);
  3116. var c = Math.cos(angle);
  3117. result.m[10] = 1.0;
  3118. result.m[15] = 1.0;
  3119. result.m[0] = c;
  3120. result.m[1] = s;
  3121. result.m[4] = -s;
  3122. result.m[5] = c;
  3123. result.m[2] = 0.0;
  3124. result.m[3] = 0.0;
  3125. result.m[6] = 0.0;
  3126. result.m[7] = 0.0;
  3127. result.m[8] = 0.0;
  3128. result.m[9] = 0.0;
  3129. result.m[11] = 0.0;
  3130. result.m[12] = 0.0;
  3131. result.m[13] = 0.0;
  3132. result.m[14] = 0.0;
  3133. };
  3134. /**
  3135. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3136. */
  3137. Matrix.RotationAxis = function (axis, angle) {
  3138. var result = Matrix.Zero();
  3139. Matrix.RotationAxisToRef(axis, angle, result);
  3140. return result;
  3141. };
  3142. /**
  3143. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3144. */
  3145. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3146. var s = Math.sin(-angle);
  3147. var c = Math.cos(-angle);
  3148. var c1 = 1 - c;
  3149. axis.normalize();
  3150. result.m[0] = (axis.x * axis.x) * c1 + c;
  3151. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3152. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3153. result.m[3] = 0.0;
  3154. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3155. result.m[5] = (axis.y * axis.y) * c1 + c;
  3156. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3157. result.m[7] = 0.0;
  3158. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3159. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3160. result.m[10] = (axis.z * axis.z) * c1 + c;
  3161. result.m[11] = 0.0;
  3162. result.m[15] = 1.0;
  3163. };
  3164. /**
  3165. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3166. */
  3167. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3168. var result = new Matrix();
  3169. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3170. return result;
  3171. };
  3172. /**
  3173. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3174. */
  3175. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3176. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3177. this._tempQuaternion.toRotationMatrix(result);
  3178. };
  3179. /**
  3180. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3181. */
  3182. Matrix.Scaling = function (x, y, z) {
  3183. var result = Matrix.Zero();
  3184. Matrix.ScalingToRef(x, y, z, result);
  3185. return result;
  3186. };
  3187. /**
  3188. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3189. */
  3190. Matrix.ScalingToRef = function (x, y, z, result) {
  3191. result.m[0] = x;
  3192. result.m[1] = 0.0;
  3193. result.m[2] = 0.0;
  3194. result.m[3] = 0.0;
  3195. result.m[4] = 0.0;
  3196. result.m[5] = y;
  3197. result.m[6] = 0.0;
  3198. result.m[7] = 0.0;
  3199. result.m[8] = 0.0;
  3200. result.m[9] = 0.0;
  3201. result.m[10] = z;
  3202. result.m[11] = 0.0;
  3203. result.m[12] = 0.0;
  3204. result.m[13] = 0.0;
  3205. result.m[14] = 0.0;
  3206. result.m[15] = 1.0;
  3207. };
  3208. /**
  3209. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3210. */
  3211. Matrix.Translation = function (x, y, z) {
  3212. var result = Matrix.Identity();
  3213. Matrix.TranslationToRef(x, y, z, result);
  3214. return result;
  3215. };
  3216. /**
  3217. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3218. */
  3219. Matrix.TranslationToRef = function (x, y, z, result) {
  3220. 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);
  3221. };
  3222. /**
  3223. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3224. */
  3225. Matrix.Lerp = function (startValue, endValue, gradient) {
  3226. var result = Matrix.Zero();
  3227. for (var index = 0; index < 16; index++) {
  3228. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3229. }
  3230. return result;
  3231. };
  3232. /**
  3233. * Returns a new Matrix whose values are computed by :
  3234. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3235. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3236. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3237. */
  3238. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3239. var startScale = new Vector3(0, 0, 0);
  3240. var startRotation = new Quaternion();
  3241. var startTranslation = new Vector3(0, 0, 0);
  3242. startValue.decompose(startScale, startRotation, startTranslation);
  3243. var endScale = new Vector3(0, 0, 0);
  3244. var endRotation = new Quaternion();
  3245. var endTranslation = new Vector3(0, 0, 0);
  3246. endValue.decompose(endScale, endRotation, endTranslation);
  3247. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3248. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3249. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3250. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3251. };
  3252. /**
  3253. * 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".
  3254. * This methods works for a Left-Handed system.
  3255. */
  3256. Matrix.LookAtLH = function (eye, target, up) {
  3257. var result = Matrix.Zero();
  3258. Matrix.LookAtLHToRef(eye, target, up, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * 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".
  3263. * This methods works for a Left-Handed system.
  3264. */
  3265. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3266. // Z axis
  3267. target.subtractToRef(eye, this._zAxis);
  3268. this._zAxis.normalize();
  3269. // X axis
  3270. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3271. if (this._xAxis.lengthSquared() === 0) {
  3272. this._xAxis.x = 1.0;
  3273. }
  3274. else {
  3275. this._xAxis.normalize();
  3276. }
  3277. // Y axis
  3278. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3279. this._yAxis.normalize();
  3280. // Eye angles
  3281. var ex = -Vector3.Dot(this._xAxis, eye);
  3282. var ey = -Vector3.Dot(this._yAxis, eye);
  3283. var ez = -Vector3.Dot(this._zAxis, eye);
  3284. 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);
  3285. };
  3286. /**
  3287. * 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".
  3288. * This methods works for a Right-Handed system.
  3289. */
  3290. Matrix.LookAtRH = function (eye, target, up) {
  3291. var result = Matrix.Zero();
  3292. Matrix.LookAtRHToRef(eye, target, up, result);
  3293. return result;
  3294. };
  3295. /**
  3296. * 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".
  3297. * This methods works for a Left-Handed system.
  3298. */
  3299. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3300. // Z axis
  3301. eye.subtractToRef(target, this._zAxis);
  3302. this._zAxis.normalize();
  3303. // X axis
  3304. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3305. if (this._xAxis.lengthSquared() === 0) {
  3306. this._xAxis.x = 1.0;
  3307. }
  3308. else {
  3309. this._xAxis.normalize();
  3310. }
  3311. // Y axis
  3312. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3313. this._yAxis.normalize();
  3314. // Eye angles
  3315. var ex = -Vector3.Dot(this._xAxis, eye);
  3316. var ey = -Vector3.Dot(this._yAxis, eye);
  3317. var ez = -Vector3.Dot(this._zAxis, eye);
  3318. 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);
  3319. };
  3320. /**
  3321. * 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.
  3322. */
  3323. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3324. var matrix = Matrix.Zero();
  3325. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3326. return matrix;
  3327. };
  3328. /**
  3329. * 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.
  3330. */
  3331. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3332. var n = znear;
  3333. var f = zfar;
  3334. var a = 2.0 / width;
  3335. var b = 2.0 / height;
  3336. var c = 2.0 / (f - n);
  3337. var d = -(f + n) / (f - n);
  3338. 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);
  3339. };
  3340. /**
  3341. * 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.
  3342. */
  3343. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3344. var matrix = Matrix.Zero();
  3345. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3346. return matrix;
  3347. };
  3348. /**
  3349. * 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.
  3350. */
  3351. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3352. var n = znear;
  3353. var f = zfar;
  3354. var a = 2.0 / (right - left);
  3355. var b = 2.0 / (top - bottom);
  3356. var c = 2.0 / (f - n);
  3357. var d = -(f + n) / (f - n);
  3358. var i0 = (left + right) / (left - right);
  3359. var i1 = (top + bottom) / (bottom - top);
  3360. 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);
  3361. };
  3362. /**
  3363. * 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.
  3364. */
  3365. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3366. var matrix = Matrix.Zero();
  3367. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3368. return matrix;
  3369. };
  3370. /**
  3371. * 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.
  3372. */
  3373. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3374. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3375. result.m[10] *= -1.0;
  3376. };
  3377. /**
  3378. * 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.
  3379. */
  3380. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3381. var matrix = Matrix.Zero();
  3382. var n = znear;
  3383. var f = zfar;
  3384. var a = 2.0 * n / width;
  3385. var b = 2.0 * n / height;
  3386. var c = (f + n) / (f - n);
  3387. var d = -2.0 * f * n / (f - n);
  3388. 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);
  3389. return matrix;
  3390. };
  3391. /**
  3392. * 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.
  3393. */
  3394. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3395. var matrix = Matrix.Zero();
  3396. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3397. return matrix;
  3398. };
  3399. /**
  3400. * 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.
  3401. */
  3402. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3403. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3404. var n = znear;
  3405. var f = zfar;
  3406. var t = 1.0 / (Math.tan(fov * 0.5));
  3407. var a = isVerticalFovFixed ? (t / aspect) : t;
  3408. var b = isVerticalFovFixed ? t : (t * aspect);
  3409. var c = (f + n) / (f - n);
  3410. var d = -2.0 * f * n / (f - n);
  3411. 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);
  3412. };
  3413. /**
  3414. * 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.
  3415. */
  3416. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3417. var matrix = Matrix.Zero();
  3418. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3419. return matrix;
  3420. };
  3421. /**
  3422. * 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.
  3423. */
  3424. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3425. //alternatively this could be expressed as:
  3426. // m = PerspectiveFovLHToRef
  3427. // m[10] *= -1.0;
  3428. // m[11] *= -1.0;
  3429. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3430. var n = znear;
  3431. var f = zfar;
  3432. var t = 1.0 / (Math.tan(fov * 0.5));
  3433. var a = isVerticalFovFixed ? (t / aspect) : t;
  3434. var b = isVerticalFovFixed ? t : (t * aspect);
  3435. var c = -(f + n) / (f - n);
  3436. var d = -2 * f * n / (f - n);
  3437. 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);
  3438. };
  3439. /**
  3440. * 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.
  3441. */
  3442. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  3443. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3444. //left handed
  3445. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3446. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3447. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3448. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3449. var xScale = 2.0 / (leftTan + rightTan);
  3450. var yScale = 2.0 / (upTan + downTan);
  3451. result.m[0] = xScale;
  3452. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3453. result.m[5] = yScale;
  3454. result.m[6] = result.m[7] = 0.0;
  3455. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  3456. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  3457. result.m[10] = -(znear + zfar) / (zfar - znear);
  3458. // result.m[10] = -zfar / (znear - zfar);
  3459. result.m[11] = 1.0;
  3460. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3461. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3462. // result.m[14] = (znear * zfar) / (znear - zfar);
  3463. };
  3464. /**
  3465. * Returns the final transformation matrix : world * view * projection * viewport
  3466. */
  3467. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3468. var cw = viewport.width;
  3469. var ch = viewport.height;
  3470. var cx = viewport.x;
  3471. var cy = viewport.y;
  3472. 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);
  3473. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3474. };
  3475. /**
  3476. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3477. */
  3478. Matrix.GetAsMatrix2x2 = function (matrix) {
  3479. return new Float32Array([
  3480. matrix.m[0], matrix.m[1],
  3481. matrix.m[4], matrix.m[5]
  3482. ]);
  3483. };
  3484. /**
  3485. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3486. */
  3487. Matrix.GetAsMatrix3x3 = function (matrix) {
  3488. return new Float32Array([
  3489. matrix.m[0], matrix.m[1], matrix.m[2],
  3490. matrix.m[4], matrix.m[5], matrix.m[6],
  3491. matrix.m[8], matrix.m[9], matrix.m[10]
  3492. ]);
  3493. };
  3494. /**
  3495. * Compute the transpose of the passed Matrix.
  3496. * Returns a new Matrix.
  3497. */
  3498. Matrix.Transpose = function (matrix) {
  3499. var result = new Matrix();
  3500. result.m[0] = matrix.m[0];
  3501. result.m[1] = matrix.m[4];
  3502. result.m[2] = matrix.m[8];
  3503. result.m[3] = matrix.m[12];
  3504. result.m[4] = matrix.m[1];
  3505. result.m[5] = matrix.m[5];
  3506. result.m[6] = matrix.m[9];
  3507. result.m[7] = matrix.m[13];
  3508. result.m[8] = matrix.m[2];
  3509. result.m[9] = matrix.m[6];
  3510. result.m[10] = matrix.m[10];
  3511. result.m[11] = matrix.m[14];
  3512. result.m[12] = matrix.m[3];
  3513. result.m[13] = matrix.m[7];
  3514. result.m[14] = matrix.m[11];
  3515. result.m[15] = matrix.m[15];
  3516. return result;
  3517. };
  3518. /**
  3519. * Returns a new Matrix as the reflection matrix across the passed plane.
  3520. */
  3521. Matrix.Reflection = function (plane) {
  3522. var matrix = new Matrix();
  3523. Matrix.ReflectionToRef(plane, matrix);
  3524. return matrix;
  3525. };
  3526. /**
  3527. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3528. */
  3529. Matrix.ReflectionToRef = function (plane, result) {
  3530. plane.normalize();
  3531. var x = plane.normal.x;
  3532. var y = plane.normal.y;
  3533. var z = plane.normal.z;
  3534. var temp = -2 * x;
  3535. var temp2 = -2 * y;
  3536. var temp3 = -2 * z;
  3537. result.m[0] = (temp * x) + 1;
  3538. result.m[1] = temp2 * x;
  3539. result.m[2] = temp3 * x;
  3540. result.m[3] = 0.0;
  3541. result.m[4] = temp * y;
  3542. result.m[5] = (temp2 * y) + 1;
  3543. result.m[6] = temp3 * y;
  3544. result.m[7] = 0.0;
  3545. result.m[8] = temp * z;
  3546. result.m[9] = temp2 * z;
  3547. result.m[10] = (temp3 * z) + 1;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = temp * plane.d;
  3550. result.m[13] = temp2 * plane.d;
  3551. result.m[14] = temp3 * plane.d;
  3552. result.m[15] = 1.0;
  3553. };
  3554. /**
  3555. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3556. */
  3557. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3558. mat.m[0] = xaxis.x;
  3559. mat.m[1] = xaxis.y;
  3560. mat.m[2] = xaxis.z;
  3561. mat.m[3] = 0.0;
  3562. mat.m[4] = yaxis.x;
  3563. mat.m[5] = yaxis.y;
  3564. mat.m[6] = yaxis.z;
  3565. mat.m[7] = 0.0;
  3566. mat.m[8] = zaxis.x;
  3567. mat.m[9] = zaxis.y;
  3568. mat.m[10] = zaxis.z;
  3569. mat.m[11] = 0.0;
  3570. mat.m[12] = 0.0;
  3571. mat.m[13] = 0.0;
  3572. mat.m[14] = 0.0;
  3573. mat.m[15] = 1.0;
  3574. };
  3575. /**
  3576. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3577. */
  3578. Matrix.FromQuaternionToRef = function (quat, result) {
  3579. var xx = quat.x * quat.x;
  3580. var yy = quat.y * quat.y;
  3581. var zz = quat.z * quat.z;
  3582. var xy = quat.x * quat.y;
  3583. var zw = quat.z * quat.w;
  3584. var zx = quat.z * quat.x;
  3585. var yw = quat.y * quat.w;
  3586. var yz = quat.y * quat.z;
  3587. var xw = quat.x * quat.w;
  3588. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3589. result.m[1] = 2.0 * (xy + zw);
  3590. result.m[2] = 2.0 * (zx - yw);
  3591. result.m[3] = 0.0;
  3592. result.m[4] = 2.0 * (xy - zw);
  3593. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3594. result.m[6] = 2.0 * (yz + xw);
  3595. result.m[7] = 0.0;
  3596. result.m[8] = 2.0 * (zx + yw);
  3597. result.m[9] = 2.0 * (yz - xw);
  3598. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3599. result.m[11] = 0.0;
  3600. result.m[12] = 0.0;
  3601. result.m[13] = 0.0;
  3602. result.m[14] = 0.0;
  3603. result.m[15] = 1.0;
  3604. };
  3605. return Matrix;
  3606. }());
  3607. Matrix._tempQuaternion = new Quaternion();
  3608. Matrix._xAxis = Vector3.Zero();
  3609. Matrix._yAxis = Vector3.Zero();
  3610. Matrix._zAxis = Vector3.Zero();
  3611. BABYLON.Matrix = Matrix;
  3612. var Plane = (function () {
  3613. /**
  3614. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3615. */
  3616. function Plane(a, b, c, d) {
  3617. this.normal = new Vector3(a, b, c);
  3618. this.d = d;
  3619. }
  3620. /**
  3621. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3622. */
  3623. Plane.prototype.asArray = function () {
  3624. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3625. };
  3626. // Methods
  3627. /**
  3628. * Returns a new plane copied from the current Plane.
  3629. */
  3630. Plane.prototype.clone = function () {
  3631. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3632. };
  3633. /**
  3634. * Returns the string "Plane".
  3635. */
  3636. Plane.prototype.getClassName = function () {
  3637. return "Plane";
  3638. };
  3639. /**
  3640. * Returns the Plane hash code.
  3641. */
  3642. Plane.prototype.getHashCode = function () {
  3643. var hash = this.normal.getHashCode();
  3644. hash = (hash * 397) ^ (this.d || 0);
  3645. return hash;
  3646. };
  3647. /**
  3648. * Normalize the current Plane in place.
  3649. * Returns the updated Plane.
  3650. */
  3651. Plane.prototype.normalize = function () {
  3652. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3653. var magnitude = 0.0;
  3654. if (norm !== 0) {
  3655. magnitude = 1.0 / norm;
  3656. }
  3657. this.normal.x *= magnitude;
  3658. this.normal.y *= magnitude;
  3659. this.normal.z *= magnitude;
  3660. this.d *= magnitude;
  3661. return this;
  3662. };
  3663. /**
  3664. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3665. */
  3666. Plane.prototype.transform = function (transformation) {
  3667. var transposedMatrix = Matrix.Transpose(transformation);
  3668. var x = this.normal.x;
  3669. var y = this.normal.y;
  3670. var z = this.normal.z;
  3671. var d = this.d;
  3672. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3673. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3674. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3675. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3676. return new Plane(normalX, normalY, normalZ, finalD);
  3677. };
  3678. /**
  3679. * Returns the dot product (float) of the point coordinates and the plane normal.
  3680. */
  3681. Plane.prototype.dotCoordinate = function (point) {
  3682. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3683. };
  3684. /**
  3685. * Updates the current Plane from the plane defined by the three passed points.
  3686. * Returns the updated Plane.
  3687. */
  3688. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3689. var x1 = point2.x - point1.x;
  3690. var y1 = point2.y - point1.y;
  3691. var z1 = point2.z - point1.z;
  3692. var x2 = point3.x - point1.x;
  3693. var y2 = point3.y - point1.y;
  3694. var z2 = point3.z - point1.z;
  3695. var yz = (y1 * z2) - (z1 * y2);
  3696. var xz = (z1 * x2) - (x1 * z2);
  3697. var xy = (x1 * y2) - (y1 * x2);
  3698. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3699. var invPyth;
  3700. if (pyth !== 0) {
  3701. invPyth = 1.0 / pyth;
  3702. }
  3703. else {
  3704. invPyth = 0.0;
  3705. }
  3706. this.normal.x = yz * invPyth;
  3707. this.normal.y = xz * invPyth;
  3708. this.normal.z = xy * invPyth;
  3709. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3710. return this;
  3711. };
  3712. /**
  3713. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3714. */
  3715. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3716. var dot = Vector3.Dot(this.normal, direction);
  3717. return (dot <= epsilon);
  3718. };
  3719. /**
  3720. * Returns the signed distance (float) from the passed point to the Plane.
  3721. */
  3722. Plane.prototype.signedDistanceTo = function (point) {
  3723. return Vector3.Dot(point, this.normal) + this.d;
  3724. };
  3725. // Statics
  3726. /**
  3727. * Returns a new Plane from the passed array.
  3728. */
  3729. Plane.FromArray = function (array) {
  3730. return new Plane(array[0], array[1], array[2], array[3]);
  3731. };
  3732. /**
  3733. * Returns a new Plane defined by the three passed points.
  3734. */
  3735. Plane.FromPoints = function (point1, point2, point3) {
  3736. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3737. result.copyFromPoints(point1, point2, point3);
  3738. return result;
  3739. };
  3740. /**
  3741. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3742. * Note : the vector "normal" is updated because normalized.
  3743. */
  3744. Plane.FromPositionAndNormal = function (origin, normal) {
  3745. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3746. normal.normalize();
  3747. result.normal = normal;
  3748. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3749. return result;
  3750. };
  3751. /**
  3752. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3753. */
  3754. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3755. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3756. return Vector3.Dot(point, normal) + d;
  3757. };
  3758. return Plane;
  3759. }());
  3760. BABYLON.Plane = Plane;
  3761. var Viewport = (function () {
  3762. /**
  3763. * Creates a Viewport object located at (x, y) and sized (width, height).
  3764. */
  3765. function Viewport(x, y, width, height) {
  3766. this.x = x;
  3767. this.y = y;
  3768. this.width = width;
  3769. this.height = height;
  3770. }
  3771. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3772. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3773. };
  3774. /**
  3775. * Returns a new Viewport copied from the current one.
  3776. */
  3777. Viewport.prototype.clone = function () {
  3778. return new Viewport(this.x, this.y, this.width, this.height);
  3779. };
  3780. return Viewport;
  3781. }());
  3782. BABYLON.Viewport = Viewport;
  3783. var Frustum = (function () {
  3784. function Frustum() {
  3785. }
  3786. /**
  3787. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3788. */
  3789. Frustum.GetPlanes = function (transform) {
  3790. var frustumPlanes = [];
  3791. for (var index = 0; index < 6; index++) {
  3792. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3793. }
  3794. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3795. return frustumPlanes;
  3796. };
  3797. /**
  3798. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3799. */
  3800. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3801. // Near
  3802. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3803. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3804. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3805. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3806. frustumPlanes[0].normalize();
  3807. // Far
  3808. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3809. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3810. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3811. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3812. frustumPlanes[1].normalize();
  3813. // Left
  3814. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3815. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3816. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3817. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3818. frustumPlanes[2].normalize();
  3819. // Right
  3820. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3821. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3822. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3823. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3824. frustumPlanes[3].normalize();
  3825. // Top
  3826. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3827. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3828. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3829. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3830. frustumPlanes[4].normalize();
  3831. // Bottom
  3832. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3833. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3834. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3835. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3836. frustumPlanes[5].normalize();
  3837. };
  3838. return Frustum;
  3839. }());
  3840. BABYLON.Frustum = Frustum;
  3841. var Space;
  3842. (function (Space) {
  3843. Space[Space["LOCAL"] = 0] = "LOCAL";
  3844. Space[Space["WORLD"] = 1] = "WORLD";
  3845. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  3846. var Axis = (function () {
  3847. function Axis() {
  3848. }
  3849. return Axis;
  3850. }());
  3851. Axis.X = new Vector3(1.0, 0.0, 0.0);
  3852. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  3853. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  3854. BABYLON.Axis = Axis;
  3855. ;
  3856. var BezierCurve = (function () {
  3857. function BezierCurve() {
  3858. }
  3859. /**
  3860. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  3861. */
  3862. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  3863. // Extract X (which is equal to time here)
  3864. var f0 = 1 - 3 * x2 + 3 * x1;
  3865. var f1 = 3 * x2 - 6 * x1;
  3866. var f2 = 3 * x1;
  3867. var refinedT = t;
  3868. for (var i = 0; i < 5; i++) {
  3869. var refinedT2 = refinedT * refinedT;
  3870. var refinedT3 = refinedT2 * refinedT;
  3871. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  3872. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  3873. refinedT -= (x - t) * slope;
  3874. refinedT = Math.min(1, Math.max(0, refinedT));
  3875. }
  3876. // Resolve cubic bezier for the given x
  3877. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  3878. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  3879. Math.pow(refinedT, 3);
  3880. };
  3881. return BezierCurve;
  3882. }());
  3883. BABYLON.BezierCurve = BezierCurve;
  3884. var Orientation;
  3885. (function (Orientation) {
  3886. Orientation[Orientation["CW"] = 0] = "CW";
  3887. Orientation[Orientation["CCW"] = 1] = "CCW";
  3888. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  3889. var Angle = (function () {
  3890. /**
  3891. * Creates an Angle object of "radians" radians (float).
  3892. */
  3893. function Angle(radians) {
  3894. var _this = this;
  3895. /**
  3896. * Returns the Angle value in degrees (float).
  3897. */
  3898. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  3899. /**
  3900. * Returns the Angle value in radians (float).
  3901. */
  3902. this.radians = function () { return _this._radians; };
  3903. this._radians = radians;
  3904. if (this._radians < 0.0)
  3905. this._radians += (2.0 * Math.PI);
  3906. }
  3907. /**
  3908. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  3909. */
  3910. Angle.BetweenTwoPoints = function (a, b) {
  3911. var delta = b.subtract(a);
  3912. var theta = Math.atan2(delta.y, delta.x);
  3913. return new Angle(theta);
  3914. };
  3915. /**
  3916. * Returns a new Angle object from the passed float in radians.
  3917. */
  3918. Angle.FromRadians = function (radians) {
  3919. return new Angle(radians);
  3920. };
  3921. /**
  3922. * Returns a new Angle object from the passed float in degrees.
  3923. */
  3924. Angle.FromDegrees = function (degrees) {
  3925. return new Angle(degrees * Math.PI / 180.0);
  3926. };
  3927. return Angle;
  3928. }());
  3929. BABYLON.Angle = Angle;
  3930. var Arc2 = (function () {
  3931. /**
  3932. * Creates an Arc object from the three passed points : start, middle and end.
  3933. */
  3934. function Arc2(startPoint, midPoint, endPoint) {
  3935. this.startPoint = startPoint;
  3936. this.midPoint = midPoint;
  3937. this.endPoint = endPoint;
  3938. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  3939. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  3940. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  3941. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  3942. 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);
  3943. this.radius = this.centerPoint.subtract(this.startPoint).length();
  3944. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  3945. var a1 = this.startAngle.degrees();
  3946. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  3947. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  3948. // angles correction
  3949. if (a2 - a1 > +180.0)
  3950. a2 -= 360.0;
  3951. if (a2 - a1 < -180.0)
  3952. a2 += 360.0;
  3953. if (a3 - a2 > +180.0)
  3954. a3 -= 360.0;
  3955. if (a3 - a2 < -180.0)
  3956. a3 += 360.0;
  3957. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  3958. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  3959. }
  3960. return Arc2;
  3961. }());
  3962. BABYLON.Arc2 = Arc2;
  3963. var Path2 = (function () {
  3964. /**
  3965. * Creates a Path2 object from the starting 2D coordinates x and y.
  3966. */
  3967. function Path2(x, y) {
  3968. this._points = new Array();
  3969. this._length = 0.0;
  3970. this.closed = false;
  3971. this._points.push(new Vector2(x, y));
  3972. }
  3973. /**
  3974. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  3975. * Returns the updated Path2.
  3976. */
  3977. Path2.prototype.addLineTo = function (x, y) {
  3978. if (closed) {
  3979. //Tools.Error("cannot add lines to closed paths");
  3980. return this;
  3981. }
  3982. var newPoint = new Vector2(x, y);
  3983. var previousPoint = this._points[this._points.length - 1];
  3984. this._points.push(newPoint);
  3985. this._length += newPoint.subtract(previousPoint).length();
  3986. return this;
  3987. };
  3988. /**
  3989. * 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.
  3990. * Returns the updated Path2.
  3991. */
  3992. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  3993. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  3994. if (closed) {
  3995. //Tools.Error("cannot add arcs to closed paths");
  3996. return this;
  3997. }
  3998. var startPoint = this._points[this._points.length - 1];
  3999. var midPoint = new Vector2(midX, midY);
  4000. var endPoint = new Vector2(endX, endY);
  4001. var arc = new Arc2(startPoint, midPoint, endPoint);
  4002. var increment = arc.angle.radians() / numberOfSegments;
  4003. if (arc.orientation === Orientation.CW)
  4004. increment *= -1;
  4005. var currentAngle = arc.startAngle.radians() + increment;
  4006. for (var i = 0; i < numberOfSegments; i++) {
  4007. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4008. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4009. this.addLineTo(x, y);
  4010. currentAngle += increment;
  4011. }
  4012. return this;
  4013. };
  4014. /**
  4015. * Closes the Path2.
  4016. * Returns the Path2.
  4017. */
  4018. Path2.prototype.close = function () {
  4019. this.closed = true;
  4020. return this;
  4021. };
  4022. /**
  4023. * Returns the Path2 total length (float).
  4024. */
  4025. Path2.prototype.length = function () {
  4026. var result = this._length;
  4027. if (!this.closed) {
  4028. var lastPoint = this._points[this._points.length - 1];
  4029. var firstPoint = this._points[0];
  4030. result += (firstPoint.subtract(lastPoint).length());
  4031. }
  4032. return result;
  4033. };
  4034. /**
  4035. * Returns the Path2 internal array of points.
  4036. */
  4037. Path2.prototype.getPoints = function () {
  4038. return this._points;
  4039. };
  4040. /**
  4041. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4042. */
  4043. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4044. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4045. //Tools.Error("normalized length position should be between 0 and 1.");
  4046. return Vector2.Zero();
  4047. }
  4048. var lengthPosition = normalizedLengthPosition * this.length();
  4049. var previousOffset = 0;
  4050. for (var i = 0; i < this._points.length; i++) {
  4051. var j = (i + 1) % this._points.length;
  4052. var a = this._points[i];
  4053. var b = this._points[j];
  4054. var bToA = b.subtract(a);
  4055. var nextOffset = (bToA.length() + previousOffset);
  4056. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4057. var dir = bToA.normalize();
  4058. var localOffset = lengthPosition - previousOffset;
  4059. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4060. }
  4061. previousOffset = nextOffset;
  4062. }
  4063. //Tools.Error("internal error");
  4064. return Vector2.Zero();
  4065. };
  4066. /**
  4067. * Returns a new Path2 starting at the coordinates (x, y).
  4068. */
  4069. Path2.StartingAt = function (x, y) {
  4070. return new Path2(x, y);
  4071. };
  4072. return Path2;
  4073. }());
  4074. BABYLON.Path2 = Path2;
  4075. var Path3D = (function () {
  4076. /**
  4077. * new Path3D(path, normal, raw)
  4078. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4079. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4080. * path : an array of Vector3, the curve axis of the Path3D
  4081. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4082. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4083. */
  4084. function Path3D(path, firstNormal, raw) {
  4085. this.path = path;
  4086. this._curve = new Array();
  4087. this._distances = new Array();
  4088. this._tangents = new Array();
  4089. this._normals = new Array();
  4090. this._binormals = new Array();
  4091. for (var p = 0; p < path.length; p++) {
  4092. this._curve[p] = path[p].clone(); // hard copy
  4093. }
  4094. this._raw = raw || false;
  4095. this._compute(firstNormal);
  4096. }
  4097. /**
  4098. * Returns the Path3D array of successive Vector3 designing its curve.
  4099. */
  4100. Path3D.prototype.getCurve = function () {
  4101. return this._curve;
  4102. };
  4103. /**
  4104. * Returns an array populated with tangent vectors on each Path3D curve point.
  4105. */
  4106. Path3D.prototype.getTangents = function () {
  4107. return this._tangents;
  4108. };
  4109. /**
  4110. * Returns an array populated with normal vectors on each Path3D curve point.
  4111. */
  4112. Path3D.prototype.getNormals = function () {
  4113. return this._normals;
  4114. };
  4115. /**
  4116. * Returns an array populated with binormal vectors on each Path3D curve point.
  4117. */
  4118. Path3D.prototype.getBinormals = function () {
  4119. return this._binormals;
  4120. };
  4121. /**
  4122. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4123. */
  4124. Path3D.prototype.getDistances = function () {
  4125. return this._distances;
  4126. };
  4127. /**
  4128. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4129. * Returns the same object updated.
  4130. */
  4131. Path3D.prototype.update = function (path, firstNormal) {
  4132. for (var p = 0; p < path.length; p++) {
  4133. this._curve[p].x = path[p].x;
  4134. this._curve[p].y = path[p].y;
  4135. this._curve[p].z = path[p].z;
  4136. }
  4137. this._compute(firstNormal);
  4138. return this;
  4139. };
  4140. // private function compute() : computes tangents, normals and binormals
  4141. Path3D.prototype._compute = function (firstNormal) {
  4142. var l = this._curve.length;
  4143. // first and last tangents
  4144. this._tangents[0] = this._getFirstNonNullVector(0);
  4145. if (!this._raw) {
  4146. this._tangents[0].normalize();
  4147. }
  4148. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4149. if (!this._raw) {
  4150. this._tangents[l - 1].normalize();
  4151. }
  4152. // normals and binormals at first point : arbitrary vector with _normalVector()
  4153. var tg0 = this._tangents[0];
  4154. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4155. this._normals[0] = pp0;
  4156. if (!this._raw) {
  4157. this._normals[0].normalize();
  4158. }
  4159. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4160. if (!this._raw) {
  4161. this._binormals[0].normalize();
  4162. }
  4163. this._distances[0] = 0.0;
  4164. // normals and binormals : next points
  4165. var prev; // previous vector (segment)
  4166. var cur; // current vector (segment)
  4167. var curTang; // current tangent
  4168. // previous normal
  4169. var prevBinor; // previous binormal
  4170. for (var i = 1; i < l; i++) {
  4171. // tangents
  4172. prev = this._getLastNonNullVector(i);
  4173. if (i < l - 1) {
  4174. cur = this._getFirstNonNullVector(i);
  4175. this._tangents[i] = prev.add(cur);
  4176. this._tangents[i].normalize();
  4177. }
  4178. this._distances[i] = this._distances[i - 1] + prev.length();
  4179. // normals and binormals
  4180. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4181. curTang = this._tangents[i];
  4182. prevBinor = this._binormals[i - 1];
  4183. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4184. if (!this._raw) {
  4185. this._normals[i].normalize();
  4186. }
  4187. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4188. if (!this._raw) {
  4189. this._binormals[i].normalize();
  4190. }
  4191. }
  4192. };
  4193. // private function getFirstNonNullVector(index)
  4194. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4195. Path3D.prototype._getFirstNonNullVector = function (index) {
  4196. var i = 1;
  4197. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4198. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4199. i++;
  4200. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4201. }
  4202. return nNVector;
  4203. };
  4204. // private function getLastNonNullVector(index)
  4205. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4206. Path3D.prototype._getLastNonNullVector = function (index) {
  4207. var i = 1;
  4208. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4209. while (nLVector.length() === 0 && index > i + 1) {
  4210. i++;
  4211. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4212. }
  4213. return nLVector;
  4214. };
  4215. // private function normalVector(v0, vt, va) :
  4216. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4217. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4218. Path3D.prototype._normalVector = function (v0, vt, va) {
  4219. var normal0;
  4220. var tgl = vt.length();
  4221. if (tgl === 0.0) {
  4222. tgl = 1.0;
  4223. }
  4224. if (va === undefined || va === null) {
  4225. var point;
  4226. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4227. point = new Vector3(0.0, -1.0, 0.0);
  4228. }
  4229. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4230. point = new Vector3(1.0, 0.0, 0.0);
  4231. }
  4232. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4233. point = new Vector3(0.0, 0.0, 1.0);
  4234. }
  4235. normal0 = Vector3.Cross(vt, point);
  4236. }
  4237. else {
  4238. normal0 = Vector3.Cross(vt, va);
  4239. Vector3.CrossToRef(normal0, vt, normal0);
  4240. }
  4241. normal0.normalize();
  4242. return normal0;
  4243. };
  4244. return Path3D;
  4245. }());
  4246. BABYLON.Path3D = Path3D;
  4247. var Curve3 = (function () {
  4248. /**
  4249. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4250. * A Curve3 is designed from a series of successive Vector3.
  4251. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4252. */
  4253. function Curve3(points) {
  4254. this._length = 0.0;
  4255. this._points = points;
  4256. this._length = this._computeLength(points);
  4257. }
  4258. /**
  4259. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4260. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4261. * @param v1 (Vector3) the control point
  4262. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4263. * @param nbPoints (integer) the wanted number of points in the curve
  4264. */
  4265. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4266. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4267. var bez = new Array();
  4268. var equation = function (t, val0, val1, val2) {
  4269. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4270. return res;
  4271. };
  4272. for (var i = 0; i <= nbPoints; i++) {
  4273. 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)));
  4274. }
  4275. return new Curve3(bez);
  4276. };
  4277. /**
  4278. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4279. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4280. * @param v1 (Vector3) the first control point
  4281. * @param v2 (Vector3) the second control point
  4282. * @param v3 (Vector3) the end point of the Cubic Bezier
  4283. * @param nbPoints (integer) the wanted number of points in the curve
  4284. */
  4285. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4286. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4287. var bez = new Array();
  4288. var equation = function (t, val0, val1, val2, val3) {
  4289. 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;
  4290. return res;
  4291. };
  4292. for (var i = 0; i <= nbPoints; i++) {
  4293. 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)));
  4294. }
  4295. return new Curve3(bez);
  4296. };
  4297. /**
  4298. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4299. * @param p1 (Vector3) the origin point of the Hermite Spline
  4300. * @param t1 (Vector3) the tangent vector at the origin point
  4301. * @param p2 (Vector3) the end point of the Hermite Spline
  4302. * @param t2 (Vector3) the tangent vector at the end point
  4303. * @param nbPoints (integer) the wanted number of points in the curve
  4304. */
  4305. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4306. var hermite = new Array();
  4307. var step = 1.0 / nbPoints;
  4308. for (var i = 0; i <= nbPoints; i++) {
  4309. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4310. }
  4311. return new Curve3(hermite);
  4312. };
  4313. /**
  4314. * Returns a Curve3 object along a CatmullRom Spline curve :
  4315. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4316. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4317. */
  4318. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4319. var totalPoints = new Array();
  4320. totalPoints.push(points[0].clone());
  4321. Array.prototype.push.apply(totalPoints, points);
  4322. totalPoints.push(points[points.length - 1].clone());
  4323. var catmullRom = new Array();
  4324. var step = 1.0 / nbPoints;
  4325. for (var i = 0; i < totalPoints.length - 3; i++) {
  4326. var amount = 0.0;
  4327. for (var c = 0; c < nbPoints; c++) {
  4328. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4329. amount += step;
  4330. }
  4331. }
  4332. i--;
  4333. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4334. return new Curve3(catmullRom);
  4335. };
  4336. /**
  4337. * Returns the Curve3 stored array of successive Vector3
  4338. */
  4339. Curve3.prototype.getPoints = function () {
  4340. return this._points;
  4341. };
  4342. /**
  4343. * Returns the computed length (float) of the curve.
  4344. */
  4345. Curve3.prototype.length = function () {
  4346. return this._length;
  4347. };
  4348. /**
  4349. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4350. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4351. * curveA and curveB keep unchanged.
  4352. */
  4353. Curve3.prototype.continue = function (curve) {
  4354. var lastPoint = this._points[this._points.length - 1];
  4355. var continuedPoints = this._points.slice();
  4356. var curvePoints = curve.getPoints();
  4357. for (var i = 1; i < curvePoints.length; i++) {
  4358. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4359. }
  4360. var continuedCurve = new Curve3(continuedPoints);
  4361. return continuedCurve;
  4362. };
  4363. Curve3.prototype._computeLength = function (path) {
  4364. var l = 0;
  4365. for (var i = 1; i < path.length; i++) {
  4366. l += (path[i].subtract(path[i - 1])).length();
  4367. }
  4368. return l;
  4369. };
  4370. return Curve3;
  4371. }());
  4372. BABYLON.Curve3 = Curve3;
  4373. // SphericalHarmonics
  4374. var SphericalHarmonics = (function () {
  4375. function SphericalHarmonics() {
  4376. this.L00 = Vector3.Zero();
  4377. this.L1_1 = Vector3.Zero();
  4378. this.L10 = Vector3.Zero();
  4379. this.L11 = Vector3.Zero();
  4380. this.L2_2 = Vector3.Zero();
  4381. this.L2_1 = Vector3.Zero();
  4382. this.L20 = Vector3.Zero();
  4383. this.L21 = Vector3.Zero();
  4384. this.L22 = Vector3.Zero();
  4385. }
  4386. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4387. var colorVector = new Vector3(color.r, color.g, color.b);
  4388. var c = colorVector.scale(deltaSolidAngle);
  4389. this.L00 = this.L00.add(c.scale(0.282095));
  4390. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4391. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4392. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4393. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4394. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4395. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4396. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4397. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4398. };
  4399. SphericalHarmonics.prototype.scale = function (scale) {
  4400. this.L00 = this.L00.scale(scale);
  4401. this.L1_1 = this.L1_1.scale(scale);
  4402. this.L10 = this.L10.scale(scale);
  4403. this.L11 = this.L11.scale(scale);
  4404. this.L2_2 = this.L2_2.scale(scale);
  4405. this.L2_1 = this.L2_1.scale(scale);
  4406. this.L20 = this.L20.scale(scale);
  4407. this.L21 = this.L21.scale(scale);
  4408. this.L22 = this.L22.scale(scale);
  4409. };
  4410. return SphericalHarmonics;
  4411. }());
  4412. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4413. // SphericalPolynomial
  4414. var SphericalPolynomial = (function () {
  4415. function SphericalPolynomial() {
  4416. this.x = Vector3.Zero();
  4417. this.y = Vector3.Zero();
  4418. this.z = Vector3.Zero();
  4419. this.xx = Vector3.Zero();
  4420. this.yy = Vector3.Zero();
  4421. this.zz = Vector3.Zero();
  4422. this.xy = Vector3.Zero();
  4423. this.yz = Vector3.Zero();
  4424. this.zx = Vector3.Zero();
  4425. }
  4426. SphericalPolynomial.prototype.addAmbient = function (color) {
  4427. var colorVector = new Vector3(color.r, color.g, color.b);
  4428. this.xx = this.xx.add(colorVector);
  4429. this.yy = this.yy.add(colorVector);
  4430. this.zz = this.zz.add(colorVector);
  4431. };
  4432. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4433. var result = new SphericalPolynomial();
  4434. result.x = harmonics.L11.scale(1.02333);
  4435. result.y = harmonics.L1_1.scale(1.02333);
  4436. result.z = harmonics.L10.scale(1.02333);
  4437. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4438. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4439. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4440. result.yz = harmonics.L2_1.scale(0.858086);
  4441. result.zx = harmonics.L21.scale(0.858086);
  4442. result.xy = harmonics.L2_2.scale(0.858086);
  4443. return result;
  4444. };
  4445. return SphericalPolynomial;
  4446. }());
  4447. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4448. // Vertex formats
  4449. var PositionNormalVertex = (function () {
  4450. function PositionNormalVertex(position, normal) {
  4451. if (position === void 0) { position = Vector3.Zero(); }
  4452. if (normal === void 0) { normal = Vector3.Up(); }
  4453. this.position = position;
  4454. this.normal = normal;
  4455. }
  4456. PositionNormalVertex.prototype.clone = function () {
  4457. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4458. };
  4459. return PositionNormalVertex;
  4460. }());
  4461. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4462. var PositionNormalTextureVertex = (function () {
  4463. function PositionNormalTextureVertex(position, normal, uv) {
  4464. if (position === void 0) { position = Vector3.Zero(); }
  4465. if (normal === void 0) { normal = Vector3.Up(); }
  4466. if (uv === void 0) { uv = Vector2.Zero(); }
  4467. this.position = position;
  4468. this.normal = normal;
  4469. this.uv = uv;
  4470. }
  4471. PositionNormalTextureVertex.prototype.clone = function () {
  4472. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4473. };
  4474. return PositionNormalTextureVertex;
  4475. }());
  4476. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4477. // Temporary pre-allocated objects for engine internal use
  4478. // usage in any internal function :
  4479. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4480. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4481. var Tmp = (function () {
  4482. function Tmp() {
  4483. }
  4484. return Tmp;
  4485. }());
  4486. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4487. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4488. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4489. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4490. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4491. Tmp.Quaternion = [new Quaternion(0.0, 0.0, 0.0, 0.0),
  4492. new Quaternion(0.0, 0.0, 0.0, 0.0)]; // 2 temp Quaternion at once should be enough
  4493. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4494. Matrix.Zero(), Matrix.Zero(),
  4495. Matrix.Zero(), Matrix.Zero(),
  4496. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4497. BABYLON.Tmp = Tmp;
  4498. })(BABYLON || (BABYLON = {}));
  4499. //# sourceMappingURL=babylon.math.js.map
  4500. //# sourceMappingURL=babylon.mixins.js.map
  4501. var BABYLON;
  4502. (function (BABYLON) {
  4503. function generateSerializableMember(type, sourceName) {
  4504. return function (target, propertyKey) {
  4505. if (!target.__serializableMembers) {
  4506. target.__serializableMembers = {};
  4507. }
  4508. if (!target.__serializableMembers[propertyKey]) {
  4509. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4510. }
  4511. };
  4512. }
  4513. function serialize(sourceName) {
  4514. return generateSerializableMember(0, sourceName); // value member
  4515. }
  4516. BABYLON.serialize = serialize;
  4517. function serializeAsTexture(sourceName) {
  4518. return generateSerializableMember(1, sourceName); // texture member
  4519. }
  4520. BABYLON.serializeAsTexture = serializeAsTexture;
  4521. function serializeAsColor3(sourceName) {
  4522. return generateSerializableMember(2, sourceName); // color3 member
  4523. }
  4524. BABYLON.serializeAsColor3 = serializeAsColor3;
  4525. function serializeAsFresnelParameters(sourceName) {
  4526. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4527. }
  4528. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4529. function serializeAsVector2(sourceName) {
  4530. return generateSerializableMember(4, sourceName); // vector2 member
  4531. }
  4532. BABYLON.serializeAsVector2 = serializeAsVector2;
  4533. function serializeAsVector3(sourceName) {
  4534. return generateSerializableMember(5, sourceName); // vector3 member
  4535. }
  4536. BABYLON.serializeAsVector3 = serializeAsVector3;
  4537. function serializeAsMeshReference(sourceName) {
  4538. return generateSerializableMember(6, sourceName); // mesh reference member
  4539. }
  4540. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4541. function serializeAsColorCurves(sourceName) {
  4542. return generateSerializableMember(7, sourceName); // color curves
  4543. }
  4544. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4545. var SerializationHelper = (function () {
  4546. function SerializationHelper() {
  4547. }
  4548. SerializationHelper.Serialize = function (entity, serializationObject) {
  4549. if (!serializationObject) {
  4550. serializationObject = {};
  4551. }
  4552. // Tags
  4553. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4554. // Properties
  4555. for (var property in entity.__serializableMembers) {
  4556. var propertyDescriptor = entity.__serializableMembers[property];
  4557. var targetPropertyName = propertyDescriptor.sourceName || property;
  4558. var propertyType = propertyDescriptor.type;
  4559. var sourceProperty = entity[property];
  4560. if (sourceProperty !== undefined && sourceProperty !== null) {
  4561. switch (propertyType) {
  4562. case 0:
  4563. serializationObject[targetPropertyName] = sourceProperty;
  4564. break;
  4565. case 1:
  4566. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4567. break;
  4568. case 2:
  4569. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4570. break;
  4571. case 3:
  4572. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4573. break;
  4574. case 4:
  4575. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4576. break;
  4577. case 5:
  4578. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4579. break;
  4580. case 6:
  4581. serializationObject[targetPropertyName] = sourceProperty.id;
  4582. break;
  4583. case 7:
  4584. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4585. break;
  4586. }
  4587. }
  4588. }
  4589. return serializationObject;
  4590. };
  4591. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4592. var destination = creationFunction();
  4593. // Tags
  4594. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4595. // Properties
  4596. for (var property in destination.__serializableMembers) {
  4597. var propertyDescriptor = destination.__serializableMembers[property];
  4598. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4599. var propertyType = propertyDescriptor.type;
  4600. if (sourceProperty !== undefined && sourceProperty !== null) {
  4601. switch (propertyType) {
  4602. case 0:
  4603. destination[property] = sourceProperty;
  4604. break;
  4605. case 1:
  4606. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4607. break;
  4608. case 2:
  4609. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4610. break;
  4611. case 3:
  4612. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4613. break;
  4614. case 4:
  4615. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4616. break;
  4617. case 5:
  4618. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4619. break;
  4620. case 6:
  4621. destination[property] = scene.getLastMeshByID(sourceProperty);
  4622. break;
  4623. case 7:
  4624. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4625. break;
  4626. }
  4627. }
  4628. }
  4629. return destination;
  4630. };
  4631. SerializationHelper.Clone = function (creationFunction, source) {
  4632. var destination = creationFunction();
  4633. // Tags
  4634. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4635. // Properties
  4636. for (var property in destination.__serializableMembers) {
  4637. var propertyDescriptor = destination.__serializableMembers[property];
  4638. var sourceProperty = source[property];
  4639. var propertyType = propertyDescriptor.type;
  4640. if (sourceProperty !== undefined && sourceProperty !== null) {
  4641. switch (propertyType) {
  4642. case 0: // Value
  4643. case 6:
  4644. destination[property] = sourceProperty;
  4645. break;
  4646. case 1: // Texture
  4647. case 2: // Color3
  4648. case 3: // FresnelParameters
  4649. case 4: // Vector2
  4650. case 5: // Vector3
  4651. case 7:
  4652. destination[property] = sourceProperty.clone();
  4653. break;
  4654. }
  4655. }
  4656. }
  4657. return destination;
  4658. };
  4659. return SerializationHelper;
  4660. }());
  4661. BABYLON.SerializationHelper = SerializationHelper;
  4662. })(BABYLON || (BABYLON = {}));
  4663. //# sourceMappingURL=babylon.decorators.js.map
  4664. var BABYLON;
  4665. (function (BABYLON) {
  4666. /**
  4667. * A class serves as a medium between the observable and its observers
  4668. */
  4669. var EventState = (function () {
  4670. /**
  4671. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4672. */
  4673. function EventState(mask, skipNextObservers) {
  4674. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4675. this.initalize(mask, skipNextObservers);
  4676. }
  4677. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4678. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4679. this.mask = mask;
  4680. this.skipNextObservers = skipNextObservers;
  4681. return this;
  4682. };
  4683. return EventState;
  4684. }());
  4685. BABYLON.EventState = EventState;
  4686. /**
  4687. * Represent an Observer registered to a given Observable object.
  4688. */
  4689. var Observer = (function () {
  4690. function Observer(callback, mask) {
  4691. this.callback = callback;
  4692. this.mask = mask;
  4693. }
  4694. return Observer;
  4695. }());
  4696. BABYLON.Observer = Observer;
  4697. /**
  4698. * The Observable class is a simple implementation of the Observable pattern.
  4699. * 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.
  4700. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4701. * 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).
  4702. * 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.
  4703. */
  4704. var Observable = (function () {
  4705. function Observable() {
  4706. this._observers = new Array();
  4707. this._eventState = new EventState(0);
  4708. }
  4709. /**
  4710. * Create a new Observer with the specified callback
  4711. * @param callback the callback that will be executed for that Observer
  4712. * @param mask the mask used to filter observers
  4713. * @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.
  4714. */
  4715. Observable.prototype.add = function (callback, mask, insertFirst) {
  4716. if (mask === void 0) { mask = -1; }
  4717. if (insertFirst === void 0) { insertFirst = false; }
  4718. if (!callback) {
  4719. return null;
  4720. }
  4721. var observer = new Observer(callback, mask);
  4722. if (insertFirst) {
  4723. this._observers.unshift(observer);
  4724. }
  4725. else {
  4726. this._observers.push(observer);
  4727. }
  4728. return observer;
  4729. };
  4730. /**
  4731. * Remove an Observer from the Observable object
  4732. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4733. */
  4734. Observable.prototype.remove = function (observer) {
  4735. var index = this._observers.indexOf(observer);
  4736. if (index !== -1) {
  4737. this._observers.splice(index, 1);
  4738. return true;
  4739. }
  4740. return false;
  4741. };
  4742. /**
  4743. * Remove a callback from the Observable object
  4744. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4745. */
  4746. Observable.prototype.removeCallback = function (callback) {
  4747. for (var index = 0; index < this._observers.length; index++) {
  4748. if (this._observers[index].callback === callback) {
  4749. this._observers.splice(index, 1);
  4750. return true;
  4751. }
  4752. }
  4753. return false;
  4754. };
  4755. /**
  4756. * Notify all Observers by calling their respective callback with the given data
  4757. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4758. * @param eventData
  4759. * @param mask
  4760. */
  4761. Observable.prototype.notifyObservers = function (eventData, mask) {
  4762. if (mask === void 0) { mask = -1; }
  4763. var state = this._eventState;
  4764. state.mask = mask;
  4765. state.skipNextObservers = false;
  4766. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4767. var obs = _a[_i];
  4768. if (obs.mask & mask) {
  4769. obs.callback(eventData, state);
  4770. }
  4771. if (state.skipNextObservers) {
  4772. return false;
  4773. }
  4774. }
  4775. return true;
  4776. };
  4777. /**
  4778. * return true is the Observable has at least one Observer registered
  4779. */
  4780. Observable.prototype.hasObservers = function () {
  4781. return this._observers.length > 0;
  4782. };
  4783. /**
  4784. * Clear the list of observers
  4785. */
  4786. Observable.prototype.clear = function () {
  4787. this._observers = new Array();
  4788. };
  4789. /**
  4790. * Clone the current observable
  4791. */
  4792. Observable.prototype.clone = function () {
  4793. var result = new Observable();
  4794. result._observers = this._observers.slice(0);
  4795. return result;
  4796. };
  4797. return Observable;
  4798. }());
  4799. BABYLON.Observable = Observable;
  4800. })(BABYLON || (BABYLON = {}));
  4801. //# sourceMappingURL=babylon.observable.js.map
  4802. var BABYLON;
  4803. (function (BABYLON) {
  4804. var Database = (function () {
  4805. function Database(urlToScene, callbackManifestChecked) {
  4806. // Handling various flavors of prefixed version of IndexedDB
  4807. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4808. this.callbackManifestChecked = callbackManifestChecked;
  4809. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4810. this.db = null;
  4811. this.enableSceneOffline = false;
  4812. this.enableTexturesOffline = false;
  4813. this.manifestVersionFound = 0;
  4814. this.mustUpdateRessources = false;
  4815. this.hasReachedQuota = false;
  4816. if (!Database.IDBStorageEnabled) {
  4817. this.callbackManifestChecked(true);
  4818. }
  4819. else {
  4820. this.checkManifestFile();
  4821. }
  4822. }
  4823. Database.prototype.checkManifestFile = function () {
  4824. var _this = this;
  4825. function noManifestFile() {
  4826. that.enableSceneOffline = false;
  4827. that.enableTexturesOffline = false;
  4828. that.callbackManifestChecked(false);
  4829. }
  4830. var that = this;
  4831. var timeStampUsed = false;
  4832. var manifestURL = this.currentSceneUrl + ".manifest";
  4833. var xhr = new XMLHttpRequest();
  4834. if (navigator.onLine) {
  4835. // Adding a timestamp to by-pass browsers' cache
  4836. timeStampUsed = true;
  4837. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  4838. }
  4839. xhr.open("GET", manifestURL, true);
  4840. xhr.addEventListener("load", function () {
  4841. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  4842. try {
  4843. var manifestFile = JSON.parse(xhr.response);
  4844. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  4845. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  4846. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  4847. _this.manifestVersionFound = manifestFile.version;
  4848. }
  4849. if (_this.callbackManifestChecked) {
  4850. _this.callbackManifestChecked(true);
  4851. }
  4852. }
  4853. catch (ex) {
  4854. noManifestFile();
  4855. }
  4856. }
  4857. else {
  4858. noManifestFile();
  4859. }
  4860. }, false);
  4861. xhr.addEventListener("error", function (event) {
  4862. if (timeStampUsed) {
  4863. timeStampUsed = false;
  4864. // Let's retry without the timeStamp
  4865. // It could fail when coupled with HTML5 Offline API
  4866. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  4867. xhr.open("GET", retryManifestURL, true);
  4868. xhr.send();
  4869. }
  4870. else {
  4871. noManifestFile();
  4872. }
  4873. }, false);
  4874. try {
  4875. xhr.send();
  4876. }
  4877. catch (ex) {
  4878. BABYLON.Tools.Error("Error on XHR send request.");
  4879. that.callbackManifestChecked(false);
  4880. }
  4881. };
  4882. Database.prototype.openAsync = function (successCallback, errorCallback) {
  4883. var _this = this;
  4884. function handleError() {
  4885. that.isSupported = false;
  4886. if (errorCallback)
  4887. errorCallback();
  4888. }
  4889. var that = this;
  4890. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  4891. // Your browser doesn't support IndexedDB
  4892. this.isSupported = false;
  4893. if (errorCallback)
  4894. errorCallback();
  4895. }
  4896. else {
  4897. // If the DB hasn't been opened or created yet
  4898. if (!this.db) {
  4899. this.hasReachedQuota = false;
  4900. this.isSupported = true;
  4901. var request = this.idbFactory.open("babylonjs", 1);
  4902. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  4903. request.onerror = function (event) {
  4904. handleError();
  4905. };
  4906. // executes when a version change transaction cannot complete due to other active transactions
  4907. request.onblocked = function (event) {
  4908. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  4909. handleError();
  4910. };
  4911. // DB has been opened successfully
  4912. request.onsuccess = function (event) {
  4913. _this.db = request.result;
  4914. successCallback();
  4915. };
  4916. // Initialization of the DB. Creating Scenes & Textures stores
  4917. request.onupgradeneeded = function (event) {
  4918. _this.db = (event.target).result;
  4919. try {
  4920. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  4921. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  4922. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  4923. }
  4924. catch (ex) {
  4925. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  4926. handleError();
  4927. }
  4928. };
  4929. }
  4930. else {
  4931. if (successCallback)
  4932. successCallback();
  4933. }
  4934. }
  4935. };
  4936. Database.prototype.loadImageFromDB = function (url, image) {
  4937. var _this = this;
  4938. var completeURL = Database.ReturnFullUrlLocation(url);
  4939. var saveAndLoadImage = function () {
  4940. if (!_this.hasReachedQuota && _this.db !== null) {
  4941. // the texture is not yet in the DB, let's try to save it
  4942. _this._saveImageIntoDBAsync(completeURL, image);
  4943. }
  4944. else {
  4945. image.src = url;
  4946. }
  4947. };
  4948. if (!this.mustUpdateRessources) {
  4949. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  4950. }
  4951. else {
  4952. saveAndLoadImage();
  4953. }
  4954. };
  4955. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  4956. if (this.isSupported && this.db !== null) {
  4957. var texture;
  4958. var transaction = this.db.transaction(["textures"]);
  4959. transaction.onabort = function (event) {
  4960. image.src = url;
  4961. };
  4962. transaction.oncomplete = function (event) {
  4963. var blobTextureURL;
  4964. if (texture) {
  4965. var URL = window.URL || window.webkitURL;
  4966. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  4967. image.onerror = function () {
  4968. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  4969. image.src = url;
  4970. };
  4971. image.src = blobTextureURL;
  4972. }
  4973. else {
  4974. notInDBCallback();
  4975. }
  4976. };
  4977. var getRequest = transaction.objectStore("textures").get(url);
  4978. getRequest.onsuccess = function (event) {
  4979. texture = (event.target).result;
  4980. };
  4981. getRequest.onerror = function (event) {
  4982. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  4983. image.src = url;
  4984. };
  4985. }
  4986. else {
  4987. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4988. image.src = url;
  4989. }
  4990. };
  4991. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  4992. var _this = this;
  4993. if (this.isSupported) {
  4994. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  4995. var generateBlobUrl = function () {
  4996. var blobTextureURL;
  4997. if (blob) {
  4998. var URL = window.URL || window.webkitURL;
  4999. try {
  5000. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5001. }
  5002. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5003. catch (ex) {
  5004. blobTextureURL = URL.createObjectURL(blob);
  5005. }
  5006. }
  5007. image.src = blobTextureURL;
  5008. };
  5009. if (Database.IsUASupportingBlobStorage) {
  5010. var xhr = new XMLHttpRequest(), blob;
  5011. xhr.open("GET", url, true);
  5012. xhr.responseType = "blob";
  5013. xhr.addEventListener("load", function () {
  5014. if (xhr.status === 200) {
  5015. // Blob as response (XHR2)
  5016. blob = xhr.response;
  5017. var transaction = _this.db.transaction(["textures"], "readwrite");
  5018. // the transaction could abort because of a QuotaExceededError error
  5019. transaction.onabort = function (event) {
  5020. try {
  5021. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5022. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5023. _this.hasReachedQuota = true;
  5024. }
  5025. }
  5026. catch (ex) { }
  5027. generateBlobUrl();
  5028. };
  5029. transaction.oncomplete = function (event) {
  5030. generateBlobUrl();
  5031. };
  5032. var newTexture = { textureUrl: url, data: blob };
  5033. try {
  5034. // Put the blob into the dabase
  5035. var addRequest = transaction.objectStore("textures").put(newTexture);
  5036. addRequest.onsuccess = function (event) {
  5037. };
  5038. addRequest.onerror = function (event) {
  5039. generateBlobUrl();
  5040. };
  5041. }
  5042. catch (ex) {
  5043. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5044. if (ex.code === 25) {
  5045. Database.IsUASupportingBlobStorage = false;
  5046. }
  5047. image.src = url;
  5048. }
  5049. }
  5050. else {
  5051. image.src = url;
  5052. }
  5053. }, false);
  5054. xhr.addEventListener("error", function (event) {
  5055. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5056. image.src = url;
  5057. }, false);
  5058. xhr.send();
  5059. }
  5060. else {
  5061. image.src = url;
  5062. }
  5063. }
  5064. else {
  5065. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5066. image.src = url;
  5067. }
  5068. };
  5069. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5070. var _this = this;
  5071. var updateVersion = function (event) {
  5072. // the version is not yet in the DB or we need to update it
  5073. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5074. };
  5075. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5076. };
  5077. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5078. var _this = this;
  5079. if (this.isSupported) {
  5080. var version;
  5081. try {
  5082. var transaction = this.db.transaction(["versions"]);
  5083. transaction.oncomplete = function (event) {
  5084. if (version) {
  5085. // If the version in the JSON file is > than the version in DB
  5086. if (_this.manifestVersionFound > version.data) {
  5087. _this.mustUpdateRessources = true;
  5088. updateInDBCallback();
  5089. }
  5090. else {
  5091. callback(version.data);
  5092. }
  5093. }
  5094. else {
  5095. _this.mustUpdateRessources = true;
  5096. updateInDBCallback();
  5097. }
  5098. };
  5099. transaction.onabort = function (event) {
  5100. callback(-1);
  5101. };
  5102. var getRequest = transaction.objectStore("versions").get(url);
  5103. getRequest.onsuccess = function (event) {
  5104. version = (event.target).result;
  5105. };
  5106. getRequest.onerror = function (event) {
  5107. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5108. callback(-1);
  5109. };
  5110. }
  5111. catch (ex) {
  5112. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5113. callback(-1);
  5114. }
  5115. }
  5116. else {
  5117. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5118. callback(-1);
  5119. }
  5120. };
  5121. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5122. var _this = this;
  5123. if (this.isSupported && !this.hasReachedQuota) {
  5124. try {
  5125. // Open a transaction to the database
  5126. var transaction = this.db.transaction(["versions"], "readwrite");
  5127. // the transaction could abort because of a QuotaExceededError error
  5128. transaction.onabort = function (event) {
  5129. try {
  5130. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5131. _this.hasReachedQuota = true;
  5132. }
  5133. }
  5134. catch (ex) { }
  5135. callback(-1);
  5136. };
  5137. transaction.oncomplete = function (event) {
  5138. callback(_this.manifestVersionFound);
  5139. };
  5140. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5141. // Put the scene into the database
  5142. var addRequest = transaction.objectStore("versions").put(newVersion);
  5143. addRequest.onsuccess = function (event) {
  5144. };
  5145. addRequest.onerror = function (event) {
  5146. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5147. };
  5148. }
  5149. catch (ex) {
  5150. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5151. callback(-1);
  5152. }
  5153. }
  5154. else {
  5155. callback(-1);
  5156. }
  5157. };
  5158. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5159. var _this = this;
  5160. var completeUrl = Database.ReturnFullUrlLocation(url);
  5161. var saveAndLoadFile = function (event) {
  5162. // the scene is not yet in the DB, let's try to save it
  5163. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5164. };
  5165. this._checkVersionFromDB(completeUrl, function (version) {
  5166. if (version !== -1) {
  5167. if (!_this.mustUpdateRessources) {
  5168. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5169. }
  5170. else {
  5171. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5172. }
  5173. }
  5174. else {
  5175. errorCallback();
  5176. }
  5177. });
  5178. };
  5179. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5180. if (this.isSupported) {
  5181. var targetStore;
  5182. if (url.indexOf(".babylon") !== -1) {
  5183. targetStore = "scenes";
  5184. }
  5185. else {
  5186. targetStore = "textures";
  5187. }
  5188. var file;
  5189. var transaction = this.db.transaction([targetStore]);
  5190. transaction.oncomplete = function (event) {
  5191. if (file) {
  5192. callback(file.data);
  5193. }
  5194. else {
  5195. notInDBCallback();
  5196. }
  5197. };
  5198. transaction.onabort = function (event) {
  5199. notInDBCallback();
  5200. };
  5201. var getRequest = transaction.objectStore(targetStore).get(url);
  5202. getRequest.onsuccess = function (event) {
  5203. file = (event.target).result;
  5204. };
  5205. getRequest.onerror = function (event) {
  5206. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5207. notInDBCallback();
  5208. };
  5209. }
  5210. else {
  5211. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5212. callback();
  5213. }
  5214. };
  5215. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5216. var _this = this;
  5217. if (this.isSupported) {
  5218. var targetStore;
  5219. if (url.indexOf(".babylon") !== -1) {
  5220. targetStore = "scenes";
  5221. }
  5222. else {
  5223. targetStore = "textures";
  5224. }
  5225. // Create XHR
  5226. var xhr = new XMLHttpRequest(), fileData;
  5227. xhr.open("GET", url, true);
  5228. if (useArrayBuffer) {
  5229. xhr.responseType = "arraybuffer";
  5230. }
  5231. xhr.onprogress = progressCallback;
  5232. xhr.addEventListener("load", function () {
  5233. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5234. // Blob as response (XHR2)
  5235. //fileData = xhr.responseText;
  5236. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5237. if (!_this.hasReachedQuota) {
  5238. // Open a transaction to the database
  5239. var transaction = _this.db.transaction([targetStore], "readwrite");
  5240. // the transaction could abort because of a QuotaExceededError error
  5241. transaction.onabort = function (event) {
  5242. try {
  5243. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5244. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5245. _this.hasReachedQuota = true;
  5246. }
  5247. }
  5248. catch (ex) { }
  5249. callback(fileData);
  5250. };
  5251. transaction.oncomplete = function (event) {
  5252. callback(fileData);
  5253. };
  5254. var newFile;
  5255. if (targetStore === "scenes") {
  5256. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5257. }
  5258. else {
  5259. newFile = { textureUrl: url, data: fileData };
  5260. }
  5261. try {
  5262. // Put the scene into the database
  5263. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5264. addRequest.onsuccess = function (event) {
  5265. };
  5266. addRequest.onerror = function (event) {
  5267. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5268. };
  5269. }
  5270. catch (ex) {
  5271. callback(fileData);
  5272. }
  5273. }
  5274. else {
  5275. callback(fileData);
  5276. }
  5277. }
  5278. else {
  5279. callback();
  5280. }
  5281. }, false);
  5282. xhr.addEventListener("error", function (event) {
  5283. BABYLON.Tools.Error("error on XHR request.");
  5284. callback();
  5285. }, false);
  5286. xhr.send();
  5287. }
  5288. else {
  5289. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5290. callback();
  5291. }
  5292. };
  5293. return Database;
  5294. }());
  5295. Database.IsUASupportingBlobStorage = true;
  5296. Database.IDBStorageEnabled = true;
  5297. Database.parseURL = function (url) {
  5298. var a = document.createElement('a');
  5299. a.href = url;
  5300. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5301. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5302. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5303. return absLocation;
  5304. };
  5305. Database.ReturnFullUrlLocation = function (url) {
  5306. if (url.indexOf("http:/") === -1) {
  5307. return (Database.parseURL(window.location.href) + url);
  5308. }
  5309. else {
  5310. return url;
  5311. }
  5312. };
  5313. BABYLON.Database = Database;
  5314. })(BABYLON || (BABYLON = {}));
  5315. //# sourceMappingURL=babylon.database.js.map
  5316. var BABYLON;
  5317. (function (BABYLON) {
  5318. var Internals;
  5319. (function (Internals) {
  5320. /*
  5321. * Based on jsTGALoader - Javascript loader for TGA file
  5322. * By Vincent Thibault
  5323. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5324. */
  5325. var TGATools = (function () {
  5326. function TGATools() {
  5327. }
  5328. TGATools.GetTGAHeader = function (data) {
  5329. var offset = 0;
  5330. var header = {
  5331. id_length: data[offset++],
  5332. colormap_type: data[offset++],
  5333. image_type: data[offset++],
  5334. colormap_index: data[offset++] | data[offset++] << 8,
  5335. colormap_length: data[offset++] | data[offset++] << 8,
  5336. colormap_size: data[offset++],
  5337. origin: [
  5338. data[offset++] | data[offset++] << 8,
  5339. data[offset++] | data[offset++] << 8
  5340. ],
  5341. width: data[offset++] | data[offset++] << 8,
  5342. height: data[offset++] | data[offset++] << 8,
  5343. pixel_size: data[offset++],
  5344. flags: data[offset++]
  5345. };
  5346. return header;
  5347. };
  5348. TGATools.UploadContent = function (gl, data) {
  5349. // Not enough data to contain header ?
  5350. if (data.length < 19) {
  5351. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5352. return;
  5353. }
  5354. // Read Header
  5355. var offset = 18;
  5356. var header = TGATools.GetTGAHeader(data);
  5357. // Assume it's a valid Targa file.
  5358. if (header.id_length + offset > data.length) {
  5359. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5360. return;
  5361. }
  5362. // Skip not needed data
  5363. offset += header.id_length;
  5364. var use_rle = false;
  5365. var use_pal = false;
  5366. var use_rgb = false;
  5367. var use_grey = false;
  5368. // Get some informations.
  5369. switch (header.image_type) {
  5370. case TGATools._TYPE_RLE_INDEXED:
  5371. use_rle = true;
  5372. case TGATools._TYPE_INDEXED:
  5373. use_pal = true;
  5374. break;
  5375. case TGATools._TYPE_RLE_RGB:
  5376. use_rle = true;
  5377. case TGATools._TYPE_RGB:
  5378. use_rgb = true;
  5379. break;
  5380. case TGATools._TYPE_RLE_GREY:
  5381. use_rle = true;
  5382. case TGATools._TYPE_GREY:
  5383. use_grey = true;
  5384. break;
  5385. }
  5386. var pixel_data;
  5387. var numAlphaBits = header.flags & 0xf;
  5388. var pixel_size = header.pixel_size >> 3;
  5389. var pixel_total = header.width * header.height * pixel_size;
  5390. // Read palettes
  5391. var palettes;
  5392. if (use_pal) {
  5393. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5394. }
  5395. // Read LRE
  5396. if (use_rle) {
  5397. pixel_data = new Uint8Array(pixel_total);
  5398. var c, count, i;
  5399. var localOffset = 0;
  5400. var pixels = new Uint8Array(pixel_size);
  5401. while (offset < pixel_total && localOffset < pixel_total) {
  5402. c = data[offset++];
  5403. count = (c & 0x7f) + 1;
  5404. // RLE pixels
  5405. if (c & 0x80) {
  5406. // Bind pixel tmp array
  5407. for (i = 0; i < pixel_size; ++i) {
  5408. pixels[i] = data[offset++];
  5409. }
  5410. // Copy pixel array
  5411. for (i = 0; i < count; ++i) {
  5412. pixel_data.set(pixels, localOffset + i * pixel_size);
  5413. }
  5414. localOffset += pixel_size * count;
  5415. }
  5416. else {
  5417. count *= pixel_size;
  5418. for (i = 0; i < count; ++i) {
  5419. pixel_data[localOffset + i] = data[offset++];
  5420. }
  5421. localOffset += count;
  5422. }
  5423. }
  5424. }
  5425. else {
  5426. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5427. }
  5428. // Load to texture
  5429. var x_start, y_start, x_step, y_step, y_end, x_end;
  5430. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5431. default:
  5432. case TGATools._ORIGIN_UL:
  5433. x_start = 0;
  5434. x_step = 1;
  5435. x_end = header.width;
  5436. y_start = 0;
  5437. y_step = 1;
  5438. y_end = header.height;
  5439. break;
  5440. case TGATools._ORIGIN_BL:
  5441. x_start = 0;
  5442. x_step = 1;
  5443. x_end = header.width;
  5444. y_start = header.height - 1;
  5445. y_step = -1;
  5446. y_end = -1;
  5447. break;
  5448. case TGATools._ORIGIN_UR:
  5449. x_start = header.width - 1;
  5450. x_step = -1;
  5451. x_end = -1;
  5452. y_start = 0;
  5453. y_step = 1;
  5454. y_end = header.height;
  5455. break;
  5456. case TGATools._ORIGIN_BR:
  5457. x_start = header.width - 1;
  5458. x_step = -1;
  5459. x_end = -1;
  5460. y_start = header.height - 1;
  5461. y_step = -1;
  5462. y_end = -1;
  5463. break;
  5464. }
  5465. // Load the specify method
  5466. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5467. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5468. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5469. };
  5470. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5471. var image = pixel_data, colormap = palettes;
  5472. var width = header.width, height = header.height;
  5473. var color, i = 0, x, y;
  5474. var imageData = new Uint8Array(width * height * 4);
  5475. for (y = y_start; y !== y_end; y += y_step) {
  5476. for (x = x_start; x !== x_end; x += x_step, i++) {
  5477. color = image[i];
  5478. imageData[(x + width * y) * 4 + 3] = 255;
  5479. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5480. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5481. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5482. }
  5483. }
  5484. return imageData;
  5485. };
  5486. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5487. var image = pixel_data;
  5488. var width = header.width, height = header.height;
  5489. var color, i = 0, x, y;
  5490. var imageData = new Uint8Array(width * height * 4);
  5491. for (y = y_start; y !== y_end; y += y_step) {
  5492. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5493. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5494. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5495. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5496. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5497. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5498. }
  5499. }
  5500. return imageData;
  5501. };
  5502. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5503. var image = pixel_data;
  5504. var width = header.width, height = header.height;
  5505. var i = 0, x, y;
  5506. var imageData = new Uint8Array(width * height * 4);
  5507. for (y = y_start; y !== y_end; y += y_step) {
  5508. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5509. imageData[(x + width * y) * 4 + 3] = 255;
  5510. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5511. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5512. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5513. }
  5514. }
  5515. return imageData;
  5516. };
  5517. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5518. var image = pixel_data;
  5519. var width = header.width, height = header.height;
  5520. var i = 0, x, y;
  5521. var imageData = new Uint8Array(width * height * 4);
  5522. for (y = y_start; y !== y_end; y += y_step) {
  5523. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5524. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5525. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5526. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5527. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5528. }
  5529. }
  5530. return imageData;
  5531. };
  5532. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5533. var image = pixel_data;
  5534. var width = header.width, height = header.height;
  5535. var color, i = 0, x, y;
  5536. var imageData = new Uint8Array(width * height * 4);
  5537. for (y = y_start; y !== y_end; y += y_step) {
  5538. for (x = x_start; x !== x_end; x += x_step, i++) {
  5539. color = image[i];
  5540. imageData[(x + width * y) * 4 + 0] = color;
  5541. imageData[(x + width * y) * 4 + 1] = color;
  5542. imageData[(x + width * y) * 4 + 2] = color;
  5543. imageData[(x + width * y) * 4 + 3] = 255;
  5544. }
  5545. }
  5546. return imageData;
  5547. };
  5548. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5549. var image = pixel_data;
  5550. var width = header.width, height = header.height;
  5551. var i = 0, x, y;
  5552. var imageData = new Uint8Array(width * height * 4);
  5553. for (y = y_start; y !== y_end; y += y_step) {
  5554. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5555. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5556. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5557. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5558. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5559. }
  5560. }
  5561. return imageData;
  5562. };
  5563. return TGATools;
  5564. }());
  5565. TGATools._TYPE_NO_DATA = 0;
  5566. TGATools._TYPE_INDEXED = 1;
  5567. TGATools._TYPE_RGB = 2;
  5568. TGATools._TYPE_GREY = 3;
  5569. TGATools._TYPE_RLE_INDEXED = 9;
  5570. TGATools._TYPE_RLE_RGB = 10;
  5571. TGATools._TYPE_RLE_GREY = 11;
  5572. TGATools._ORIGIN_MASK = 0x30;
  5573. TGATools._ORIGIN_SHIFT = 0x04;
  5574. TGATools._ORIGIN_BL = 0x00;
  5575. TGATools._ORIGIN_BR = 0x01;
  5576. TGATools._ORIGIN_UL = 0x02;
  5577. TGATools._ORIGIN_UR = 0x03;
  5578. Internals.TGATools = TGATools;
  5579. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5580. })(BABYLON || (BABYLON = {}));
  5581. //# sourceMappingURL=babylon.tools.tga.js.map
  5582. var BABYLON;
  5583. (function (BABYLON) {
  5584. var SmartArray = (function () {
  5585. function SmartArray(capacity) {
  5586. this.length = 0;
  5587. this._duplicateId = 0;
  5588. this.data = new Array(capacity);
  5589. this._id = SmartArray._GlobalId++;
  5590. }
  5591. SmartArray.prototype.push = function (value) {
  5592. this.data[this.length++] = value;
  5593. if (this.length > this.data.length) {
  5594. this.data.length *= 2;
  5595. }
  5596. if (!value.__smartArrayFlags) {
  5597. value.__smartArrayFlags = {};
  5598. }
  5599. value.__smartArrayFlags[this._id] = this._duplicateId;
  5600. };
  5601. SmartArray.prototype.pushNoDuplicate = function (value) {
  5602. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5603. return false;
  5604. }
  5605. this.push(value);
  5606. return true;
  5607. };
  5608. SmartArray.prototype.sort = function (compareFn) {
  5609. this.data.sort(compareFn);
  5610. };
  5611. SmartArray.prototype.reset = function () {
  5612. this.length = 0;
  5613. this._duplicateId++;
  5614. };
  5615. SmartArray.prototype.concat = function (array) {
  5616. if (array.length === 0) {
  5617. return;
  5618. }
  5619. if (this.length + array.length > this.data.length) {
  5620. this.data.length = (this.length + array.length) * 2;
  5621. }
  5622. for (var index = 0; index < array.length; index++) {
  5623. this.data[this.length++] = (array.data || array)[index];
  5624. }
  5625. };
  5626. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5627. if (array.length === 0) {
  5628. return;
  5629. }
  5630. if (this.length + array.length > this.data.length) {
  5631. this.data.length = (this.length + array.length) * 2;
  5632. }
  5633. for (var index = 0; index < array.length; index++) {
  5634. var item = (array.data || array)[index];
  5635. this.pushNoDuplicate(item);
  5636. }
  5637. };
  5638. SmartArray.prototype.indexOf = function (value) {
  5639. var position = this.data.indexOf(value);
  5640. if (position >= this.length) {
  5641. return -1;
  5642. }
  5643. return position;
  5644. };
  5645. return SmartArray;
  5646. }());
  5647. // Statics
  5648. SmartArray._GlobalId = 0;
  5649. BABYLON.SmartArray = SmartArray;
  5650. })(BABYLON || (BABYLON = {}));
  5651. //# sourceMappingURL=babylon.smartArray.js.map
  5652. var BABYLON;
  5653. (function (BABYLON) {
  5654. /**
  5655. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5656. * The underlying implementation relies on an associative array to ensure the best performances.
  5657. * The value can be anything including 'null' but except 'undefined'
  5658. */
  5659. var StringDictionary = (function () {
  5660. function StringDictionary() {
  5661. this._count = 0;
  5662. this._data = {};
  5663. }
  5664. /**
  5665. * This will clear this dictionary and copy the content from the 'source' one.
  5666. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5667. * @param source the dictionary to take the content from and copy to this dictionary
  5668. */
  5669. StringDictionary.prototype.copyFrom = function (source) {
  5670. var _this = this;
  5671. this.clear();
  5672. source.forEach(function (t, v) { return _this.add(t, v); });
  5673. };
  5674. /**
  5675. * Get a value based from its key
  5676. * @param key the given key to get the matching value from
  5677. * @return the value if found, otherwise undefined is returned
  5678. */
  5679. StringDictionary.prototype.get = function (key) {
  5680. var val = this._data[key];
  5681. if (val !== undefined) {
  5682. return val;
  5683. }
  5684. return undefined;
  5685. };
  5686. /**
  5687. * Get a value from its key or add it if it doesn't exist.
  5688. * This method will ensure you that a given key/data will be present in the dictionary.
  5689. * @param key the given key to get the matching value from
  5690. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5691. * The factory will only be invoked if there's no data for the given key.
  5692. * @return the value corresponding to the key.
  5693. */
  5694. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5695. var val = this.get(key);
  5696. if (val !== undefined) {
  5697. return val;
  5698. }
  5699. val = factory(key);
  5700. if (val) {
  5701. this.add(key, val);
  5702. }
  5703. return val;
  5704. };
  5705. /**
  5706. * Get a value from its key if present in the dictionary otherwise add it
  5707. * @param key the key to get the value from
  5708. * @param val if there's no such key/value pair in the dictionary add it with this value
  5709. * @return the value corresponding to the key
  5710. */
  5711. StringDictionary.prototype.getOrAdd = function (key, val) {
  5712. var curVal = this.get(key);
  5713. if (curVal !== undefined) {
  5714. return curVal;
  5715. }
  5716. this.add(key, val);
  5717. return val;
  5718. };
  5719. /**
  5720. * Check if there's a given key in the dictionary
  5721. * @param key the key to check for
  5722. * @return true if the key is present, false otherwise
  5723. */
  5724. StringDictionary.prototype.contains = function (key) {
  5725. return this._data[key] !== undefined;
  5726. };
  5727. /**
  5728. * Add a new key and its corresponding value
  5729. * @param key the key to add
  5730. * @param value the value corresponding to the key
  5731. * @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
  5732. */
  5733. StringDictionary.prototype.add = function (key, value) {
  5734. if (this._data[key] !== undefined) {
  5735. return false;
  5736. }
  5737. this._data[key] = value;
  5738. ++this._count;
  5739. return true;
  5740. };
  5741. StringDictionary.prototype.set = function (key, value) {
  5742. if (this._data[key] === undefined) {
  5743. return false;
  5744. }
  5745. this._data[key] = value;
  5746. return true;
  5747. };
  5748. /**
  5749. * Get the element of the given key and remove it from the dictionary
  5750. * @param key
  5751. */
  5752. StringDictionary.prototype.getAndRemove = function (key) {
  5753. var val = this.get(key);
  5754. if (val !== undefined) {
  5755. delete this._data[key];
  5756. --this._count;
  5757. return val;
  5758. }
  5759. return null;
  5760. };
  5761. /**
  5762. * Remove a key/value from the dictionary.
  5763. * @param key the key to remove
  5764. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5765. */
  5766. StringDictionary.prototype.remove = function (key) {
  5767. if (this.contains(key)) {
  5768. delete this._data[key];
  5769. --this._count;
  5770. return true;
  5771. }
  5772. return false;
  5773. };
  5774. /**
  5775. * Clear the whole content of the dictionary
  5776. */
  5777. StringDictionary.prototype.clear = function () {
  5778. this._data = {};
  5779. this._count = 0;
  5780. };
  5781. Object.defineProperty(StringDictionary.prototype, "count", {
  5782. get: function () {
  5783. return this._count;
  5784. },
  5785. enumerable: true,
  5786. configurable: true
  5787. });
  5788. /**
  5789. * Execute a callback on each key/val of the dictionary.
  5790. * Note that you can remove any element in this dictionary in the callback implementation
  5791. * @param callback the callback to execute on a given key/value pair
  5792. */
  5793. StringDictionary.prototype.forEach = function (callback) {
  5794. for (var cur in this._data) {
  5795. var val = this._data[cur];
  5796. callback(cur, val);
  5797. }
  5798. };
  5799. /**
  5800. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5801. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5802. * Note that you can remove any element in this dictionary in the callback implementation
  5803. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5804. */
  5805. StringDictionary.prototype.first = function (callback) {
  5806. for (var cur in this._data) {
  5807. var val = this._data[cur];
  5808. var res = callback(cur, val);
  5809. if (res) {
  5810. return res;
  5811. }
  5812. }
  5813. return null;
  5814. };
  5815. return StringDictionary;
  5816. }());
  5817. BABYLON.StringDictionary = StringDictionary;
  5818. })(BABYLON || (BABYLON = {}));
  5819. //# sourceMappingURL=babylon.stringDictionary.js.map
  5820. var BABYLON;
  5821. (function (BABYLON) {
  5822. // Screenshots
  5823. var screenshotCanvas;
  5824. var cloneValue = function (source, destinationObject) {
  5825. if (!source)
  5826. return null;
  5827. if (source instanceof BABYLON.Mesh) {
  5828. return null;
  5829. }
  5830. if (source instanceof BABYLON.SubMesh) {
  5831. return source.clone(destinationObject);
  5832. }
  5833. else if (source.clone) {
  5834. return source.clone();
  5835. }
  5836. return null;
  5837. };
  5838. var Tools = (function () {
  5839. function Tools() {
  5840. }
  5841. ;
  5842. Tools.Instantiate = function (className) {
  5843. var arr = className.split(".");
  5844. var fn = (window || this);
  5845. for (var i = 0, len = arr.length; i < len; i++) {
  5846. fn = fn[arr[i]];
  5847. }
  5848. if (typeof fn !== "function") {
  5849. return null;
  5850. }
  5851. return fn;
  5852. };
  5853. Tools.SetImmediate = function (action) {
  5854. if (window.setImmediate) {
  5855. window.setImmediate(action);
  5856. }
  5857. else {
  5858. setTimeout(action, 1);
  5859. }
  5860. };
  5861. Tools.IsExponentOfTwo = function (value) {
  5862. var count = 1;
  5863. do {
  5864. count *= 2;
  5865. } while (count < value);
  5866. return count === value;
  5867. };
  5868. Tools.GetExponentOfTwo = function (value, max) {
  5869. var count = 1;
  5870. do {
  5871. count *= 2;
  5872. } while (count < value);
  5873. if (count > max)
  5874. count = max;
  5875. return count;
  5876. };
  5877. Tools.GetFilename = function (path) {
  5878. var index = path.lastIndexOf("/");
  5879. if (index < 0)
  5880. return path;
  5881. return path.substring(index + 1);
  5882. };
  5883. Tools.GetDOMTextContent = function (element) {
  5884. var result = "";
  5885. var child = element.firstChild;
  5886. while (child) {
  5887. if (child.nodeType === 3) {
  5888. result += child.textContent;
  5889. }
  5890. child = child.nextSibling;
  5891. }
  5892. return result;
  5893. };
  5894. Tools.ToDegrees = function (angle) {
  5895. return angle * 180 / Math.PI;
  5896. };
  5897. Tools.ToRadians = function (angle) {
  5898. return angle * Math.PI / 180;
  5899. };
  5900. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5901. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5902. var output = "";
  5903. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5904. var i = 0;
  5905. var bytes = new Uint8Array(buffer);
  5906. while (i < bytes.length) {
  5907. chr1 = bytes[i++];
  5908. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5909. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5910. enc1 = chr1 >> 2;
  5911. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5912. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5913. enc4 = chr3 & 63;
  5914. if (isNaN(chr2)) {
  5915. enc3 = enc4 = 64;
  5916. }
  5917. else if (isNaN(chr3)) {
  5918. enc4 = 64;
  5919. }
  5920. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5921. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5922. }
  5923. return "data:image/png;base64," + output;
  5924. };
  5925. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5926. if (bias === void 0) { bias = null; }
  5927. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5928. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5929. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5930. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5931. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5932. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5933. }
  5934. if (bias) {
  5935. minimum.x -= minimum.x * bias.x + bias.y;
  5936. minimum.y -= minimum.y * bias.x + bias.y;
  5937. minimum.z -= minimum.z * bias.x + bias.y;
  5938. maximum.x += maximum.x * bias.x + bias.y;
  5939. maximum.y += maximum.y * bias.x + bias.y;
  5940. maximum.z += maximum.z * bias.x + bias.y;
  5941. }
  5942. return {
  5943. minimum: minimum,
  5944. maximum: maximum
  5945. };
  5946. };
  5947. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5948. if (bias === void 0) { bias = null; }
  5949. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5950. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5951. if (!stride) {
  5952. stride = 3;
  5953. }
  5954. for (var index = start; index < start + count; index++) {
  5955. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5956. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5957. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5958. }
  5959. if (bias) {
  5960. minimum.x -= minimum.x * bias.x + bias.y;
  5961. minimum.y -= minimum.y * bias.x + bias.y;
  5962. minimum.z -= minimum.z * bias.x + bias.y;
  5963. maximum.x += maximum.x * bias.x + bias.y;
  5964. maximum.y += maximum.y * bias.x + bias.y;
  5965. maximum.z += maximum.z * bias.x + bias.y;
  5966. }
  5967. return {
  5968. minimum: minimum,
  5969. maximum: maximum
  5970. };
  5971. };
  5972. Tools.Vector2ArrayFeeder = function (array) {
  5973. return function (index) {
  5974. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5975. var length = isFloatArray ? array.length / 2 : array.length;
  5976. if (index >= length) {
  5977. return null;
  5978. }
  5979. if (isFloatArray) {
  5980. var fa = array;
  5981. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5982. }
  5983. var a = array;
  5984. return a[index];
  5985. };
  5986. };
  5987. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5988. if (bias === void 0) { bias = null; }
  5989. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5990. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5991. var i = 0;
  5992. var cur = feeder(i++);
  5993. while (cur) {
  5994. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5995. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5996. cur = feeder(i++);
  5997. }
  5998. if (bias) {
  5999. minimum.x -= minimum.x * bias.x + bias.y;
  6000. minimum.y -= minimum.y * bias.x + bias.y;
  6001. maximum.x += maximum.x * bias.x + bias.y;
  6002. maximum.y += maximum.y * bias.x + bias.y;
  6003. }
  6004. return {
  6005. minimum: minimum,
  6006. maximum: maximum
  6007. };
  6008. };
  6009. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6010. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6011. return undefined;
  6012. return Array.isArray(obj) ? obj : [obj];
  6013. };
  6014. // Misc.
  6015. Tools.GetPointerPrefix = function () {
  6016. var eventPrefix = "pointer";
  6017. // Check if pointer events are supported
  6018. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6019. eventPrefix = "mouse";
  6020. }
  6021. return eventPrefix;
  6022. };
  6023. /**
  6024. * @param func - the function to be called
  6025. * @param requester - the object that will request the next frame. Falls back to window.
  6026. */
  6027. Tools.QueueNewFrame = function (func, requester) {
  6028. if (requester === void 0) { requester = window; }
  6029. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6030. /*if(requester.isPresenting) {
  6031. return;
  6032. } else*/ if (requester.requestAnimationFrame)
  6033. requester.requestAnimationFrame(func);
  6034. else if (requester.msRequestAnimationFrame)
  6035. requester.msRequestAnimationFrame(func);
  6036. else if (requester.webkitRequestAnimationFrame)
  6037. requester.webkitRequestAnimationFrame(func);
  6038. else if (requester.mozRequestAnimationFrame)
  6039. requester.mozRequestAnimationFrame(func);
  6040. else if (requester.oRequestAnimationFrame)
  6041. requester.oRequestAnimationFrame(func);
  6042. else {
  6043. window.setTimeout(func, 16);
  6044. }
  6045. };
  6046. Tools.RequestFullscreen = function (element) {
  6047. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6048. if (!requestFunction)
  6049. return;
  6050. requestFunction.call(element);
  6051. };
  6052. Tools.ExitFullscreen = function () {
  6053. if (document.exitFullscreen) {
  6054. document.exitFullscreen();
  6055. }
  6056. else if (document.mozCancelFullScreen) {
  6057. document.mozCancelFullScreen();
  6058. }
  6059. else if (document.webkitCancelFullScreen) {
  6060. document.webkitCancelFullScreen();
  6061. }
  6062. else if (document.msCancelFullScreen) {
  6063. document.msCancelFullScreen();
  6064. }
  6065. };
  6066. Tools.SetCorsBehavior = function (url, img) {
  6067. if (Tools.CorsBehavior) {
  6068. switch (typeof (Tools.CorsBehavior)) {
  6069. case "function":
  6070. var result = Tools.CorsBehavior(url);
  6071. if (result) {
  6072. return result;
  6073. }
  6074. break;
  6075. case "string":
  6076. default:
  6077. img.crossOrigin = Tools.CorsBehavior;
  6078. break;
  6079. }
  6080. }
  6081. };
  6082. // External files
  6083. Tools.CleanUrl = function (url) {
  6084. url = url.replace(/#/mg, "%23");
  6085. return url;
  6086. };
  6087. Tools.LoadImage = function (url, onload, onerror, database) {
  6088. if (url instanceof ArrayBuffer) {
  6089. url = Tools.EncodeArrayBufferTobase64(url);
  6090. }
  6091. url = Tools.CleanUrl(url);
  6092. var img = new Image();
  6093. if (url.substr(0, 5) !== "data:") {
  6094. Tools.SetCorsBehavior(url, img);
  6095. }
  6096. img.onload = function () {
  6097. onload(img);
  6098. };
  6099. img.onerror = function (err) {
  6100. Tools.Error("Error while trying to load image: " + url);
  6101. if (Tools.UseFallbackTexture) {
  6102. img.src = Tools.fallbackTexture;
  6103. onload(img);
  6104. }
  6105. else {
  6106. onerror();
  6107. }
  6108. };
  6109. var noIndexedDB = function () {
  6110. img.src = url;
  6111. };
  6112. var loadFromIndexedDB = function () {
  6113. database.loadImageFromDB(url, img);
  6114. };
  6115. //ANY database to do!
  6116. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6117. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6118. }
  6119. else {
  6120. if (url.indexOf("file:") === -1) {
  6121. noIndexedDB();
  6122. }
  6123. else {
  6124. var textureName = url.substring(5).toLowerCase();
  6125. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6126. try {
  6127. var blobURL;
  6128. try {
  6129. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6130. }
  6131. catch (ex) {
  6132. // Chrome doesn't support oneTimeOnly parameter
  6133. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6134. }
  6135. img.src = blobURL;
  6136. }
  6137. catch (e) {
  6138. img.src = null;
  6139. }
  6140. }
  6141. else {
  6142. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6143. img.src = Tools.fallbackTexture;
  6144. }
  6145. }
  6146. }
  6147. return img;
  6148. };
  6149. //ANY
  6150. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6151. url = Tools.CleanUrl(url);
  6152. var noIndexedDB = function () {
  6153. var request = new XMLHttpRequest();
  6154. var loadUrl = Tools.BaseUrl + url;
  6155. request.open('GET', loadUrl, true);
  6156. if (useArrayBuffer) {
  6157. request.responseType = "arraybuffer";
  6158. }
  6159. request.onprogress = progressCallBack;
  6160. request.onreadystatechange = function () {
  6161. if (request.readyState === 4) {
  6162. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6163. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6164. callback(!useArrayBuffer ? request.responseText : request.response);
  6165. }
  6166. else {
  6167. if (onError) {
  6168. onError();
  6169. }
  6170. else {
  6171. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6172. }
  6173. }
  6174. }
  6175. };
  6176. request.send(null);
  6177. };
  6178. var loadFromIndexedDB = function () {
  6179. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6180. };
  6181. if (url.indexOf("file:") !== -1) {
  6182. var fileName = url.substring(5).toLowerCase();
  6183. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6184. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6185. }
  6186. else {
  6187. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6188. }
  6189. }
  6190. else {
  6191. // Caching all files
  6192. if (database && database.enableSceneOffline) {
  6193. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6194. }
  6195. else {
  6196. noIndexedDB();
  6197. }
  6198. }
  6199. };
  6200. /**
  6201. * Load a script (identified by an url). When the url returns, the
  6202. * content of this file is added into a new script element, attached to the DOM (body element)
  6203. */
  6204. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6205. var head = document.getElementsByTagName('head')[0];
  6206. var script = document.createElement('script');
  6207. script.type = 'text/javascript';
  6208. script.src = scriptUrl;
  6209. var self = this;
  6210. script.onload = function () {
  6211. if (onSuccess) {
  6212. onSuccess();
  6213. }
  6214. };
  6215. script.onerror = function () {
  6216. if (onError) {
  6217. onError();
  6218. }
  6219. };
  6220. head.appendChild(script);
  6221. };
  6222. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6223. var reader = new FileReader();
  6224. reader.onload = function (e) {
  6225. //target doesn't have result from ts 1.3
  6226. callback(e.target['result']);
  6227. };
  6228. reader.onprogress = progressCallback;
  6229. reader.readAsDataURL(fileToLoad);
  6230. };
  6231. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6232. var reader = new FileReader();
  6233. reader.onerror = function (e) {
  6234. Tools.Log("Error while reading file: " + fileToLoad.name);
  6235. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6236. };
  6237. reader.onload = function (e) {
  6238. //target doesn't have result from ts 1.3
  6239. callback(e.target['result']);
  6240. };
  6241. reader.onprogress = progressCallBack;
  6242. if (!useArrayBuffer) {
  6243. // Asynchronous read
  6244. reader.readAsText(fileToLoad);
  6245. }
  6246. else {
  6247. reader.readAsArrayBuffer(fileToLoad);
  6248. }
  6249. };
  6250. //returns a downloadable url to a file content.
  6251. Tools.FileAsURL = function (content) {
  6252. var fileBlob = new Blob([content]);
  6253. var url = window.URL || window.webkitURL;
  6254. var link = url.createObjectURL(fileBlob);
  6255. return link;
  6256. };
  6257. // Misc.
  6258. Tools.Format = function (value, decimals) {
  6259. if (decimals === void 0) { decimals = 2; }
  6260. return value.toFixed(decimals);
  6261. };
  6262. Tools.CheckExtends = function (v, min, max) {
  6263. if (v.x < min.x)
  6264. min.x = v.x;
  6265. if (v.y < min.y)
  6266. min.y = v.y;
  6267. if (v.z < min.z)
  6268. min.z = v.z;
  6269. if (v.x > max.x)
  6270. max.x = v.x;
  6271. if (v.y > max.y)
  6272. max.y = v.y;
  6273. if (v.z > max.z)
  6274. max.z = v.z;
  6275. };
  6276. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6277. for (var prop in source) {
  6278. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6279. continue;
  6280. }
  6281. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6282. continue;
  6283. }
  6284. var sourceValue = source[prop];
  6285. var typeOfSourceValue = typeof sourceValue;
  6286. if (typeOfSourceValue === "function") {
  6287. continue;
  6288. }
  6289. if (typeOfSourceValue === "object") {
  6290. if (sourceValue instanceof Array) {
  6291. destination[prop] = [];
  6292. if (sourceValue.length > 0) {
  6293. if (typeof sourceValue[0] == "object") {
  6294. for (var index = 0; index < sourceValue.length; index++) {
  6295. var clonedValue = cloneValue(sourceValue[index], destination);
  6296. if (destination[prop].indexOf(clonedValue) === -1) {
  6297. destination[prop].push(clonedValue);
  6298. }
  6299. }
  6300. }
  6301. else {
  6302. destination[prop] = sourceValue.slice(0);
  6303. }
  6304. }
  6305. }
  6306. else {
  6307. destination[prop] = cloneValue(sourceValue, destination);
  6308. }
  6309. }
  6310. else {
  6311. destination[prop] = sourceValue;
  6312. }
  6313. }
  6314. };
  6315. Tools.IsEmpty = function (obj) {
  6316. for (var i in obj) {
  6317. return false;
  6318. }
  6319. return true;
  6320. };
  6321. Tools.RegisterTopRootEvents = function (events) {
  6322. for (var index = 0; index < events.length; index++) {
  6323. var event = events[index];
  6324. window.addEventListener(event.name, event.handler, false);
  6325. try {
  6326. if (window.parent) {
  6327. window.parent.addEventListener(event.name, event.handler, false);
  6328. }
  6329. }
  6330. catch (e) {
  6331. }
  6332. }
  6333. };
  6334. Tools.UnregisterTopRootEvents = function (events) {
  6335. for (var index = 0; index < events.length; index++) {
  6336. var event = events[index];
  6337. window.removeEventListener(event.name, event.handler);
  6338. try {
  6339. if (window.parent) {
  6340. window.parent.removeEventListener(event.name, event.handler);
  6341. }
  6342. }
  6343. catch (e) {
  6344. }
  6345. }
  6346. };
  6347. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6348. if (mimeType === void 0) { mimeType = "image/png"; }
  6349. // Read the contents of the framebuffer
  6350. var numberOfChannelsByLine = width * 4;
  6351. var halfHeight = height / 2;
  6352. //Reading datas from WebGL
  6353. var data = engine.readPixels(0, 0, width, height);
  6354. //To flip image on Y axis.
  6355. for (var i = 0; i < halfHeight; i++) {
  6356. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6357. var currentCell = j + i * numberOfChannelsByLine;
  6358. var targetLine = height - i - 1;
  6359. var targetCell = j + targetLine * numberOfChannelsByLine;
  6360. var temp = data[currentCell];
  6361. data[currentCell] = data[targetCell];
  6362. data[targetCell] = temp;
  6363. }
  6364. }
  6365. // Create a 2D canvas to store the result
  6366. if (!screenshotCanvas) {
  6367. screenshotCanvas = document.createElement('canvas');
  6368. }
  6369. screenshotCanvas.width = width;
  6370. screenshotCanvas.height = height;
  6371. var context = screenshotCanvas.getContext('2d');
  6372. // Copy the pixels to a 2D canvas
  6373. var imageData = context.createImageData(width, height);
  6374. var castData = (imageData.data);
  6375. castData.set(data);
  6376. context.putImageData(imageData, 0, 0);
  6377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6378. };
  6379. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6380. if (mimeType === void 0) { mimeType = "image/png"; }
  6381. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6382. if (successCallback) {
  6383. successCallback(base64Image);
  6384. }
  6385. else {
  6386. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6387. if (("download" in document.createElement("a"))) {
  6388. var a = window.document.createElement("a");
  6389. a.href = base64Image;
  6390. var date = new Date();
  6391. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6392. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6393. window.document.body.appendChild(a);
  6394. a.addEventListener("click", function () {
  6395. a.parentElement.removeChild(a);
  6396. });
  6397. a.click();
  6398. }
  6399. else {
  6400. var newWindow = window.open("");
  6401. var img = newWindow.document.createElement("img");
  6402. img.src = base64Image;
  6403. newWindow.document.body.appendChild(img);
  6404. }
  6405. }
  6406. };
  6407. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6408. if (mimeType === void 0) { mimeType = "image/png"; }
  6409. var width;
  6410. var height;
  6411. // If a precision value is specified
  6412. if (size.precision) {
  6413. width = Math.round(engine.getRenderWidth() * size.precision);
  6414. height = Math.round(width / engine.getAspectRatio(camera));
  6415. }
  6416. else if (size.width && size.height) {
  6417. width = size.width;
  6418. height = size.height;
  6419. }
  6420. else if (size.width && !size.height) {
  6421. width = size.width;
  6422. height = Math.round(width / engine.getAspectRatio(camera));
  6423. }
  6424. else if (size.height && !size.width) {
  6425. height = size.height;
  6426. width = Math.round(height * engine.getAspectRatio(camera));
  6427. }
  6428. else if (!isNaN(size)) {
  6429. height = size;
  6430. width = size;
  6431. }
  6432. else {
  6433. Tools.Error("Invalid 'size' parameter !");
  6434. return;
  6435. }
  6436. if (!screenshotCanvas) {
  6437. screenshotCanvas = document.createElement('canvas');
  6438. }
  6439. screenshotCanvas.width = width;
  6440. screenshotCanvas.height = height;
  6441. var renderContext = screenshotCanvas.getContext("2d");
  6442. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6443. var newWidth = width;
  6444. var newHeight = newWidth / ratio;
  6445. if (newHeight > height) {
  6446. newHeight = height;
  6447. newWidth = newHeight * ratio;
  6448. }
  6449. var offsetX = Math.max(0, width - newWidth) / 2;
  6450. var offsetY = Math.max(0, height - newHeight) / 2;
  6451. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6452. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6453. };
  6454. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  6455. if (mimeType === void 0) { mimeType = "image/png"; }
  6456. var width;
  6457. var height;
  6458. //If a precision value is specified
  6459. if (size.precision) {
  6460. width = Math.round(engine.getRenderWidth() * size.precision);
  6461. height = Math.round(width / engine.getAspectRatio(camera));
  6462. size = { width: width, height: height };
  6463. }
  6464. else if (size.width && size.height) {
  6465. width = size.width;
  6466. height = size.height;
  6467. }
  6468. else if (size.width && !size.height) {
  6469. width = size.width;
  6470. height = Math.round(width / engine.getAspectRatio(camera));
  6471. size = { width: width, height: height };
  6472. }
  6473. else if (size.height && !size.width) {
  6474. height = size.height;
  6475. width = Math.round(height * engine.getAspectRatio(camera));
  6476. size = { width: width, height: height };
  6477. }
  6478. else if (!isNaN(size)) {
  6479. height = size;
  6480. width = size;
  6481. }
  6482. else {
  6483. Tools.Error("Invalid 'size' parameter !");
  6484. return;
  6485. }
  6486. var scene = camera.getScene();
  6487. var previousCamera = null;
  6488. if (scene.activeCamera !== camera) {
  6489. previousCamera = scene.activeCamera;
  6490. scene.activeCamera = camera;
  6491. }
  6492. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6493. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6494. texture.renderList = scene.meshes;
  6495. texture.onAfterRenderObservable.add(function () {
  6496. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6497. });
  6498. scene.incrementRenderId();
  6499. scene.resetCachedMaterial();
  6500. texture.render(true);
  6501. texture.dispose();
  6502. if (previousCamera) {
  6503. scene.activeCamera = previousCamera;
  6504. }
  6505. camera.getProjectionMatrix(true); // Force cache refresh;
  6506. };
  6507. // XHR response validator for local file scenario
  6508. Tools.ValidateXHRData = function (xhr, dataType) {
  6509. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6510. if (dataType === void 0) { dataType = 7; }
  6511. try {
  6512. if (dataType & 1) {
  6513. if (xhr.responseText && xhr.responseText.length > 0) {
  6514. return true;
  6515. }
  6516. else if (dataType === 1) {
  6517. return false;
  6518. }
  6519. }
  6520. if (dataType & 2) {
  6521. // Check header width and height since there is no "TGA" magic number
  6522. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6523. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6524. return true;
  6525. }
  6526. else if (dataType === 2) {
  6527. return false;
  6528. }
  6529. }
  6530. if (dataType & 4) {
  6531. // Check for the "DDS" magic number
  6532. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6533. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6534. return true;
  6535. }
  6536. else {
  6537. return false;
  6538. }
  6539. }
  6540. }
  6541. catch (e) {
  6542. }
  6543. return false;
  6544. };
  6545. /**
  6546. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6547. * Be aware Math.random() could cause collisions, but:
  6548. * "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"
  6549. */
  6550. Tools.RandomId = function () {
  6551. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6552. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6553. return v.toString(16);
  6554. });
  6555. };
  6556. Object.defineProperty(Tools, "NoneLogLevel", {
  6557. get: function () {
  6558. return Tools._NoneLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Tools, "MessageLogLevel", {
  6564. get: function () {
  6565. return Tools._MessageLogLevel;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Tools, "WarningLogLevel", {
  6571. get: function () {
  6572. return Tools._WarningLogLevel;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Tools, "ErrorLogLevel", {
  6578. get: function () {
  6579. return Tools._ErrorLogLevel;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Object.defineProperty(Tools, "AllLogLevel", {
  6585. get: function () {
  6586. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6587. },
  6588. enumerable: true,
  6589. configurable: true
  6590. });
  6591. Tools._AddLogEntry = function (entry) {
  6592. Tools._LogCache = entry + Tools._LogCache;
  6593. if (Tools.OnNewCacheEntry) {
  6594. Tools.OnNewCacheEntry(entry);
  6595. }
  6596. };
  6597. Tools._FormatMessage = function (message) {
  6598. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6599. var date = new Date();
  6600. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6601. };
  6602. Tools._LogDisabled = function (message) {
  6603. // nothing to do
  6604. };
  6605. Tools._LogEnabled = function (message) {
  6606. var formattedMessage = Tools._FormatMessage(message);
  6607. console.log("BJS - " + formattedMessage);
  6608. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6609. Tools._AddLogEntry(entry);
  6610. };
  6611. Tools._WarnDisabled = function (message) {
  6612. // nothing to do
  6613. };
  6614. Tools._WarnEnabled = function (message) {
  6615. var formattedMessage = Tools._FormatMessage(message);
  6616. console.warn("BJS - " + formattedMessage);
  6617. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6618. Tools._AddLogEntry(entry);
  6619. };
  6620. Tools._ErrorDisabled = function (message) {
  6621. // nothing to do
  6622. };
  6623. Tools._ErrorEnabled = function (message) {
  6624. Tools.errorsCount++;
  6625. var formattedMessage = Tools._FormatMessage(message);
  6626. console.error("BJS - " + formattedMessage);
  6627. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6628. Tools._AddLogEntry(entry);
  6629. };
  6630. Object.defineProperty(Tools, "LogCache", {
  6631. get: function () {
  6632. return Tools._LogCache;
  6633. },
  6634. enumerable: true,
  6635. configurable: true
  6636. });
  6637. Tools.ClearLogCache = function () {
  6638. Tools._LogCache = "";
  6639. Tools.errorsCount = 0;
  6640. };
  6641. Object.defineProperty(Tools, "LogLevels", {
  6642. set: function (level) {
  6643. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6644. Tools.Log = Tools._LogEnabled;
  6645. }
  6646. else {
  6647. Tools.Log = Tools._LogDisabled;
  6648. }
  6649. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6650. Tools.Warn = Tools._WarnEnabled;
  6651. }
  6652. else {
  6653. Tools.Warn = Tools._WarnDisabled;
  6654. }
  6655. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6656. Tools.Error = Tools._ErrorEnabled;
  6657. }
  6658. else {
  6659. Tools.Error = Tools._ErrorDisabled;
  6660. }
  6661. },
  6662. enumerable: true,
  6663. configurable: true
  6664. });
  6665. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6666. get: function () {
  6667. return Tools._PerformanceNoneLogLevel;
  6668. },
  6669. enumerable: true,
  6670. configurable: true
  6671. });
  6672. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6673. get: function () {
  6674. return Tools._PerformanceUserMarkLogLevel;
  6675. },
  6676. enumerable: true,
  6677. configurable: true
  6678. });
  6679. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6680. get: function () {
  6681. return Tools._PerformanceConsoleLogLevel;
  6682. },
  6683. enumerable: true,
  6684. configurable: true
  6685. });
  6686. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6687. set: function (level) {
  6688. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6689. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6690. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6691. return;
  6692. }
  6693. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6694. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6695. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6696. return;
  6697. }
  6698. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6699. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6705. };
  6706. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6707. };
  6708. Tools._StartUserMark = function (counterName, condition) {
  6709. if (condition === void 0) { condition = true; }
  6710. if (!condition || !Tools._performance.mark) {
  6711. return;
  6712. }
  6713. Tools._performance.mark(counterName + "-Begin");
  6714. };
  6715. Tools._EndUserMark = function (counterName, condition) {
  6716. if (condition === void 0) { condition = true; }
  6717. if (!condition || !Tools._performance.mark) {
  6718. return;
  6719. }
  6720. Tools._performance.mark(counterName + "-End");
  6721. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6722. };
  6723. Tools._StartPerformanceConsole = function (counterName, condition) {
  6724. if (condition === void 0) { condition = true; }
  6725. if (!condition) {
  6726. return;
  6727. }
  6728. Tools._StartUserMark(counterName, condition);
  6729. if (console.time) {
  6730. console.time(counterName);
  6731. }
  6732. };
  6733. Tools._EndPerformanceConsole = function (counterName, condition) {
  6734. if (condition === void 0) { condition = true; }
  6735. if (!condition) {
  6736. return;
  6737. }
  6738. Tools._EndUserMark(counterName, condition);
  6739. if (console.time) {
  6740. console.timeEnd(counterName);
  6741. }
  6742. };
  6743. Object.defineProperty(Tools, "Now", {
  6744. get: function () {
  6745. if (window.performance && window.performance.now) {
  6746. return window.performance.now();
  6747. }
  6748. return new Date().getTime();
  6749. },
  6750. enumerable: true,
  6751. configurable: true
  6752. });
  6753. /**
  6754. * This method will return the name of the class used to create the instance of the given object.
  6755. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6756. * @param object the object to get the class name from
  6757. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6758. */
  6759. Tools.getClassName = function (object, isType) {
  6760. if (isType === void 0) { isType = false; }
  6761. var name = null;
  6762. if (!isType && object.getClassName) {
  6763. name = object.getClassName();
  6764. }
  6765. else {
  6766. if (object instanceof Object) {
  6767. var classObj = isType ? object : Object.getPrototypeOf(object);
  6768. name = classObj.constructor["__bjsclassName__"];
  6769. }
  6770. if (!name) {
  6771. name = typeof object;
  6772. }
  6773. }
  6774. return name;
  6775. };
  6776. Tools.first = function (array, predicate) {
  6777. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6778. var el = array_1[_i];
  6779. if (predicate(el)) {
  6780. return el;
  6781. }
  6782. }
  6783. };
  6784. /**
  6785. * This method will return the name of the full name of the class, including its owning module (if any).
  6786. * 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).
  6787. * @param object the object to get the class name from
  6788. * @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.
  6789. */
  6790. Tools.getFullClassName = function (object, isType) {
  6791. if (isType === void 0) { isType = false; }
  6792. var className = null;
  6793. var moduleName = null;
  6794. if (!isType && object.getClassName) {
  6795. className = object.getClassName();
  6796. }
  6797. else {
  6798. if (object instanceof Object) {
  6799. var classObj = isType ? object : Object.getPrototypeOf(object);
  6800. className = classObj.constructor["__bjsclassName__"];
  6801. moduleName = classObj.constructor["__bjsmoduleName__"];
  6802. }
  6803. if (!className) {
  6804. className = typeof object;
  6805. }
  6806. }
  6807. if (!className) {
  6808. return null;
  6809. }
  6810. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6811. };
  6812. /**
  6813. * 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.
  6814. * @param array
  6815. */
  6816. Tools.arrayOrStringFeeder = function (array) {
  6817. return function (index) {
  6818. if (index >= array.length) {
  6819. return null;
  6820. }
  6821. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6822. if (val && val.getHashCode) {
  6823. val = val.getHashCode();
  6824. }
  6825. if (typeof val === "string") {
  6826. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6827. }
  6828. return val;
  6829. };
  6830. };
  6831. /**
  6832. * Compute the hashCode of a stream of number
  6833. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6834. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6835. * @return the hash code computed
  6836. */
  6837. Tools.hashCodeFromStream = function (feeder) {
  6838. // Based from here: http://stackoverflow.com/a/7616484/802124
  6839. var hash = 0;
  6840. var index = 0;
  6841. var chr = feeder(index++);
  6842. while (chr != null) {
  6843. hash = ((hash << 5) - hash) + chr;
  6844. hash |= 0; // Convert to 32bit integer
  6845. chr = feeder(index++);
  6846. }
  6847. return hash;
  6848. };
  6849. return Tools;
  6850. }());
  6851. Tools.BaseUrl = "";
  6852. Tools.CorsBehavior = "anonymous";
  6853. Tools.UseFallbackTexture = true;
  6854. // Used in case of a texture loading problem
  6855. 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";
  6856. // Logs
  6857. Tools._NoneLogLevel = 0;
  6858. Tools._MessageLogLevel = 1;
  6859. Tools._WarningLogLevel = 2;
  6860. Tools._ErrorLogLevel = 4;
  6861. Tools._LogCache = "";
  6862. Tools.errorsCount = 0;
  6863. Tools.Log = Tools._LogEnabled;
  6864. Tools.Warn = Tools._WarnEnabled;
  6865. Tools.Error = Tools._ErrorEnabled;
  6866. // Performances
  6867. Tools._PerformanceNoneLogLevel = 0;
  6868. Tools._PerformanceUserMarkLogLevel = 1;
  6869. Tools._PerformanceConsoleLogLevel = 2;
  6870. Tools._performance = window.performance;
  6871. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6872. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6873. BABYLON.Tools = Tools;
  6874. /**
  6875. * This class is used to track a performance counter which is number based.
  6876. * The user has access to many properties which give statistics of different nature
  6877. *
  6878. * The implementer can track two kinds of Performance Counter: time and count
  6879. * 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.
  6880. * 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.
  6881. */
  6882. var PerfCounter = (function () {
  6883. function PerfCounter() {
  6884. this._startMonitoringTime = 0;
  6885. this._min = 0;
  6886. this._max = 0;
  6887. this._average = 0;
  6888. this._lastSecAverage = 0;
  6889. this._current = 0;
  6890. this._totalValueCount = 0;
  6891. this._totalAccumulated = 0;
  6892. this._lastSecAccumulated = 0;
  6893. this._lastSecTime = 0;
  6894. this._lastSecValueCount = 0;
  6895. }
  6896. Object.defineProperty(PerfCounter.prototype, "min", {
  6897. /**
  6898. * Returns the smallest value ever
  6899. */
  6900. get: function () {
  6901. return this._min;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(PerfCounter.prototype, "max", {
  6907. /**
  6908. * Returns the biggest value ever
  6909. */
  6910. get: function () {
  6911. return this._max;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(PerfCounter.prototype, "average", {
  6917. /**
  6918. * Returns the average value since the performance counter is running
  6919. */
  6920. get: function () {
  6921. return this._average;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6927. /**
  6928. * Returns the average value of the last second the counter was monitored
  6929. */
  6930. get: function () {
  6931. return this._lastSecAverage;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(PerfCounter.prototype, "current", {
  6937. /**
  6938. * Returns the current value
  6939. */
  6940. get: function () {
  6941. return this._current;
  6942. },
  6943. enumerable: true,
  6944. configurable: true
  6945. });
  6946. Object.defineProperty(PerfCounter.prototype, "total", {
  6947. get: function () {
  6948. return this._totalAccumulated;
  6949. },
  6950. enumerable: true,
  6951. configurable: true
  6952. });
  6953. /**
  6954. * Call this method to start monitoring a new frame.
  6955. * 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.
  6956. */
  6957. PerfCounter.prototype.fetchNewFrame = function () {
  6958. this._totalValueCount++;
  6959. this._current = 0;
  6960. this._lastSecValueCount++;
  6961. };
  6962. /**
  6963. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6964. * @param newCount the count value to add to the monitored count
  6965. * @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.
  6966. */
  6967. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6968. this._current += newCount;
  6969. if (fetchResult) {
  6970. this._fetchResult();
  6971. }
  6972. };
  6973. /**
  6974. * Start monitoring this performance counter
  6975. */
  6976. PerfCounter.prototype.beginMonitoring = function () {
  6977. this._startMonitoringTime = Tools.Now;
  6978. };
  6979. /**
  6980. * Compute the time lapsed since the previous beginMonitoring() call.
  6981. * @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
  6982. */
  6983. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6984. if (newFrame === void 0) { newFrame = true; }
  6985. if (newFrame) {
  6986. this.fetchNewFrame();
  6987. }
  6988. var currentTime = Tools.Now;
  6989. this._current = currentTime - this._startMonitoringTime;
  6990. if (newFrame) {
  6991. this._fetchResult();
  6992. }
  6993. };
  6994. PerfCounter.prototype._fetchResult = function () {
  6995. this._totalAccumulated += this._current;
  6996. this._lastSecAccumulated += this._current;
  6997. // Min/Max update
  6998. this._min = Math.min(this._min, this._current);
  6999. this._max = Math.max(this._max, this._current);
  7000. this._average = this._totalAccumulated / this._totalValueCount;
  7001. // Reset last sec?
  7002. var now = Tools.Now;
  7003. if ((now - this._lastSecTime) > 1000) {
  7004. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7005. this._lastSecTime = now;
  7006. this._lastSecAccumulated = 0;
  7007. this._lastSecValueCount = 0;
  7008. }
  7009. };
  7010. return PerfCounter;
  7011. }());
  7012. BABYLON.PerfCounter = PerfCounter;
  7013. /**
  7014. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7015. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7016. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7017. * @param name The name of the class, case should be preserved
  7018. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7019. */
  7020. function className(name, module) {
  7021. return function (target) {
  7022. target["__bjsclassName__"] = name;
  7023. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7024. };
  7025. }
  7026. BABYLON.className = className;
  7027. /**
  7028. * An implementation of a loop for asynchronous functions.
  7029. */
  7030. var AsyncLoop = (function () {
  7031. /**
  7032. * Constroctor.
  7033. * @param iterations the number of iterations.
  7034. * @param _fn the function to run each iteration
  7035. * @param _successCallback the callback that will be called upon succesful execution
  7036. * @param offset starting offset.
  7037. */
  7038. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7039. if (offset === void 0) { offset = 0; }
  7040. this.iterations = iterations;
  7041. this._fn = _fn;
  7042. this._successCallback = _successCallback;
  7043. this.index = offset - 1;
  7044. this._done = false;
  7045. }
  7046. /**
  7047. * Execute the next iteration. Must be called after the last iteration was finished.
  7048. */
  7049. AsyncLoop.prototype.executeNext = function () {
  7050. if (!this._done) {
  7051. if (this.index + 1 < this.iterations) {
  7052. ++this.index;
  7053. this._fn(this);
  7054. }
  7055. else {
  7056. this.breakLoop();
  7057. }
  7058. }
  7059. };
  7060. /**
  7061. * Break the loop and run the success callback.
  7062. */
  7063. AsyncLoop.prototype.breakLoop = function () {
  7064. this._done = true;
  7065. this._successCallback();
  7066. };
  7067. /**
  7068. * Helper function
  7069. */
  7070. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7071. if (offset === void 0) { offset = 0; }
  7072. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7073. loop.executeNext();
  7074. return loop;
  7075. };
  7076. /**
  7077. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7078. * @param iterations total number of iterations
  7079. * @param syncedIterations number of synchronous iterations in each async iteration.
  7080. * @param fn the function to call each iteration.
  7081. * @param callback a success call back that will be called when iterating stops.
  7082. * @param breakFunction a break condition (optional)
  7083. * @param timeout timeout settings for the setTimeout function. default - 0.
  7084. * @constructor
  7085. */
  7086. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7087. if (timeout === void 0) { timeout = 0; }
  7088. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7089. if (breakFunction && breakFunction())
  7090. loop.breakLoop();
  7091. else {
  7092. setTimeout(function () {
  7093. for (var i = 0; i < syncedIterations; ++i) {
  7094. var iteration = (loop.index * syncedIterations) + i;
  7095. if (iteration >= iterations)
  7096. break;
  7097. fn(iteration);
  7098. if (breakFunction && breakFunction()) {
  7099. loop.breakLoop();
  7100. break;
  7101. }
  7102. }
  7103. loop.executeNext();
  7104. }, timeout);
  7105. }
  7106. }, callback);
  7107. };
  7108. return AsyncLoop;
  7109. }());
  7110. BABYLON.AsyncLoop = AsyncLoop;
  7111. })(BABYLON || (BABYLON = {}));
  7112. //# sourceMappingURL=babylon.tools.js.map
  7113. var BABYLON;
  7114. (function (BABYLON) {
  7115. var Internals;
  7116. (function (Internals) {
  7117. var _AlphaState = (function () {
  7118. /**
  7119. * Initializes the state.
  7120. */
  7121. function _AlphaState() {
  7122. this._isAlphaBlendDirty = false;
  7123. this._isBlendFunctionParametersDirty = false;
  7124. this._alphaBlend = false;
  7125. this._blendFunctionParameters = new Array(4);
  7126. this.reset();
  7127. }
  7128. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7129. get: function () {
  7130. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7136. get: function () {
  7137. return this._alphaBlend;
  7138. },
  7139. set: function (value) {
  7140. if (this._alphaBlend === value) {
  7141. return;
  7142. }
  7143. this._alphaBlend = value;
  7144. this._isAlphaBlendDirty = true;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7150. if (this._blendFunctionParameters[0] === value0 &&
  7151. this._blendFunctionParameters[1] === value1 &&
  7152. this._blendFunctionParameters[2] === value2 &&
  7153. this._blendFunctionParameters[3] === value3) {
  7154. return;
  7155. }
  7156. this._blendFunctionParameters[0] = value0;
  7157. this._blendFunctionParameters[1] = value1;
  7158. this._blendFunctionParameters[2] = value2;
  7159. this._blendFunctionParameters[3] = value3;
  7160. this._isBlendFunctionParametersDirty = true;
  7161. };
  7162. _AlphaState.prototype.reset = function () {
  7163. this._alphaBlend = false;
  7164. this._blendFunctionParameters[0] = null;
  7165. this._blendFunctionParameters[1] = null;
  7166. this._blendFunctionParameters[2] = null;
  7167. this._blendFunctionParameters[3] = null;
  7168. this._isAlphaBlendDirty = true;
  7169. this._isBlendFunctionParametersDirty = false;
  7170. };
  7171. _AlphaState.prototype.apply = function (gl) {
  7172. if (!this.isDirty) {
  7173. return;
  7174. }
  7175. // Alpha blend
  7176. if (this._isAlphaBlendDirty) {
  7177. if (this._alphaBlend) {
  7178. gl.enable(gl.BLEND);
  7179. }
  7180. else {
  7181. gl.disable(gl.BLEND);
  7182. }
  7183. this._isAlphaBlendDirty = false;
  7184. }
  7185. // Alpha function
  7186. if (this._isBlendFunctionParametersDirty) {
  7187. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7188. this._isBlendFunctionParametersDirty = false;
  7189. }
  7190. };
  7191. return _AlphaState;
  7192. }());
  7193. Internals._AlphaState = _AlphaState;
  7194. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7195. })(BABYLON || (BABYLON = {}));
  7196. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7197. var BABYLON;
  7198. (function (BABYLON) {
  7199. var Internals;
  7200. (function (Internals) {
  7201. var _DepthCullingState = (function () {
  7202. /**
  7203. * Initializes the state.
  7204. */
  7205. function _DepthCullingState() {
  7206. this._isDepthTestDirty = false;
  7207. this._isDepthMaskDirty = false;
  7208. this._isDepthFuncDirty = false;
  7209. this._isCullFaceDirty = false;
  7210. this._isCullDirty = false;
  7211. this._isZOffsetDirty = false;
  7212. this.reset();
  7213. }
  7214. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7215. get: function () {
  7216. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7217. },
  7218. enumerable: true,
  7219. configurable: true
  7220. });
  7221. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7222. get: function () {
  7223. return this._zOffset;
  7224. },
  7225. set: function (value) {
  7226. if (this._zOffset === value) {
  7227. return;
  7228. }
  7229. this._zOffset = value;
  7230. this._isZOffsetDirty = true;
  7231. },
  7232. enumerable: true,
  7233. configurable: true
  7234. });
  7235. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7236. get: function () {
  7237. return this._cullFace;
  7238. },
  7239. set: function (value) {
  7240. if (this._cullFace === value) {
  7241. return;
  7242. }
  7243. this._cullFace = value;
  7244. this._isCullFaceDirty = true;
  7245. },
  7246. enumerable: true,
  7247. configurable: true
  7248. });
  7249. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7250. get: function () {
  7251. return this._cull;
  7252. },
  7253. set: function (value) {
  7254. if (this._cull === value) {
  7255. return;
  7256. }
  7257. this._cull = value;
  7258. this._isCullDirty = true;
  7259. },
  7260. enumerable: true,
  7261. configurable: true
  7262. });
  7263. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7264. get: function () {
  7265. return this._depthFunc;
  7266. },
  7267. set: function (value) {
  7268. if (this._depthFunc === value) {
  7269. return;
  7270. }
  7271. this._depthFunc = value;
  7272. this._isDepthFuncDirty = true;
  7273. },
  7274. enumerable: true,
  7275. configurable: true
  7276. });
  7277. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7278. get: function () {
  7279. return this._depthMask;
  7280. },
  7281. set: function (value) {
  7282. if (this._depthMask === value) {
  7283. return;
  7284. }
  7285. this._depthMask = value;
  7286. this._isDepthMaskDirty = true;
  7287. },
  7288. enumerable: true,
  7289. configurable: true
  7290. });
  7291. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7292. get: function () {
  7293. return this._depthTest;
  7294. },
  7295. set: function (value) {
  7296. if (this._depthTest === value) {
  7297. return;
  7298. }
  7299. this._depthTest = value;
  7300. this._isDepthTestDirty = true;
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. _DepthCullingState.prototype.reset = function () {
  7306. this._depthMask = true;
  7307. this._depthTest = true;
  7308. this._depthFunc = null;
  7309. this._cullFace = null;
  7310. this._cull = null;
  7311. this._zOffset = 0;
  7312. this._isDepthTestDirty = true;
  7313. this._isDepthMaskDirty = true;
  7314. this._isDepthFuncDirty = false;
  7315. this._isCullFaceDirty = false;
  7316. this._isCullDirty = false;
  7317. this._isZOffsetDirty = false;
  7318. };
  7319. _DepthCullingState.prototype.apply = function (gl) {
  7320. if (!this.isDirty) {
  7321. return;
  7322. }
  7323. // Cull
  7324. if (this._isCullDirty) {
  7325. if (this.cull) {
  7326. gl.enable(gl.CULL_FACE);
  7327. }
  7328. else {
  7329. gl.disable(gl.CULL_FACE);
  7330. }
  7331. this._isCullDirty = false;
  7332. }
  7333. // Cull face
  7334. if (this._isCullFaceDirty) {
  7335. gl.cullFace(this.cullFace);
  7336. this._isCullFaceDirty = false;
  7337. }
  7338. // Depth mask
  7339. if (this._isDepthMaskDirty) {
  7340. gl.depthMask(this.depthMask);
  7341. this._isDepthMaskDirty = false;
  7342. }
  7343. // Depth test
  7344. if (this._isDepthTestDirty) {
  7345. if (this.depthTest) {
  7346. gl.enable(gl.DEPTH_TEST);
  7347. }
  7348. else {
  7349. gl.disable(gl.DEPTH_TEST);
  7350. }
  7351. this._isDepthTestDirty = false;
  7352. }
  7353. // Depth func
  7354. if (this._isDepthFuncDirty) {
  7355. gl.depthFunc(this.depthFunc);
  7356. this._isDepthFuncDirty = false;
  7357. }
  7358. // zOffset
  7359. if (this._isZOffsetDirty) {
  7360. if (this.zOffset) {
  7361. gl.enable(gl.POLYGON_OFFSET_FILL);
  7362. gl.polygonOffset(this.zOffset, 0);
  7363. }
  7364. else {
  7365. gl.disable(gl.POLYGON_OFFSET_FILL);
  7366. }
  7367. this._isZOffsetDirty = false;
  7368. }
  7369. };
  7370. return _DepthCullingState;
  7371. }());
  7372. Internals._DepthCullingState = _DepthCullingState;
  7373. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7374. })(BABYLON || (BABYLON = {}));
  7375. //# sourceMappingURL=babylon.depthCullingState.js.map
  7376. var BABYLON;
  7377. (function (BABYLON) {
  7378. var Internals;
  7379. (function (Internals) {
  7380. var _StencilState = (function () {
  7381. function _StencilState() {
  7382. this._isStencilTestDirty = false;
  7383. this._isStencilMaskDirty = false;
  7384. this._isStencilFuncDirty = false;
  7385. this._isStencilOpDirty = false;
  7386. this.reset();
  7387. }
  7388. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7389. get: function () {
  7390. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7391. },
  7392. enumerable: true,
  7393. configurable: true
  7394. });
  7395. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7396. get: function () {
  7397. return this._stencilFunc;
  7398. },
  7399. set: function (value) {
  7400. if (this._stencilFunc === value) {
  7401. return;
  7402. }
  7403. this._stencilFunc = value;
  7404. this._isStencilFuncDirty = true;
  7405. },
  7406. enumerable: true,
  7407. configurable: true
  7408. });
  7409. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7410. get: function () {
  7411. return this._stencilFuncRef;
  7412. },
  7413. set: function (value) {
  7414. if (this._stencilFuncRef === value) {
  7415. return;
  7416. }
  7417. this._stencilFuncRef = value;
  7418. this._isStencilFuncDirty = true;
  7419. },
  7420. enumerable: true,
  7421. configurable: true
  7422. });
  7423. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7424. get: function () {
  7425. return this._stencilFuncMask;
  7426. },
  7427. set: function (value) {
  7428. if (this._stencilFuncMask === value) {
  7429. return;
  7430. }
  7431. this._stencilFuncMask = value;
  7432. this._isStencilFuncDirty = true;
  7433. },
  7434. enumerable: true,
  7435. configurable: true
  7436. });
  7437. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7438. get: function () {
  7439. return this._stencilOpStencilFail;
  7440. },
  7441. set: function (value) {
  7442. if (this._stencilOpStencilFail === value) {
  7443. return;
  7444. }
  7445. this._stencilOpStencilFail = value;
  7446. this._isStencilOpDirty = true;
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7452. get: function () {
  7453. return this._stencilOpDepthFail;
  7454. },
  7455. set: function (value) {
  7456. if (this._stencilOpDepthFail === value) {
  7457. return;
  7458. }
  7459. this._stencilOpDepthFail = value;
  7460. this._isStencilOpDirty = true;
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7466. get: function () {
  7467. return this._stencilOpStencilDepthPass;
  7468. },
  7469. set: function (value) {
  7470. if (this._stencilOpStencilDepthPass === value) {
  7471. return;
  7472. }
  7473. this._stencilOpStencilDepthPass = value;
  7474. this._isStencilOpDirty = true;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7480. get: function () {
  7481. return this._stencilMask;
  7482. },
  7483. set: function (value) {
  7484. if (this._stencilMask === value) {
  7485. return;
  7486. }
  7487. this._stencilMask = value;
  7488. this._isStencilMaskDirty = true;
  7489. },
  7490. enumerable: true,
  7491. configurable: true
  7492. });
  7493. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7494. get: function () {
  7495. return this._stencilTest;
  7496. },
  7497. set: function (value) {
  7498. if (this._stencilTest === value) {
  7499. return;
  7500. }
  7501. this._stencilTest = value;
  7502. this._isStencilTestDirty = true;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. _StencilState.prototype.reset = function () {
  7508. this._stencilTest = false;
  7509. this._stencilMask = 0xFF;
  7510. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7511. this._stencilFuncRef = 1;
  7512. this._stencilFuncMask = 0xFF;
  7513. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7514. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7515. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7516. this._isStencilTestDirty = true;
  7517. this._isStencilMaskDirty = true;
  7518. this._isStencilFuncDirty = true;
  7519. this._isStencilOpDirty = true;
  7520. };
  7521. _StencilState.prototype.apply = function (gl) {
  7522. if (!this.isDirty) {
  7523. return;
  7524. }
  7525. // Stencil test
  7526. if (this._isStencilTestDirty) {
  7527. if (this.stencilTest) {
  7528. gl.enable(gl.STENCIL_TEST);
  7529. }
  7530. else {
  7531. gl.disable(gl.STENCIL_TEST);
  7532. }
  7533. this._isStencilTestDirty = false;
  7534. }
  7535. // Stencil mask
  7536. if (this._isStencilMaskDirty) {
  7537. gl.stencilMask(this.stencilMask);
  7538. this._isStencilMaskDirty = false;
  7539. }
  7540. // Stencil func
  7541. if (this._isStencilFuncDirty) {
  7542. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7543. this._isStencilFuncDirty = false;
  7544. }
  7545. // Stencil op
  7546. if (this._isStencilOpDirty) {
  7547. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7548. this._isStencilOpDirty = false;
  7549. }
  7550. };
  7551. return _StencilState;
  7552. }());
  7553. Internals._StencilState = _StencilState;
  7554. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7555. })(BABYLON || (BABYLON = {}));
  7556. //# sourceMappingURL=babylon.stencilState.js.map
  7557. var BABYLON;
  7558. (function (BABYLON) {
  7559. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7560. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7561. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7562. gl.compileShader(shader);
  7563. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7564. throw new Error(gl.getShaderInfoLog(shader));
  7565. }
  7566. return shader;
  7567. };
  7568. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7569. var magFilter = gl.NEAREST;
  7570. var minFilter = gl.NEAREST;
  7571. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7572. magFilter = gl.LINEAR;
  7573. if (generateMipMaps) {
  7574. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7575. }
  7576. else {
  7577. minFilter = gl.LINEAR;
  7578. }
  7579. }
  7580. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7581. magFilter = gl.LINEAR;
  7582. if (generateMipMaps) {
  7583. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7584. }
  7585. else {
  7586. minFilter = gl.LINEAR;
  7587. }
  7588. }
  7589. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7590. magFilter = gl.NEAREST;
  7591. if (generateMipMaps) {
  7592. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7593. }
  7594. else {
  7595. minFilter = gl.NEAREST;
  7596. }
  7597. }
  7598. return {
  7599. min: minFilter,
  7600. mag: magFilter
  7601. };
  7602. };
  7603. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7605. var engine = scene.getEngine();
  7606. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7607. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7608. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7609. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7610. texture._baseWidth = width;
  7611. texture._baseHeight = height;
  7612. texture._width = potWidth;
  7613. texture._height = potHeight;
  7614. texture.isReady = true;
  7615. processFunction(potWidth, potHeight);
  7616. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7617. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7619. if (!noMipmap && !isCompressed) {
  7620. gl.generateMipmap(gl.TEXTURE_2D);
  7621. }
  7622. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7623. engine.resetTextureCache();
  7624. scene._removePendingData(texture);
  7625. texture.onLoadedCallbacks.forEach(function (callback) {
  7626. callback();
  7627. });
  7628. texture.onLoadedCallbacks = [];
  7629. };
  7630. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7631. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7632. var img;
  7633. var onload = function () {
  7634. loadedImages[index] = img;
  7635. loadedImages._internalCount++;
  7636. scene._removePendingData(img);
  7637. if (loadedImages._internalCount === 6) {
  7638. onfinish(loadedImages);
  7639. }
  7640. };
  7641. var onerror = function () {
  7642. scene._removePendingData(img);
  7643. if (onErrorCallBack) {
  7644. onErrorCallBack();
  7645. }
  7646. };
  7647. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7648. scene._addPendingData(img);
  7649. };
  7650. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7651. if (onError === void 0) { onError = null; }
  7652. var loadedImages = [];
  7653. loadedImages._internalCount = 0;
  7654. for (var index = 0; index < 6; index++) {
  7655. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7656. }
  7657. };
  7658. var InstancingAttributeInfo = (function () {
  7659. function InstancingAttributeInfo() {
  7660. }
  7661. return InstancingAttributeInfo;
  7662. }());
  7663. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7664. var EngineCapabilities = (function () {
  7665. function EngineCapabilities() {
  7666. }
  7667. return EngineCapabilities;
  7668. }());
  7669. BABYLON.EngineCapabilities = EngineCapabilities;
  7670. /**
  7671. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7672. */
  7673. var Engine = (function () {
  7674. /**
  7675. * @constructor
  7676. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7677. * @param {boolean} [antialias] - enable antialias
  7678. * @param options - further options to be sent to the getContext function
  7679. */
  7680. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7681. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7682. var _this = this;
  7683. // Public members
  7684. this.isFullscreen = false;
  7685. this.isPointerLock = false;
  7686. this.cullBackFaces = true;
  7687. this.renderEvenInBackground = true;
  7688. // To enable/disable IDB support and avoid XHR on .manifest
  7689. this.enableOfflineSupport = true;
  7690. this.scenes = new Array();
  7691. this._windowIsBackground = false;
  7692. this._webGLVersion = 1.0;
  7693. this._badOS = false;
  7694. this._drawCalls = new BABYLON.PerfCounter();
  7695. this._renderingQueueLaunched = false;
  7696. this._activeRenderLoops = [];
  7697. // FPS
  7698. this.fpsRange = 60;
  7699. this.previousFramesDuration = [];
  7700. this.fps = 60;
  7701. this.deltaTime = 0;
  7702. // States
  7703. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7704. this._stencilState = new BABYLON.Internals._StencilState();
  7705. this._alphaState = new BABYLON.Internals._AlphaState();
  7706. this._alphaMode = Engine.ALPHA_DISABLE;
  7707. // Cache
  7708. this._loadedTexturesCache = new Array();
  7709. this._maxTextureChannels = 16;
  7710. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7711. this._compiledEffects = {};
  7712. this._vertexAttribArraysEnabled = [];
  7713. this._uintIndicesCurrentlySet = false;
  7714. this._currentBoundBuffer = new Array();
  7715. this._currentBufferPointers = [];
  7716. this._currentInstanceLocations = new Array();
  7717. this._currentInstanceBuffers = new Array();
  7718. this._vaoRecordInProgress = false;
  7719. this._mustWipeVertexAttributes = false;
  7720. // Hardware supported Compressed Textures
  7721. this._texturesSupported = new Array();
  7722. this._onVRFullScreenTriggered = function () {
  7723. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7724. //get the old size before we change
  7725. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7726. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7727. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  7728. //But actually, no browser follow the specs...
  7729. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  7730. //get the width and height, change the render size
  7731. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7732. var width, height;
  7733. _this.setHardwareScalingLevel(1);
  7734. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7735. }
  7736. else {
  7737. //When the specs are implemented, need to uncomment this.
  7738. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7739. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7740. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7741. _this._vrDisplayEnabled = undefined;
  7742. }
  7743. };
  7744. this._renderingCanvas = canvas;
  7745. this._externalData = new BABYLON.StringDictionary();
  7746. options = options || {};
  7747. if (antialias != null) {
  7748. options.antialias = antialias;
  7749. }
  7750. if (options.preserveDrawingBuffer === undefined) {
  7751. options.preserveDrawingBuffer = false;
  7752. }
  7753. // GL
  7754. if (!options.disableWebGL2Support) {
  7755. try {
  7756. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7757. if (this._gl) {
  7758. this._webGLVersion = 2.0;
  7759. }
  7760. }
  7761. catch (e) {
  7762. }
  7763. }
  7764. if (!this._gl) {
  7765. if (!canvas) {
  7766. throw new Error("The provided canvas is null or undefined.");
  7767. }
  7768. try {
  7769. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7770. }
  7771. catch (e) {
  7772. throw new Error("WebGL not supported");
  7773. }
  7774. }
  7775. if (!this._gl) {
  7776. throw new Error("WebGL not supported");
  7777. }
  7778. this._onBlur = function () {
  7779. _this._windowIsBackground = true;
  7780. };
  7781. this._onFocus = function () {
  7782. _this._windowIsBackground = false;
  7783. };
  7784. window.addEventListener("blur", this._onBlur);
  7785. window.addEventListener("focus", this._onFocus);
  7786. // Viewport
  7787. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7788. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7789. this.resize();
  7790. // Caps
  7791. this._isStencilEnable = options.stencil;
  7792. this._caps = new EngineCapabilities();
  7793. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7794. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7795. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7796. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7797. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7798. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7799. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7800. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7801. // Infos
  7802. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7803. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7804. if (rendererInfo != null) {
  7805. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7806. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7807. }
  7808. if (!this._glVendor) {
  7809. this._glVendor = "Unknown vendor";
  7810. }
  7811. if (!this._glRenderer) {
  7812. this._glRenderer = "Unknown renderer";
  7813. }
  7814. // Extensions
  7815. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7816. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7817. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7818. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7819. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7820. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7821. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7822. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  7823. 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');
  7824. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7825. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7826. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7827. this._caps.highPrecisionShaderSupported = true;
  7828. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7829. // Checks if some of the format renders first to allow the use of webgl inspector.
  7830. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7831. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7832. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7833. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7834. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7835. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7836. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7837. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7838. // Vertex array object
  7839. if (this._webGLVersion > 1) {
  7840. this._caps.vertexArrayObject = true;
  7841. }
  7842. else {
  7843. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7844. if (vertexArrayObjectExtension != null) {
  7845. this._caps.vertexArrayObject = true;
  7846. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7847. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7848. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7849. }
  7850. else {
  7851. this._caps.vertexArrayObject = false;
  7852. }
  7853. }
  7854. // Instances count
  7855. if (this._webGLVersion > 1) {
  7856. this._caps.instancedArrays = true;
  7857. }
  7858. else {
  7859. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7860. if (instanceExtension != null) {
  7861. this._caps.instancedArrays = true;
  7862. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7863. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7864. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7865. }
  7866. else {
  7867. this._caps.instancedArrays = false;
  7868. }
  7869. }
  7870. // Intelligently add supported compressed formats in order to check for.
  7871. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7872. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7873. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7874. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7875. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  7876. if (this._caps.astc)
  7877. this.texturesSupported.push('-astc.ktx');
  7878. if (this._caps.s3tc)
  7879. this.texturesSupported.push('-dxt.ktx');
  7880. if (this._caps.pvrtc)
  7881. this.texturesSupported.push('-pvrtc.ktx');
  7882. if (this._caps.etc2)
  7883. this.texturesSupported.push('-etc2.ktx');
  7884. if (this._caps.atc)
  7885. this.texturesSupported.push('-atc.ktx');
  7886. if (this._caps.etc1)
  7887. this.texturesSupported.push('-etc1.ktx');
  7888. if (this._gl.getShaderPrecisionFormat) {
  7889. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7890. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7891. }
  7892. // Depth buffer
  7893. this.setDepthBuffer(true);
  7894. this.setDepthFunctionToLessOrEqual();
  7895. this.setDepthWrite(true);
  7896. // Fullscreen
  7897. this._onFullscreenChange = function () {
  7898. if (document.fullscreen !== undefined) {
  7899. _this.isFullscreen = document.fullscreen;
  7900. }
  7901. else if (document.mozFullScreen !== undefined) {
  7902. _this.isFullscreen = document.mozFullScreen;
  7903. }
  7904. else if (document.webkitIsFullScreen !== undefined) {
  7905. _this.isFullscreen = document.webkitIsFullScreen;
  7906. }
  7907. else if (document.msIsFullScreen !== undefined) {
  7908. _this.isFullscreen = document.msIsFullScreen;
  7909. }
  7910. // Pointer lock
  7911. if (_this.isFullscreen && _this._pointerLockRequested) {
  7912. canvas.requestPointerLock = canvas.requestPointerLock ||
  7913. canvas.msRequestPointerLock ||
  7914. canvas.mozRequestPointerLock ||
  7915. canvas.webkitRequestPointerLock;
  7916. if (canvas.requestPointerLock) {
  7917. canvas.requestPointerLock();
  7918. }
  7919. }
  7920. };
  7921. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7922. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7923. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7924. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7925. // Pointer lock
  7926. this._onPointerLockChange = function () {
  7927. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7928. document.webkitPointerLockElement === canvas ||
  7929. document.msPointerLockElement === canvas ||
  7930. document.pointerLockElement === canvas);
  7931. };
  7932. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7933. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7934. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7935. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7936. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  7937. Engine.audioEngine = new BABYLON.AudioEngine();
  7938. }
  7939. //default loading screen
  7940. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  7941. //Load WebVR Devices
  7942. if (options.autoEnableWebVR) {
  7943. this.initWebVR();
  7944. }
  7945. //Detect if we are running on a faulty buggy OS.
  7946. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7947. //ua sniffing is the tool of the devil.
  7948. this._badOS = regexp.test(navigator.userAgent);
  7949. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7950. }
  7951. Object.defineProperty(Engine, "NEVER", {
  7952. get: function () {
  7953. return Engine._NEVER;
  7954. },
  7955. enumerable: true,
  7956. configurable: true
  7957. });
  7958. Object.defineProperty(Engine, "ALWAYS", {
  7959. get: function () {
  7960. return Engine._ALWAYS;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(Engine, "LESS", {
  7966. get: function () {
  7967. return Engine._LESS;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(Engine, "EQUAL", {
  7973. get: function () {
  7974. return Engine._EQUAL;
  7975. },
  7976. enumerable: true,
  7977. configurable: true
  7978. });
  7979. Object.defineProperty(Engine, "LEQUAL", {
  7980. get: function () {
  7981. return Engine._LEQUAL;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. Object.defineProperty(Engine, "GREATER", {
  7987. get: function () {
  7988. return Engine._GREATER;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. Object.defineProperty(Engine, "GEQUAL", {
  7994. get: function () {
  7995. return Engine._GEQUAL;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(Engine, "NOTEQUAL", {
  8001. get: function () {
  8002. return Engine._NOTEQUAL;
  8003. },
  8004. enumerable: true,
  8005. configurable: true
  8006. });
  8007. Object.defineProperty(Engine, "KEEP", {
  8008. get: function () {
  8009. return Engine._KEEP;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. Object.defineProperty(Engine, "REPLACE", {
  8015. get: function () {
  8016. return Engine._REPLACE;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(Engine, "INCR", {
  8022. get: function () {
  8023. return Engine._INCR;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. Object.defineProperty(Engine, "DECR", {
  8029. get: function () {
  8030. return Engine._DECR;
  8031. },
  8032. enumerable: true,
  8033. configurable: true
  8034. });
  8035. Object.defineProperty(Engine, "INVERT", {
  8036. get: function () {
  8037. return Engine._INVERT;
  8038. },
  8039. enumerable: true,
  8040. configurable: true
  8041. });
  8042. Object.defineProperty(Engine, "INCR_WRAP", {
  8043. get: function () {
  8044. return Engine._INCR_WRAP;
  8045. },
  8046. enumerable: true,
  8047. configurable: true
  8048. });
  8049. Object.defineProperty(Engine, "DECR_WRAP", {
  8050. get: function () {
  8051. return Engine._DECR_WRAP;
  8052. },
  8053. enumerable: true,
  8054. configurable: true
  8055. });
  8056. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8057. get: function () {
  8058. return Engine._ALPHA_DISABLE;
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8064. get: function () {
  8065. return Engine._ALPHA_ONEONE;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Object.defineProperty(Engine, "ALPHA_ADD", {
  8071. get: function () {
  8072. return Engine._ALPHA_ADD;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8078. get: function () {
  8079. return Engine._ALPHA_COMBINE;
  8080. },
  8081. enumerable: true,
  8082. configurable: true
  8083. });
  8084. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8085. get: function () {
  8086. return Engine._ALPHA_SUBTRACT;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8092. get: function () {
  8093. return Engine._ALPHA_MULTIPLY;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8099. get: function () {
  8100. return Engine._ALPHA_MAXIMIZED;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8106. get: function () {
  8107. return Engine._ALPHA_PREMULTIPLIED;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8113. get: function () {
  8114. return Engine._DELAYLOADSTATE_NONE;
  8115. },
  8116. enumerable: true,
  8117. configurable: true
  8118. });
  8119. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8120. get: function () {
  8121. return Engine._DELAYLOADSTATE_LOADED;
  8122. },
  8123. enumerable: true,
  8124. configurable: true
  8125. });
  8126. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8127. get: function () {
  8128. return Engine._DELAYLOADSTATE_LOADING;
  8129. },
  8130. enumerable: true,
  8131. configurable: true
  8132. });
  8133. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8134. get: function () {
  8135. return Engine._DELAYLOADSTATE_NOTLOADED;
  8136. },
  8137. enumerable: true,
  8138. configurable: true
  8139. });
  8140. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8141. get: function () {
  8142. return Engine._TEXTUREFORMAT_ALPHA;
  8143. },
  8144. enumerable: true,
  8145. configurable: true
  8146. });
  8147. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8148. get: function () {
  8149. return Engine._TEXTUREFORMAT_LUMINANCE;
  8150. },
  8151. enumerable: true,
  8152. configurable: true
  8153. });
  8154. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8155. get: function () {
  8156. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8157. },
  8158. enumerable: true,
  8159. configurable: true
  8160. });
  8161. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8162. get: function () {
  8163. return Engine._TEXTUREFORMAT_RGB;
  8164. },
  8165. enumerable: true,
  8166. configurable: true
  8167. });
  8168. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8169. get: function () {
  8170. return Engine._TEXTUREFORMAT_RGBA;
  8171. },
  8172. enumerable: true,
  8173. configurable: true
  8174. });
  8175. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8176. get: function () {
  8177. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8178. },
  8179. enumerable: true,
  8180. configurable: true
  8181. });
  8182. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8183. get: function () {
  8184. return Engine._TEXTURETYPE_FLOAT;
  8185. },
  8186. enumerable: true,
  8187. configurable: true
  8188. });
  8189. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8190. get: function () {
  8191. return Engine._TEXTURETYPE_HALF_FLOAT;
  8192. },
  8193. enumerable: true,
  8194. configurable: true
  8195. });
  8196. Object.defineProperty(Engine, "Version", {
  8197. get: function () {
  8198. return "2.6-alpha";
  8199. },
  8200. enumerable: true,
  8201. configurable: true
  8202. });
  8203. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8204. get: function () {
  8205. return this._texturesSupported;
  8206. },
  8207. enumerable: true,
  8208. configurable: true
  8209. });
  8210. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8211. get: function () {
  8212. return this._textureFormatInUse;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8218. get: function () {
  8219. return this._webGLVersion;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8225. /**
  8226. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8227. */
  8228. get: function () {
  8229. return this._isStencilEnable;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Engine.prototype._prepareWorkingCanvas = function () {
  8235. if (this._workingCanvas) {
  8236. return;
  8237. }
  8238. this._workingCanvas = document.createElement("canvas");
  8239. this._workingContext = this._workingCanvas.getContext("2d");
  8240. };
  8241. Engine.prototype.resetTextureCache = function () {
  8242. for (var index = 0; index < this._maxTextureChannels; index++) {
  8243. this._activeTexturesCache[index] = null;
  8244. }
  8245. };
  8246. Engine.prototype.getGlInfo = function () {
  8247. return {
  8248. vendor: this._glVendor,
  8249. renderer: this._glRenderer,
  8250. version: this._glVersion
  8251. };
  8252. };
  8253. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8254. if (useScreen === void 0) { useScreen = false; }
  8255. var viewport = camera.viewport;
  8256. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8257. };
  8258. Engine.prototype.getRenderWidth = function (useScreen) {
  8259. if (useScreen === void 0) { useScreen = false; }
  8260. if (!useScreen && this._currentRenderTarget) {
  8261. return this._currentRenderTarget._width;
  8262. }
  8263. return this._renderingCanvas.width;
  8264. };
  8265. Engine.prototype.getRenderHeight = function (useScreen) {
  8266. if (useScreen === void 0) { useScreen = false; }
  8267. if (!useScreen && this._currentRenderTarget) {
  8268. return this._currentRenderTarget._height;
  8269. }
  8270. return this._renderingCanvas.height;
  8271. };
  8272. Engine.prototype.getRenderingCanvas = function () {
  8273. return this._renderingCanvas;
  8274. };
  8275. Engine.prototype.getRenderingCanvasClientRect = function () {
  8276. return this._renderingCanvas.getBoundingClientRect();
  8277. };
  8278. Engine.prototype.setHardwareScalingLevel = function (level) {
  8279. this._hardwareScalingLevel = level;
  8280. this.resize();
  8281. };
  8282. Engine.prototype.getHardwareScalingLevel = function () {
  8283. return this._hardwareScalingLevel;
  8284. };
  8285. Engine.prototype.getLoadedTexturesCache = function () {
  8286. return this._loadedTexturesCache;
  8287. };
  8288. Engine.prototype.getCaps = function () {
  8289. return this._caps;
  8290. };
  8291. Object.defineProperty(Engine.prototype, "drawCalls", {
  8292. get: function () {
  8293. return this._drawCalls.current;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8299. get: function () {
  8300. return this._drawCalls;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Engine.prototype.getDepthFunction = function () {
  8306. return this._depthCullingState.depthFunc;
  8307. };
  8308. Engine.prototype.setDepthFunction = function (depthFunc) {
  8309. this._depthCullingState.depthFunc = depthFunc;
  8310. };
  8311. Engine.prototype.setDepthFunctionToGreater = function () {
  8312. this._depthCullingState.depthFunc = this._gl.GREATER;
  8313. };
  8314. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8315. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8316. };
  8317. Engine.prototype.setDepthFunctionToLess = function () {
  8318. this._depthCullingState.depthFunc = this._gl.LESS;
  8319. };
  8320. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8321. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8322. };
  8323. Engine.prototype.getStencilBuffer = function () {
  8324. return this._stencilState.stencilTest;
  8325. };
  8326. Engine.prototype.setStencilBuffer = function (enable) {
  8327. this._stencilState.stencilTest = enable;
  8328. };
  8329. Engine.prototype.getStencilMask = function () {
  8330. return this._stencilState.stencilMask;
  8331. };
  8332. Engine.prototype.setStencilMask = function (mask) {
  8333. this._stencilState.stencilMask = mask;
  8334. };
  8335. Engine.prototype.getStencilFunction = function () {
  8336. return this._stencilState.stencilFunc;
  8337. };
  8338. Engine.prototype.getStencilFunctionReference = function () {
  8339. return this._stencilState.stencilFuncRef;
  8340. };
  8341. Engine.prototype.getStencilFunctionMask = function () {
  8342. return this._stencilState.stencilFuncMask;
  8343. };
  8344. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8345. this._stencilState.stencilFunc = stencilFunc;
  8346. };
  8347. Engine.prototype.setStencilFunctionReference = function (reference) {
  8348. this._stencilState.stencilFuncRef = reference;
  8349. };
  8350. Engine.prototype.setStencilFunctionMask = function (mask) {
  8351. this._stencilState.stencilFuncMask = mask;
  8352. };
  8353. Engine.prototype.getStencilOperationFail = function () {
  8354. return this._stencilState.stencilOpStencilFail;
  8355. };
  8356. Engine.prototype.getStencilOperationDepthFail = function () {
  8357. return this._stencilState.stencilOpDepthFail;
  8358. };
  8359. Engine.prototype.getStencilOperationPass = function () {
  8360. return this._stencilState.stencilOpStencilDepthPass;
  8361. };
  8362. Engine.prototype.setStencilOperationFail = function (operation) {
  8363. this._stencilState.stencilOpStencilFail = operation;
  8364. };
  8365. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8366. this._stencilState.stencilOpDepthFail = operation;
  8367. };
  8368. Engine.prototype.setStencilOperationPass = function (operation) {
  8369. this._stencilState.stencilOpStencilDepthPass = operation;
  8370. };
  8371. /**
  8372. * stop executing a render loop function and remove it from the execution array
  8373. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8374. */
  8375. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8376. if (!renderFunction) {
  8377. this._activeRenderLoops = [];
  8378. return;
  8379. }
  8380. var index = this._activeRenderLoops.indexOf(renderFunction);
  8381. if (index >= 0) {
  8382. this._activeRenderLoops.splice(index, 1);
  8383. }
  8384. };
  8385. Engine.prototype._renderLoop = function () {
  8386. var shouldRender = true;
  8387. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8388. shouldRender = false;
  8389. }
  8390. if (shouldRender) {
  8391. // Start new frame
  8392. this.beginFrame();
  8393. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8394. var renderFunction = this._activeRenderLoops[index];
  8395. renderFunction();
  8396. }
  8397. // Present
  8398. this.endFrame();
  8399. }
  8400. if (this._activeRenderLoops.length > 0) {
  8401. // Register new frame
  8402. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8403. }
  8404. else {
  8405. this._renderingQueueLaunched = false;
  8406. }
  8407. };
  8408. /**
  8409. * Register and execute a render loop. The engine can have more than one render function.
  8410. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8411. * @example
  8412. * engine.runRenderLoop(function () {
  8413. * scene.render()
  8414. * })
  8415. */
  8416. Engine.prototype.runRenderLoop = function (renderFunction) {
  8417. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8418. return;
  8419. }
  8420. this._activeRenderLoops.push(renderFunction);
  8421. if (!this._renderingQueueLaunched) {
  8422. this._renderingQueueLaunched = true;
  8423. this._bindedRenderFunction = this._renderLoop.bind(this);
  8424. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8425. }
  8426. };
  8427. /**
  8428. * Toggle full screen mode.
  8429. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8430. * @param {any} options - an options object to be sent to the requestFullscreen function
  8431. */
  8432. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8433. if (this.isFullscreen) {
  8434. BABYLON.Tools.ExitFullscreen();
  8435. }
  8436. else {
  8437. this._pointerLockRequested = requestPointerLock;
  8438. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8439. }
  8440. };
  8441. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8442. if (stencil === void 0) { stencil = false; }
  8443. this.applyStates();
  8444. var mode = 0;
  8445. if (backBuffer && color) {
  8446. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8447. mode |= this._gl.COLOR_BUFFER_BIT;
  8448. }
  8449. if (depth) {
  8450. this._gl.clearDepth(1.0);
  8451. mode |= this._gl.DEPTH_BUFFER_BIT;
  8452. }
  8453. if (stencil) {
  8454. this._gl.clearStencil(0);
  8455. mode |= this._gl.STENCIL_BUFFER_BIT;
  8456. }
  8457. this._gl.clear(mode);
  8458. };
  8459. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8460. var gl = this._gl;
  8461. // Save state
  8462. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8463. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8464. // Change state
  8465. gl.enable(gl.SCISSOR_TEST);
  8466. gl.scissor(x, y, width, height);
  8467. // Clear
  8468. this.clear(clearColor, true, true, true);
  8469. // Restore state
  8470. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8471. if (curScissor === true) {
  8472. gl.enable(gl.SCISSOR_TEST);
  8473. }
  8474. else {
  8475. gl.disable(gl.SCISSOR_TEST);
  8476. }
  8477. };
  8478. /**
  8479. * Set the WebGL's viewport
  8480. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8481. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8482. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8483. */
  8484. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8485. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8486. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8487. var x = viewport.x || 0;
  8488. var y = viewport.y || 0;
  8489. this._cachedViewport = viewport;
  8490. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8491. };
  8492. /**
  8493. * Directly set the WebGL Viewport
  8494. * The x, y, width & height are directly passed to the WebGL call
  8495. * @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.
  8496. */
  8497. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8498. var currentViewport = this._cachedViewport;
  8499. this._cachedViewport = null;
  8500. this._gl.viewport(x, y, width, height);
  8501. return currentViewport;
  8502. };
  8503. Engine.prototype.beginFrame = function () {
  8504. this._measureFps();
  8505. };
  8506. Engine.prototype.endFrame = function () {
  8507. //force a flush in case we are using a bad OS.
  8508. if (this._badOS) {
  8509. this.flushFramebuffer();
  8510. }
  8511. //submit frame to the vr device, if enabled
  8512. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8513. this._vrDisplayEnabled.submitFrame();
  8514. }
  8515. };
  8516. /**
  8517. * resize the view according to the canvas' size.
  8518. * @example
  8519. * window.addEventListener("resize", function () {
  8520. * engine.resize();
  8521. * });
  8522. */
  8523. Engine.prototype.resize = function () {
  8524. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8525. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8526. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8527. };
  8528. /**
  8529. * force a specific size of the canvas
  8530. * @param {number} width - the new canvas' width
  8531. * @param {number} height - the new canvas' height
  8532. */
  8533. Engine.prototype.setSize = function (width, height) {
  8534. this._renderingCanvas.width = width;
  8535. this._renderingCanvas.height = height;
  8536. for (var index = 0; index < this.scenes.length; index++) {
  8537. var scene = this.scenes[index];
  8538. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8539. var cam = scene.cameras[camIndex];
  8540. cam._currentRenderId = 0;
  8541. }
  8542. }
  8543. };
  8544. //WebVR functions
  8545. Engine.prototype.initWebVR = function () {
  8546. if (!this.vrDisplaysPromise) {
  8547. this._getVRDisplays();
  8548. }
  8549. };
  8550. Engine.prototype.enableVR = function (vrDevice) {
  8551. this._vrDisplayEnabled = vrDevice;
  8552. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8553. };
  8554. Engine.prototype.disableVR = function () {
  8555. if (this._vrDisplayEnabled) {
  8556. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8557. }
  8558. };
  8559. Engine.prototype._getVRDisplays = function () {
  8560. var _this = this;
  8561. var getWebVRDevices = function (devices) {
  8562. var size = devices.length;
  8563. var i = 0;
  8564. _this._vrDisplays = devices.filter(function (device) {
  8565. return devices[i] instanceof VRDisplay;
  8566. });
  8567. return _this._vrDisplays;
  8568. };
  8569. //using a key due to typescript
  8570. if (navigator.getVRDisplays) {
  8571. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8572. }
  8573. };
  8574. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8575. this._currentRenderTarget = texture;
  8576. this.bindUnboundFramebuffer(texture._framebuffer);
  8577. var gl = this._gl;
  8578. if (texture.isCube) {
  8579. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8580. }
  8581. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8582. this.wipeCaches();
  8583. };
  8584. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8585. if (this._currentFramebuffer !== framebuffer) {
  8586. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8587. this._currentFramebuffer = framebuffer;
  8588. }
  8589. };
  8590. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  8591. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8592. this._currentRenderTarget = null;
  8593. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8594. var gl = this._gl;
  8595. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8596. gl.generateMipmap(gl.TEXTURE_2D);
  8597. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8598. }
  8599. this.bindUnboundFramebuffer(null);
  8600. };
  8601. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8602. if (texture.generateMipMaps) {
  8603. var gl = this._gl;
  8604. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8605. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8606. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8607. }
  8608. };
  8609. Engine.prototype.flushFramebuffer = function () {
  8610. this._gl.flush();
  8611. };
  8612. Engine.prototype.restoreDefaultFramebuffer = function () {
  8613. this._currentRenderTarget = null;
  8614. this.bindUnboundFramebuffer(null);
  8615. this.setViewport(this._cachedViewport);
  8616. this.wipeCaches();
  8617. };
  8618. // VBOs
  8619. Engine.prototype._resetVertexBufferBinding = function () {
  8620. this.bindArrayBuffer(null);
  8621. this._cachedVertexBuffers = null;
  8622. };
  8623. Engine.prototype.createVertexBuffer = function (vertices) {
  8624. var vbo = this._gl.createBuffer();
  8625. this.bindArrayBuffer(vbo);
  8626. if (vertices instanceof Float32Array) {
  8627. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8628. }
  8629. else {
  8630. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8631. }
  8632. this._resetVertexBufferBinding();
  8633. vbo.references = 1;
  8634. return vbo;
  8635. };
  8636. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8637. var vbo = this._gl.createBuffer();
  8638. this.bindArrayBuffer(vbo);
  8639. if (vertices instanceof Float32Array) {
  8640. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8641. }
  8642. else {
  8643. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8644. }
  8645. this._resetVertexBufferBinding();
  8646. vbo.references = 1;
  8647. return vbo;
  8648. };
  8649. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8650. this.bindArrayBuffer(vertexBuffer);
  8651. if (offset === undefined) {
  8652. offset = 0;
  8653. }
  8654. if (count === undefined) {
  8655. if (vertices instanceof Float32Array) {
  8656. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8657. }
  8658. else {
  8659. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8660. }
  8661. }
  8662. else {
  8663. if (vertices instanceof Float32Array) {
  8664. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8665. }
  8666. else {
  8667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8668. }
  8669. }
  8670. this._resetVertexBufferBinding();
  8671. };
  8672. Engine.prototype._resetIndexBufferBinding = function () {
  8673. this.bindIndexBuffer(null);
  8674. this._cachedIndexBuffer = null;
  8675. };
  8676. Engine.prototype.createIndexBuffer = function (indices) {
  8677. var vbo = this._gl.createBuffer();
  8678. this.bindIndexBuffer(vbo);
  8679. // Check for 32 bits indices
  8680. var arrayBuffer;
  8681. var need32Bits = false;
  8682. if (indices instanceof Uint16Array) {
  8683. arrayBuffer = indices;
  8684. }
  8685. else {
  8686. //check 32 bit support
  8687. if (this._caps.uintIndices) {
  8688. if (indices instanceof Uint32Array) {
  8689. arrayBuffer = indices;
  8690. need32Bits = true;
  8691. }
  8692. else {
  8693. //number[] or Int32Array, check if 32 bit is necessary
  8694. for (var index = 0; index < indices.length; index++) {
  8695. if (indices[index] > 65535) {
  8696. need32Bits = true;
  8697. break;
  8698. }
  8699. }
  8700. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8701. }
  8702. }
  8703. else {
  8704. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8705. arrayBuffer = new Uint16Array(indices);
  8706. }
  8707. }
  8708. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8709. this._resetIndexBufferBinding();
  8710. vbo.references = 1;
  8711. vbo.is32Bits = need32Bits;
  8712. return vbo;
  8713. };
  8714. Engine.prototype.bindArrayBuffer = function (buffer) {
  8715. if (!this._vaoRecordInProgress) {
  8716. this._unBindVertexArrayObject();
  8717. }
  8718. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8719. };
  8720. Engine.prototype.bindIndexBuffer = function (buffer) {
  8721. if (!this._vaoRecordInProgress) {
  8722. this._unBindVertexArrayObject();
  8723. }
  8724. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8725. };
  8726. Engine.prototype.bindBuffer = function (buffer, target) {
  8727. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8728. this._gl.bindBuffer(target, buffer);
  8729. this._currentBoundBuffer[target] = buffer;
  8730. }
  8731. };
  8732. Engine.prototype.updateArrayBuffer = function (data) {
  8733. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8734. };
  8735. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8736. var pointer = this._currentBufferPointers[indx];
  8737. var changed = false;
  8738. if (!pointer) {
  8739. changed = true;
  8740. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8741. }
  8742. else {
  8743. if (pointer.buffer !== buffer) {
  8744. pointer.buffer = buffer;
  8745. changed = true;
  8746. }
  8747. if (pointer.size !== size) {
  8748. pointer.size = size;
  8749. changed = true;
  8750. }
  8751. if (pointer.type !== type) {
  8752. pointer.type = type;
  8753. changed = true;
  8754. }
  8755. if (pointer.normalized !== normalized) {
  8756. pointer.normalized = normalized;
  8757. changed = true;
  8758. }
  8759. if (pointer.stride !== stride) {
  8760. pointer.stride = stride;
  8761. changed = true;
  8762. }
  8763. if (pointer.offset !== offset) {
  8764. pointer.offset = offset;
  8765. changed = true;
  8766. }
  8767. }
  8768. if (changed || this._vaoRecordInProgress) {
  8769. this.bindArrayBuffer(buffer);
  8770. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8771. }
  8772. };
  8773. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8774. if (indexBuffer == null) {
  8775. return;
  8776. }
  8777. if (this._cachedIndexBuffer !== indexBuffer) {
  8778. this._cachedIndexBuffer = indexBuffer;
  8779. this.bindIndexBuffer(indexBuffer);
  8780. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8781. }
  8782. };
  8783. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8784. var attributes = effect.getAttributesNames();
  8785. if (!this._vaoRecordInProgress) {
  8786. this._unBindVertexArrayObject();
  8787. }
  8788. this.unbindAllAttributes();
  8789. for (var index = 0; index < attributes.length; index++) {
  8790. var order = effect.getAttributeLocation(index);
  8791. if (order >= 0) {
  8792. var vertexBuffer = vertexBuffers[attributes[index]];
  8793. if (!vertexBuffer) {
  8794. continue;
  8795. }
  8796. this._gl.enableVertexAttribArray(order);
  8797. if (!this._vaoRecordInProgress) {
  8798. this._vertexAttribArraysEnabled[order] = true;
  8799. }
  8800. var buffer = vertexBuffer.getBuffer();
  8801. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8802. if (vertexBuffer.getIsInstanced()) {
  8803. this._gl.vertexAttribDivisor(order, 1);
  8804. if (!this._vaoRecordInProgress) {
  8805. this._currentInstanceLocations.push(order);
  8806. this._currentInstanceBuffers.push(buffer);
  8807. }
  8808. }
  8809. }
  8810. }
  8811. };
  8812. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8813. var vao = this._gl.createVertexArray();
  8814. this._vaoRecordInProgress = true;
  8815. this._gl.bindVertexArray(vao);
  8816. this._mustWipeVertexAttributes = true;
  8817. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8818. this.bindIndexBuffer(indexBuffer);
  8819. this._vaoRecordInProgress = false;
  8820. this._gl.bindVertexArray(null);
  8821. return vao;
  8822. };
  8823. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8824. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8825. this._cachedVertexArrayObject = vertexArrayObject;
  8826. this._gl.bindVertexArray(vertexArrayObject);
  8827. this._cachedVertexBuffers = null;
  8828. this._cachedIndexBuffer = null;
  8829. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8830. this._mustWipeVertexAttributes = true;
  8831. }
  8832. };
  8833. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8834. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8835. this._cachedVertexBuffers = vertexBuffer;
  8836. this._cachedEffectForVertexBuffers = effect;
  8837. var attributesCount = effect.getAttributesCount();
  8838. this._unBindVertexArrayObject();
  8839. this.unbindAllAttributes();
  8840. var offset = 0;
  8841. for (var index = 0; index < attributesCount; index++) {
  8842. if (index < vertexDeclaration.length) {
  8843. var order = effect.getAttributeLocation(index);
  8844. if (order >= 0) {
  8845. this._gl.enableVertexAttribArray(order);
  8846. this._vertexAttribArraysEnabled[order] = true;
  8847. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8848. }
  8849. offset += vertexDeclaration[index] * 4;
  8850. }
  8851. }
  8852. }
  8853. this._bindIndexBufferWithCache(indexBuffer);
  8854. };
  8855. Engine.prototype._unBindVertexArrayObject = function () {
  8856. if (!this._cachedVertexArrayObject) {
  8857. return;
  8858. }
  8859. this._cachedVertexArrayObject = null;
  8860. this._gl.bindVertexArray(null);
  8861. };
  8862. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8863. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8864. this._cachedVertexBuffers = vertexBuffers;
  8865. this._cachedEffectForVertexBuffers = effect;
  8866. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8867. }
  8868. this._bindIndexBufferWithCache(indexBuffer);
  8869. };
  8870. Engine.prototype.unbindInstanceAttributes = function () {
  8871. var boundBuffer;
  8872. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8873. var instancesBuffer = this._currentInstanceBuffers[i];
  8874. if (boundBuffer != instancesBuffer) {
  8875. boundBuffer = instancesBuffer;
  8876. this.bindArrayBuffer(instancesBuffer);
  8877. }
  8878. var offsetLocation = this._currentInstanceLocations[i];
  8879. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8880. }
  8881. this._currentInstanceBuffers.length = 0;
  8882. this._currentInstanceLocations.length = 0;
  8883. };
  8884. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8885. this._gl.deleteVertexArray(vao);
  8886. };
  8887. Engine.prototype._releaseBuffer = function (buffer) {
  8888. buffer.references--;
  8889. if (buffer.references === 0) {
  8890. this._gl.deleteBuffer(buffer);
  8891. return true;
  8892. }
  8893. return false;
  8894. };
  8895. Engine.prototype.createInstancesBuffer = function (capacity) {
  8896. var buffer = this._gl.createBuffer();
  8897. buffer.capacity = capacity;
  8898. this.bindArrayBuffer(buffer);
  8899. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8900. return buffer;
  8901. };
  8902. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8903. this._gl.deleteBuffer(buffer);
  8904. };
  8905. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8906. this.bindArrayBuffer(instancesBuffer);
  8907. if (data) {
  8908. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8909. }
  8910. if (offsetLocations[0].index !== undefined) {
  8911. var stride = 0;
  8912. for (var i = 0; i < offsetLocations.length; i++) {
  8913. var ai = offsetLocations[i];
  8914. stride += ai.attributeSize * 4;
  8915. }
  8916. for (var i = 0; i < offsetLocations.length; i++) {
  8917. var ai = offsetLocations[i];
  8918. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8919. this._gl.enableVertexAttribArray(ai.index);
  8920. this._vertexAttribArraysEnabled[ai.index] = true;
  8921. }
  8922. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8923. this._gl.vertexAttribDivisor(ai.index, 1);
  8924. this._currentInstanceLocations.push(ai.index);
  8925. this._currentInstanceBuffers.push(instancesBuffer);
  8926. }
  8927. }
  8928. else {
  8929. for (var index = 0; index < 4; index++) {
  8930. var offsetLocation = offsetLocations[index];
  8931. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8932. this._gl.enableVertexAttribArray(offsetLocation);
  8933. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8934. }
  8935. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8936. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8937. this._currentInstanceLocations.push(offsetLocation);
  8938. this._currentInstanceBuffers.push(instancesBuffer);
  8939. }
  8940. }
  8941. };
  8942. Engine.prototype.applyStates = function () {
  8943. this._depthCullingState.apply(this._gl);
  8944. this._stencilState.apply(this._gl);
  8945. this._alphaState.apply(this._gl);
  8946. };
  8947. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8948. // Apply states
  8949. this.applyStates();
  8950. this._drawCalls.addCount(1, false);
  8951. // Render
  8952. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8953. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8954. if (instancesCount) {
  8955. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8956. return;
  8957. }
  8958. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8959. };
  8960. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8961. // Apply states
  8962. this.applyStates();
  8963. this._drawCalls.addCount(1, false);
  8964. if (instancesCount) {
  8965. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8966. return;
  8967. }
  8968. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8969. };
  8970. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8971. // Apply states
  8972. this.applyStates();
  8973. this._drawCalls.addCount(1, false);
  8974. if (instancesCount) {
  8975. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8976. return;
  8977. }
  8978. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8979. };
  8980. // Shaders
  8981. Engine.prototype._releaseEffect = function (effect) {
  8982. if (this._compiledEffects[effect._key]) {
  8983. delete this._compiledEffects[effect._key];
  8984. if (effect.getProgram()) {
  8985. this._gl.deleteProgram(effect.getProgram());
  8986. }
  8987. }
  8988. };
  8989. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8990. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8991. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8992. var name = vertex + "+" + fragment + "@" + defines;
  8993. if (this._compiledEffects[name]) {
  8994. return this._compiledEffects[name];
  8995. }
  8996. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8997. effect._key = name;
  8998. this._compiledEffects[name] = effect;
  8999. return effect;
  9000. };
  9001. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9002. if (uniformsNames === void 0) { uniformsNames = []; }
  9003. if (samplers === void 0) { samplers = []; }
  9004. if (defines === void 0) { defines = ""; }
  9005. return this.createEffect({
  9006. vertex: "particles",
  9007. fragmentElement: fragmentName
  9008. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9009. };
  9010. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9011. context = context || this._gl;
  9012. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9013. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9014. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9015. var shaderProgram = context.createProgram();
  9016. context.attachShader(shaderProgram, vertexShader);
  9017. context.attachShader(shaderProgram, fragmentShader);
  9018. context.linkProgram(shaderProgram);
  9019. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9020. if (!linked) {
  9021. var error = context.getProgramInfoLog(shaderProgram);
  9022. if (error) {
  9023. throw new Error(error);
  9024. }
  9025. }
  9026. context.deleteShader(vertexShader);
  9027. context.deleteShader(fragmentShader);
  9028. return shaderProgram;
  9029. };
  9030. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9031. var results = [];
  9032. for (var index = 0; index < uniformsNames.length; index++) {
  9033. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9034. }
  9035. return results;
  9036. };
  9037. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9038. var results = [];
  9039. for (var index = 0; index < attributesNames.length; index++) {
  9040. try {
  9041. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9042. }
  9043. catch (e) {
  9044. results.push(-1);
  9045. }
  9046. }
  9047. return results;
  9048. };
  9049. Engine.prototype.enableEffect = function (effect) {
  9050. // Use program
  9051. this.setProgram(effect.getProgram());
  9052. this._currentEffect = effect;
  9053. if (effect.onBind) {
  9054. effect.onBind(effect);
  9055. }
  9056. };
  9057. Engine.prototype.setIntArray = function (uniform, array) {
  9058. if (!uniform)
  9059. return;
  9060. this._gl.uniform1iv(uniform, array);
  9061. };
  9062. Engine.prototype.setIntArray2 = function (uniform, array) {
  9063. if (!uniform || array.length % 2 !== 0)
  9064. return;
  9065. this._gl.uniform2iv(uniform, array);
  9066. };
  9067. Engine.prototype.setIntArray3 = function (uniform, array) {
  9068. if (!uniform || array.length % 3 !== 0)
  9069. return;
  9070. this._gl.uniform3iv(uniform, array);
  9071. };
  9072. Engine.prototype.setIntArray4 = function (uniform, array) {
  9073. if (!uniform || array.length % 4 !== 0)
  9074. return;
  9075. this._gl.uniform4iv(uniform, array);
  9076. };
  9077. Engine.prototype.setFloatArray = function (uniform, array) {
  9078. if (!uniform)
  9079. return;
  9080. this._gl.uniform1fv(uniform, array);
  9081. };
  9082. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9083. if (!uniform || array.length % 2 !== 0)
  9084. return;
  9085. this._gl.uniform2fv(uniform, array);
  9086. };
  9087. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9088. if (!uniform || array.length % 3 !== 0)
  9089. return;
  9090. this._gl.uniform3fv(uniform, array);
  9091. };
  9092. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9093. if (!uniform || array.length % 4 !== 0)
  9094. return;
  9095. this._gl.uniform4fv(uniform, array);
  9096. };
  9097. Engine.prototype.setArray = function (uniform, array) {
  9098. if (!uniform)
  9099. return;
  9100. this._gl.uniform1fv(uniform, array);
  9101. };
  9102. Engine.prototype.setArray2 = function (uniform, array) {
  9103. if (!uniform || array.length % 2 !== 0)
  9104. return;
  9105. this._gl.uniform2fv(uniform, array);
  9106. };
  9107. Engine.prototype.setArray3 = function (uniform, array) {
  9108. if (!uniform || array.length % 3 !== 0)
  9109. return;
  9110. this._gl.uniform3fv(uniform, array);
  9111. };
  9112. Engine.prototype.setArray4 = function (uniform, array) {
  9113. if (!uniform || array.length % 4 !== 0)
  9114. return;
  9115. this._gl.uniform4fv(uniform, array);
  9116. };
  9117. Engine.prototype.setMatrices = function (uniform, matrices) {
  9118. if (!uniform)
  9119. return;
  9120. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9121. };
  9122. Engine.prototype.setMatrix = function (uniform, matrix) {
  9123. if (!uniform)
  9124. return;
  9125. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9126. };
  9127. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9128. if (!uniform)
  9129. return;
  9130. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9131. };
  9132. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9133. if (!uniform)
  9134. return;
  9135. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9136. };
  9137. Engine.prototype.setFloat = function (uniform, value) {
  9138. if (!uniform)
  9139. return;
  9140. this._gl.uniform1f(uniform, value);
  9141. };
  9142. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9143. if (!uniform)
  9144. return;
  9145. this._gl.uniform2f(uniform, x, y);
  9146. };
  9147. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9148. if (!uniform)
  9149. return;
  9150. this._gl.uniform3f(uniform, x, y, z);
  9151. };
  9152. Engine.prototype.setBool = function (uniform, bool) {
  9153. if (!uniform)
  9154. return;
  9155. this._gl.uniform1i(uniform, bool);
  9156. };
  9157. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9158. if (!uniform)
  9159. return;
  9160. this._gl.uniform4f(uniform, x, y, z, w);
  9161. };
  9162. Engine.prototype.setColor3 = function (uniform, color3) {
  9163. if (!uniform)
  9164. return;
  9165. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9166. };
  9167. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9168. if (!uniform)
  9169. return;
  9170. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9171. };
  9172. // States
  9173. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9174. if (zOffset === void 0) { zOffset = 0; }
  9175. if (reverseSide === void 0) { reverseSide = false; }
  9176. // Culling
  9177. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9178. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9179. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9180. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9181. if (culling) {
  9182. this._depthCullingState.cullFace = cullFace;
  9183. this._depthCullingState.cull = true;
  9184. }
  9185. else {
  9186. this._depthCullingState.cull = false;
  9187. }
  9188. }
  9189. // Z offset
  9190. this._depthCullingState.zOffset = zOffset;
  9191. };
  9192. Engine.prototype.setDepthBuffer = function (enable) {
  9193. this._depthCullingState.depthTest = enable;
  9194. };
  9195. Engine.prototype.getDepthWrite = function () {
  9196. return this._depthCullingState.depthMask;
  9197. };
  9198. Engine.prototype.setDepthWrite = function (enable) {
  9199. this._depthCullingState.depthMask = enable;
  9200. };
  9201. Engine.prototype.setColorWrite = function (enable) {
  9202. this._gl.colorMask(enable, enable, enable, enable);
  9203. };
  9204. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9205. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9206. if (this._alphaMode === mode) {
  9207. return;
  9208. }
  9209. switch (mode) {
  9210. case Engine.ALPHA_DISABLE:
  9211. this._alphaState.alphaBlend = false;
  9212. break;
  9213. case Engine.ALPHA_PREMULTIPLIED:
  9214. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9215. this._alphaState.alphaBlend = true;
  9216. break;
  9217. case Engine.ALPHA_COMBINE:
  9218. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9219. this._alphaState.alphaBlend = true;
  9220. break;
  9221. case Engine.ALPHA_ONEONE:
  9222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9223. this._alphaState.alphaBlend = true;
  9224. break;
  9225. case Engine.ALPHA_ADD:
  9226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9227. this._alphaState.alphaBlend = true;
  9228. break;
  9229. case Engine.ALPHA_SUBTRACT:
  9230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9231. this._alphaState.alphaBlend = true;
  9232. break;
  9233. case Engine.ALPHA_MULTIPLY:
  9234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9235. this._alphaState.alphaBlend = true;
  9236. break;
  9237. case Engine.ALPHA_MAXIMIZED:
  9238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9239. this._alphaState.alphaBlend = true;
  9240. break;
  9241. }
  9242. if (!noDepthWriteChange) {
  9243. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9244. }
  9245. this._alphaMode = mode;
  9246. };
  9247. Engine.prototype.getAlphaMode = function () {
  9248. return this._alphaMode;
  9249. };
  9250. Engine.prototype.setAlphaTesting = function (enable) {
  9251. this._alphaTest = enable;
  9252. };
  9253. Engine.prototype.getAlphaTesting = function () {
  9254. return this._alphaTest;
  9255. };
  9256. // Textures
  9257. Engine.prototype.wipeCaches = function () {
  9258. this.resetTextureCache();
  9259. this._currentEffect = null;
  9260. this._stencilState.reset();
  9261. this._depthCullingState.reset();
  9262. this.setDepthFunctionToLessOrEqual();
  9263. this._alphaState.reset();
  9264. this._cachedVertexBuffers = null;
  9265. this._cachedIndexBuffer = null;
  9266. this._cachedEffectForVertexBuffers = null;
  9267. this._unBindVertexArrayObject();
  9268. this.bindIndexBuffer(null);
  9269. this.bindArrayBuffer(null);
  9270. };
  9271. /**
  9272. * Set the compressed texture format to use, based on the formats you have, and the formats
  9273. * supported by the hardware / browser.
  9274. *
  9275. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9276. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9277. * to API arguments needed to compressed textures. This puts the burden on the container
  9278. * generator to house the arcane code for determining these for current & future formats.
  9279. *
  9280. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9281. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9282. *
  9283. * Note: The result of this call is not taken into account when a texture is base64.
  9284. *
  9285. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9286. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9287. *
  9288. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9289. * @returns The extension selected.
  9290. */
  9291. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9292. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9293. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9294. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9295. return this._textureFormatInUse = this._texturesSupported[i];
  9296. }
  9297. }
  9298. }
  9299. // actively set format to nothing, to allow this to be called more than once
  9300. // and possibly fail the 2nd time
  9301. return this._textureFormatInUse = null;
  9302. };
  9303. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9304. var _this = this;
  9305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9306. if (onLoad === void 0) { onLoad = null; }
  9307. if (onError === void 0) { onError = null; }
  9308. if (buffer === void 0) { buffer = null; }
  9309. var texture = fallBack ? fallBack : this._gl.createTexture();
  9310. var extension;
  9311. var isKTX = false;
  9312. var fromData = false;
  9313. var url = String(urlArg);
  9314. if (url.substr(0, 5) === "data:") {
  9315. fromData = true;
  9316. }
  9317. if (!fromData) {
  9318. var lastDot = url.lastIndexOf('.');
  9319. extension = url.substring(lastDot).toLowerCase();
  9320. if (this._textureFormatInUse && !fromData && !fallBack) {
  9321. extension = this._textureFormatInUse;
  9322. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9323. isKTX = true;
  9324. }
  9325. }
  9326. else {
  9327. var oldUrl = url;
  9328. fromData = oldUrl.split(':');
  9329. url = oldUrl;
  9330. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9331. }
  9332. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9333. var isTGA = (extension === ".tga");
  9334. scene._addPendingData(texture);
  9335. texture.url = url;
  9336. texture.noMipmap = noMipmap;
  9337. texture.references = 1;
  9338. texture.samplingMode = samplingMode;
  9339. texture.onLoadedCallbacks = [];
  9340. if (onLoad) {
  9341. texture.onLoadedCallbacks.push(onLoad);
  9342. }
  9343. if (!fallBack)
  9344. this._loadedTexturesCache.push(texture);
  9345. var onerror = function () {
  9346. scene._removePendingData(texture);
  9347. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9348. if (isKTX) {
  9349. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9350. }
  9351. else if (onError) {
  9352. onError();
  9353. }
  9354. };
  9355. var callback;
  9356. if (isKTX || isTGA || isDDS) {
  9357. if (isKTX) {
  9358. callback = function (data) {
  9359. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9360. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9361. ktx.uploadLevels(_this._gl, !noMipmap);
  9362. }, samplingMode);
  9363. };
  9364. }
  9365. else if (isTGA) {
  9366. callback = function (arrayBuffer) {
  9367. var data = new Uint8Array(arrayBuffer);
  9368. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9369. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9370. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9371. }, samplingMode);
  9372. };
  9373. }
  9374. else if (isDDS) {
  9375. callback = function (data) {
  9376. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9377. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9378. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9379. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9380. }, samplingMode);
  9381. };
  9382. }
  9383. if (!(fromData instanceof Array))
  9384. BABYLON.Tools.LoadFile(url, function (data) {
  9385. callback(data);
  9386. }, null, scene.database, true, onerror);
  9387. else
  9388. callback(buffer);
  9389. }
  9390. else {
  9391. var onload = function (img) {
  9392. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9393. var isPot = (img.width === potWidth && img.height === potHeight);
  9394. if (!isPot) {
  9395. _this._prepareWorkingCanvas();
  9396. _this._workingCanvas.width = potWidth;
  9397. _this._workingCanvas.height = potHeight;
  9398. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9399. _this._workingContext.imageSmoothingEnabled = false;
  9400. _this._workingContext.mozImageSmoothingEnabled = false;
  9401. _this._workingContext.oImageSmoothingEnabled = false;
  9402. _this._workingContext.webkitImageSmoothingEnabled = false;
  9403. _this._workingContext.msImageSmoothingEnabled = false;
  9404. }
  9405. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9406. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9407. _this._workingContext.imageSmoothingEnabled = true;
  9408. _this._workingContext.mozImageSmoothingEnabled = true;
  9409. _this._workingContext.oImageSmoothingEnabled = true;
  9410. _this._workingContext.webkitImageSmoothingEnabled = true;
  9411. _this._workingContext.msImageSmoothingEnabled = true;
  9412. }
  9413. }
  9414. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9415. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9416. }, samplingMode);
  9417. };
  9418. if (!(fromData instanceof Array))
  9419. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9420. else
  9421. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9422. }
  9423. return texture;
  9424. };
  9425. Engine.prototype._getInternalFormat = function (format) {
  9426. var internalFormat = this._gl.RGBA;
  9427. switch (format) {
  9428. case Engine.TEXTUREFORMAT_ALPHA:
  9429. internalFormat = this._gl.ALPHA;
  9430. break;
  9431. case Engine.TEXTUREFORMAT_LUMINANCE:
  9432. internalFormat = this._gl.LUMINANCE;
  9433. break;
  9434. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9435. internalFormat = this._gl.LUMINANCE_ALPHA;
  9436. break;
  9437. case Engine.TEXTUREFORMAT_RGB:
  9438. internalFormat = this._gl.RGB;
  9439. break;
  9440. case Engine.TEXTUREFORMAT_RGBA:
  9441. internalFormat = this._gl.RGBA;
  9442. break;
  9443. }
  9444. return internalFormat;
  9445. };
  9446. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9447. if (compression === void 0) { compression = null; }
  9448. var internalFormat = this._getInternalFormat(format);
  9449. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9450. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9451. if (texture._width % 4 !== 0) {
  9452. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9453. }
  9454. if (compression) {
  9455. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9456. }
  9457. else {
  9458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9459. }
  9460. if (texture.generateMipMaps) {
  9461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9462. }
  9463. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9464. this.resetTextureCache();
  9465. texture.isReady = true;
  9466. };
  9467. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9468. if (compression === void 0) { compression = null; }
  9469. var texture = this._gl.createTexture();
  9470. texture._baseWidth = width;
  9471. texture._baseHeight = height;
  9472. texture._width = width;
  9473. texture._height = height;
  9474. texture.references = 1;
  9475. this.updateRawTexture(texture, data, format, invertY, compression);
  9476. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9477. // Filters
  9478. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9479. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9480. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9481. if (generateMipMaps) {
  9482. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9483. }
  9484. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9485. texture.samplingMode = samplingMode;
  9486. this._loadedTexturesCache.push(texture);
  9487. return texture;
  9488. };
  9489. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9490. var texture = this._gl.createTexture();
  9491. texture._baseWidth = width;
  9492. texture._baseHeight = height;
  9493. if (generateMipMaps) {
  9494. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9495. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9496. }
  9497. this.resetTextureCache();
  9498. texture._width = width;
  9499. texture._height = height;
  9500. texture.isReady = false;
  9501. texture.generateMipMaps = generateMipMaps;
  9502. texture.references = 1;
  9503. texture.samplingMode = samplingMode;
  9504. this.updateTextureSamplingMode(samplingMode, texture);
  9505. this._loadedTexturesCache.push(texture);
  9506. return texture;
  9507. };
  9508. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9509. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9510. if (texture.isCube) {
  9511. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9512. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9513. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9514. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9515. }
  9516. else {
  9517. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9518. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9520. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9521. }
  9522. texture.samplingMode = samplingMode;
  9523. };
  9524. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9525. if (premulAlpha === void 0) { premulAlpha = false; }
  9526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9527. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9528. if (premulAlpha) {
  9529. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9530. }
  9531. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9533. if (texture.generateMipMaps) {
  9534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9535. }
  9536. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9537. if (premulAlpha) {
  9538. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9539. }
  9540. this.resetTextureCache();
  9541. texture.isReady = true;
  9542. };
  9543. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9544. if (texture._isDisabled) {
  9545. return;
  9546. }
  9547. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9548. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9549. try {
  9550. // Testing video texture support
  9551. if (this._videoTextureSupported === undefined) {
  9552. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9553. if (this._gl.getError() !== 0) {
  9554. this._videoTextureSupported = false;
  9555. }
  9556. else {
  9557. this._videoTextureSupported = true;
  9558. }
  9559. }
  9560. // Copy video through the current working canvas if video texture is not supported
  9561. if (!this._videoTextureSupported) {
  9562. if (!texture._workingCanvas) {
  9563. texture._workingCanvas = document.createElement("canvas");
  9564. texture._workingContext = texture._workingCanvas.getContext("2d");
  9565. texture._workingCanvas.width = texture._width;
  9566. texture._workingCanvas.height = texture._height;
  9567. }
  9568. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9569. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9570. }
  9571. else {
  9572. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9573. }
  9574. if (texture.generateMipMaps) {
  9575. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9576. }
  9577. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9578. this.resetTextureCache();
  9579. texture.isReady = true;
  9580. }
  9581. catch (ex) {
  9582. // Something unexpected
  9583. // Let's disable the texture
  9584. texture._isDisabled = true;
  9585. }
  9586. };
  9587. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9588. // old version had a "generateMipMaps" arg instead of options.
  9589. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9590. // in the same way, generateDepthBuffer is defaulted to true
  9591. var generateMipMaps = false;
  9592. var generateDepthBuffer = true;
  9593. var generateStencilBuffer = false;
  9594. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9595. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9596. if (options !== undefined) {
  9597. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9598. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9599. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9600. type = options.type === undefined ? type : options.type;
  9601. if (options.samplingMode !== undefined) {
  9602. samplingMode = options.samplingMode;
  9603. }
  9604. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9605. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9606. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9607. }
  9608. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9609. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9610. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9611. }
  9612. }
  9613. var gl = this._gl;
  9614. var texture = gl.createTexture();
  9615. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9616. var width = size.width || size;
  9617. var height = size.height || size;
  9618. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9619. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9620. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9621. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9622. }
  9623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9627. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9628. var depthStencilBuffer;
  9629. // Create the depth/stencil buffer
  9630. if (generateStencilBuffer) {
  9631. depthStencilBuffer = gl.createRenderbuffer();
  9632. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9633. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9634. }
  9635. else if (generateDepthBuffer) {
  9636. depthStencilBuffer = gl.createRenderbuffer();
  9637. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9638. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9639. }
  9640. // Create the framebuffer
  9641. var framebuffer = gl.createFramebuffer();
  9642. this.bindUnboundFramebuffer(framebuffer);
  9643. // Manage attachments
  9644. if (generateStencilBuffer) {
  9645. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9646. }
  9647. else if (generateDepthBuffer) {
  9648. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9649. }
  9650. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9651. if (generateMipMaps) {
  9652. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9653. }
  9654. // Unbind
  9655. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9656. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9657. this.bindUnboundFramebuffer(null);
  9658. texture._framebuffer = framebuffer;
  9659. if (generateDepthBuffer) {
  9660. texture._depthBuffer = depthStencilBuffer;
  9661. }
  9662. texture._baseWidth = width;
  9663. texture._baseHeight = height;
  9664. texture._width = width;
  9665. texture._height = height;
  9666. texture.isReady = true;
  9667. texture.generateMipMaps = generateMipMaps;
  9668. texture.references = 1;
  9669. texture.samplingMode = samplingMode;
  9670. texture.type = type;
  9671. this.resetTextureCache();
  9672. this._loadedTexturesCache.push(texture);
  9673. return texture;
  9674. };
  9675. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9676. var gl = this._gl;
  9677. var texture = gl.createTexture();
  9678. var generateMipMaps = true;
  9679. var generateDepthBuffer = true;
  9680. var generateStencilBuffer = false;
  9681. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9682. if (options !== undefined) {
  9683. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9684. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9685. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9686. if (options.samplingMode !== undefined) {
  9687. samplingMode = options.samplingMode;
  9688. }
  9689. }
  9690. texture.isCube = true;
  9691. texture.references = 1;
  9692. texture.generateMipMaps = generateMipMaps;
  9693. texture.references = 1;
  9694. texture.samplingMode = samplingMode;
  9695. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9696. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9697. for (var face = 0; face < 6; face++) {
  9698. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9699. }
  9700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9704. // Create the depth buffer
  9705. var depthStencilBuffer;
  9706. // Create the depth/stencil buffer
  9707. if (generateStencilBuffer) {
  9708. depthStencilBuffer = gl.createRenderbuffer();
  9709. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9710. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  9711. }
  9712. else if (generateDepthBuffer) {
  9713. depthStencilBuffer = gl.createRenderbuffer();
  9714. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9715. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  9716. }
  9717. // Create the framebuffer
  9718. var framebuffer = gl.createFramebuffer();
  9719. this.bindUnboundFramebuffer(framebuffer);
  9720. // Manage attachments
  9721. if (generateStencilBuffer) {
  9722. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9723. }
  9724. else if (generateDepthBuffer) {
  9725. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9726. }
  9727. // Mipmaps
  9728. if (texture.generateMipMaps) {
  9729. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9730. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9731. }
  9732. // Unbind
  9733. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9734. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9735. this.bindUnboundFramebuffer(null);
  9736. texture._framebuffer = framebuffer;
  9737. if (generateDepthBuffer) {
  9738. texture._depthBuffer = depthStencilBuffer;
  9739. }
  9740. texture._width = size;
  9741. texture._height = size;
  9742. texture.isReady = true;
  9743. this.resetTextureCache();
  9744. this._loadedTexturesCache.push(texture);
  9745. return texture;
  9746. };
  9747. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9748. var _this = this;
  9749. if (onLoad === void 0) { onLoad = null; }
  9750. if (onError === void 0) { onError = null; }
  9751. var gl = this._gl;
  9752. var texture = gl.createTexture();
  9753. texture.isCube = true;
  9754. texture.url = rootUrl;
  9755. texture.references = 1;
  9756. texture.onLoadedCallbacks = [];
  9757. var isKTX = false;
  9758. var lastDot = rootUrl.lastIndexOf('.');
  9759. var extension = rootUrl.substring(lastDot).toLowerCase();
  9760. if (this._textureFormatInUse) {
  9761. extension = this._textureFormatInUse;
  9762. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9763. isKTX = true;
  9764. }
  9765. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9766. if (isKTX) {
  9767. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9768. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9769. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9770. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9771. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9772. ktx.uploadLevels(_this._gl, !noMipmap);
  9773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9777. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9778. _this.resetTextureCache();
  9779. texture._width = ktx.pixelWidth;
  9780. texture._height = ktx.pixelHeight;
  9781. texture.isReady = true;
  9782. }, null, null, true, onError);
  9783. }
  9784. else if (isDDS) {
  9785. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9786. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9787. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9788. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9789. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9790. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9791. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9792. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9793. }
  9794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9798. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9799. _this.resetTextureCache();
  9800. texture._width = info.width;
  9801. texture._height = info.height;
  9802. texture.isReady = true;
  9803. }, null, null, true, onError);
  9804. }
  9805. else {
  9806. cascadeLoad(rootUrl, scene, function (imgs) {
  9807. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9808. var height = width;
  9809. _this._prepareWorkingCanvas();
  9810. _this._workingCanvas.width = width;
  9811. _this._workingCanvas.height = height;
  9812. var faces = [
  9813. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9814. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9815. ];
  9816. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9817. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9818. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9819. for (var index = 0; index < faces.length; index++) {
  9820. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9821. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9822. }
  9823. if (!noMipmap) {
  9824. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9825. }
  9826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9830. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9831. _this.resetTextureCache();
  9832. texture._width = width;
  9833. texture._height = height;
  9834. texture.isReady = true;
  9835. texture.onLoadedCallbacks.forEach(function (callback) {
  9836. callback();
  9837. });
  9838. if (onLoad) {
  9839. onLoad();
  9840. }
  9841. }, files, onError);
  9842. }
  9843. this._loadedTexturesCache.push(texture);
  9844. return texture;
  9845. };
  9846. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9847. texture._width = width;
  9848. texture._height = height;
  9849. texture._size = width * height;
  9850. texture._baseWidth = width;
  9851. texture._baseHeight = height;
  9852. };
  9853. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9854. var _this = this;
  9855. if (onLoad === void 0) { onLoad = null; }
  9856. if (onError === void 0) { onError = null; }
  9857. var gl = this._gl;
  9858. var texture = gl.createTexture();
  9859. scene._addPendingData(texture);
  9860. texture.isCube = true;
  9861. texture.references = 1;
  9862. texture.url = url;
  9863. var textureType = gl.UNSIGNED_BYTE;
  9864. if (type === Engine.TEXTURETYPE_FLOAT) {
  9865. textureType = gl.FLOAT;
  9866. }
  9867. var internalFormat = this._getInternalFormat(format);
  9868. var needConversion = false;
  9869. if (internalFormat === gl.RGB) {
  9870. internalFormat = gl.RGBA;
  9871. needConversion = true;
  9872. }
  9873. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9874. var width = size;
  9875. var height = width;
  9876. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9877. texture._width = width;
  9878. texture._height = height;
  9879. var onerror = function () {
  9880. scene._removePendingData(texture);
  9881. if (onError) {
  9882. onError();
  9883. }
  9884. };
  9885. var internalCallback = function (data) {
  9886. var rgbeDataArrays = callback(data);
  9887. var facesIndex = [
  9888. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9889. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9890. ];
  9891. width = texture._width;
  9892. height = texture._height;
  9893. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9894. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9895. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9896. if (mipmmapGenerator) {
  9897. var arrayTemp = [];
  9898. // Data are known to be in +X +Y +Z -X -Y -Z
  9899. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9900. arrayTemp.push(rgbeDataArrays[0]); // +X
  9901. arrayTemp.push(rgbeDataArrays[3]); // -X
  9902. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9903. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9904. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9905. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9906. var mipData = mipmmapGenerator(arrayTemp);
  9907. // mipData is order in +X -X +Y -Y +Z -Z
  9908. var mipFaces = [0, 2, 4, 1, 3, 5];
  9909. for (var level = 0; level < mipData.length; level++) {
  9910. var mipSize = width >> level;
  9911. for (var mipIndex in mipFaces) {
  9912. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9913. if (needConversion) {
  9914. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9915. }
  9916. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9917. }
  9918. }
  9919. }
  9920. else {
  9921. // Data are known to be in +X +Y +Z -X -Y -Z
  9922. for (var index = 0; index < facesIndex.length; index++) {
  9923. var faceData = rgbeDataArrays[index];
  9924. if (needConversion) {
  9925. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9926. }
  9927. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9928. }
  9929. if (!noMipmap && isPot) {
  9930. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9931. }
  9932. else {
  9933. noMipmap = true;
  9934. }
  9935. }
  9936. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9939. }
  9940. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9943. }
  9944. else {
  9945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9947. }
  9948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9951. texture.isReady = true;
  9952. _this.resetTextureCache();
  9953. scene._removePendingData(texture);
  9954. if (onLoad) {
  9955. onLoad();
  9956. }
  9957. };
  9958. BABYLON.Tools.LoadFile(url, function (data) {
  9959. internalCallback(data);
  9960. }, onerror, scene.database, true);
  9961. return texture;
  9962. };
  9963. ;
  9964. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9965. // Create new RGBA data container.
  9966. var rgbaData;
  9967. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9968. rgbaData = new Float32Array(width * height * 4);
  9969. }
  9970. else {
  9971. rgbaData = new Uint32Array(width * height * 4);
  9972. }
  9973. // Convert each pixel.
  9974. for (var x = 0; x < width; x++) {
  9975. for (var y = 0; y < height; y++) {
  9976. var index = (y * width + x) * 3;
  9977. var newIndex = (y * width + x) * 4;
  9978. // Map Old Value to new value.
  9979. rgbaData[newIndex + 0] = rgbData[index + 0];
  9980. rgbaData[newIndex + 1] = rgbData[index + 1];
  9981. rgbaData[newIndex + 2] = rgbData[index + 2];
  9982. // Add fully opaque alpha channel.
  9983. rgbaData[newIndex + 3] = 1;
  9984. }
  9985. }
  9986. return rgbaData;
  9987. };
  9988. Engine.prototype._releaseTexture = function (texture) {
  9989. var gl = this._gl;
  9990. if (texture._framebuffer) {
  9991. gl.deleteFramebuffer(texture._framebuffer);
  9992. }
  9993. if (texture._depthBuffer) {
  9994. gl.deleteRenderbuffer(texture._depthBuffer);
  9995. }
  9996. gl.deleteTexture(texture);
  9997. // Unbind channels
  9998. this.unbindAllTextures();
  9999. var index = this._loadedTexturesCache.indexOf(texture);
  10000. if (index !== -1) {
  10001. this._loadedTexturesCache.splice(index, 1);
  10002. }
  10003. };
  10004. Engine.prototype.setProgram = function (program) {
  10005. if (this._currentProgram !== program) {
  10006. this._gl.useProgram(program);
  10007. this._currentProgram = program;
  10008. }
  10009. };
  10010. Engine.prototype.bindSamplers = function (effect) {
  10011. this.setProgram(effect.getProgram());
  10012. var samplers = effect.getSamplers();
  10013. for (var index = 0; index < samplers.length; index++) {
  10014. var uniform = effect.getUniform(samplers[index]);
  10015. this._gl.uniform1i(uniform, index);
  10016. }
  10017. this._currentEffect = null;
  10018. };
  10019. Engine.prototype.activateTexture = function (texture) {
  10020. if (this._activeTexture !== texture) {
  10021. this._gl.activeTexture(texture);
  10022. this._activeTexture = texture;
  10023. }
  10024. };
  10025. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10026. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10027. this._gl.bindTexture(target, texture);
  10028. this._activeTexturesCache[this._activeTexture] = texture;
  10029. }
  10030. };
  10031. Engine.prototype._bindTexture = function (channel, texture) {
  10032. if (channel < 0) {
  10033. return;
  10034. }
  10035. this.activateTexture(this._gl.TEXTURE0 + channel);
  10036. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10037. };
  10038. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10039. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10040. };
  10041. Engine.prototype.unbindAllTextures = function () {
  10042. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10043. this.activateTexture(this._gl["TEXTURE" + channel]);
  10044. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10045. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10046. }
  10047. };
  10048. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10049. if (channel < 0) {
  10050. return;
  10051. }
  10052. this._gl.uniform1i(uniform, channel);
  10053. this._setTexture(channel, texture);
  10054. };
  10055. Engine.prototype._setTexture = function (channel, texture) {
  10056. // Not ready?
  10057. if (!texture || !texture.isReady()) {
  10058. if (this._activeTexturesCache[channel] != null) {
  10059. this.activateTexture(this._gl["TEXTURE" + channel]);
  10060. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10062. }
  10063. return;
  10064. }
  10065. // Video
  10066. var alreadyActivated = false;
  10067. if (texture instanceof BABYLON.VideoTexture) {
  10068. this.activateTexture(this._gl["TEXTURE" + channel]);
  10069. alreadyActivated = true;
  10070. texture.update();
  10071. }
  10072. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10073. texture.delayLoad();
  10074. return;
  10075. }
  10076. var internalTexture = texture.getInternalTexture();
  10077. if (this._activeTexturesCache[channel] === internalTexture) {
  10078. return;
  10079. }
  10080. if (!alreadyActivated) {
  10081. this.activateTexture(this._gl["TEXTURE" + channel]);
  10082. }
  10083. if (internalTexture.isCube) {
  10084. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10085. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10086. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10087. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10088. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10089. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10090. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10091. }
  10092. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10093. }
  10094. else {
  10095. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10096. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10097. internalTexture._cachedWrapU = texture.wrapU;
  10098. switch (texture.wrapU) {
  10099. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10100. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10101. break;
  10102. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10103. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10104. break;
  10105. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10106. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10107. break;
  10108. }
  10109. }
  10110. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10111. internalTexture._cachedWrapV = texture.wrapV;
  10112. switch (texture.wrapV) {
  10113. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10114. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10115. break;
  10116. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10117. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10118. break;
  10119. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10120. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10121. break;
  10122. }
  10123. }
  10124. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10125. }
  10126. };
  10127. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10128. if (channel < 0) {
  10129. return;
  10130. }
  10131. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10132. this._textureUnits = new Int32Array(textures.length);
  10133. }
  10134. for (var i = 0; i < textures.length; i++) {
  10135. this._textureUnits[i] = channel + i;
  10136. }
  10137. this._gl.uniform1iv(uniform, this._textureUnits);
  10138. for (var index = 0; index < textures.length; index++) {
  10139. this._setTexture(channel + index, textures[index]);
  10140. }
  10141. };
  10142. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10143. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10144. var value = texture.anisotropicFilteringLevel;
  10145. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10146. value = 1;
  10147. }
  10148. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10149. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10150. texture._cachedAnisotropicFilteringLevel = value;
  10151. }
  10152. };
  10153. Engine.prototype.readPixels = function (x, y, width, height) {
  10154. var data = new Uint8Array(height * width * 4);
  10155. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10156. return data;
  10157. };
  10158. /**
  10159. * Add an externaly attached data from its key.
  10160. * This method call will fail and return false, if such key already exists.
  10161. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10162. * @param key the unique key that identifies the data
  10163. * @param data the data object to associate to the key for this Engine instance
  10164. * @return true if no such key were already present and the data was added successfully, false otherwise
  10165. */
  10166. Engine.prototype.addExternalData = function (key, data) {
  10167. return this._externalData.add(key, data);
  10168. };
  10169. /**
  10170. * Get an externaly attached data from its key
  10171. * @param key the unique key that identifies the data
  10172. * @return the associated data, if present (can be null), or undefined if not present
  10173. */
  10174. Engine.prototype.getExternalData = function (key) {
  10175. return this._externalData.get(key);
  10176. };
  10177. /**
  10178. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10179. * @param key the unique key that identifies the data
  10180. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10181. * @return the associated data, can be null if the factory returned null.
  10182. */
  10183. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10184. return this._externalData.getOrAddWithFactory(key, factory);
  10185. };
  10186. /**
  10187. * Remove an externaly attached data from the Engine instance
  10188. * @param key the unique key that identifies the data
  10189. * @return true if the data was successfully removed, false if it doesn't exist
  10190. */
  10191. Engine.prototype.removeExternalData = function (key) {
  10192. return this._externalData.remove(key);
  10193. };
  10194. Engine.prototype.releaseInternalTexture = function (texture) {
  10195. if (!texture) {
  10196. return;
  10197. }
  10198. texture.references--;
  10199. // Final reference ?
  10200. if (texture.references === 0) {
  10201. var texturesCache = this.getLoadedTexturesCache();
  10202. var index = texturesCache.indexOf(texture);
  10203. if (index > -1) {
  10204. texturesCache.splice(index, 1);
  10205. }
  10206. this._releaseTexture(texture);
  10207. }
  10208. };
  10209. Engine.prototype.unbindAllAttributes = function () {
  10210. if (this._mustWipeVertexAttributes) {
  10211. this._mustWipeVertexAttributes = false;
  10212. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10213. this._gl.disableVertexAttribArray(i);
  10214. this._vertexAttribArraysEnabled[i] = false;
  10215. this._currentBufferPointers[i] = null;
  10216. }
  10217. return;
  10218. }
  10219. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10220. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10221. continue;
  10222. }
  10223. this._gl.disableVertexAttribArray(i);
  10224. this._vertexAttribArraysEnabled[i] = false;
  10225. this._currentBufferPointers[i] = null;
  10226. }
  10227. };
  10228. // Dispose
  10229. Engine.prototype.dispose = function () {
  10230. this.hideLoadingUI();
  10231. this.stopRenderLoop();
  10232. // Release scenes
  10233. while (this.scenes.length) {
  10234. this.scenes[0].dispose();
  10235. }
  10236. // Release audio engine
  10237. Engine.audioEngine.dispose();
  10238. // Release effects
  10239. for (var name in this._compiledEffects) {
  10240. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10241. }
  10242. // Unbind
  10243. this.unbindAllAttributes();
  10244. this._gl = null;
  10245. //WebVR
  10246. this.disableVR();
  10247. // Events
  10248. window.removeEventListener("blur", this._onBlur);
  10249. window.removeEventListener("focus", this._onFocus);
  10250. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10251. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10252. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10253. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10254. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10255. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10256. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10257. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10258. };
  10259. // Loading screen
  10260. Engine.prototype.displayLoadingUI = function () {
  10261. this._loadingScreen.displayLoadingUI();
  10262. };
  10263. Engine.prototype.hideLoadingUI = function () {
  10264. this._loadingScreen.hideLoadingUI();
  10265. };
  10266. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10267. get: function () {
  10268. return this._loadingScreen;
  10269. },
  10270. set: function (loadingScreen) {
  10271. this._loadingScreen = loadingScreen;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10277. set: function (text) {
  10278. this._loadingScreen.loadingUIText = text;
  10279. },
  10280. enumerable: true,
  10281. configurable: true
  10282. });
  10283. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10284. set: function (color) {
  10285. this._loadingScreen.loadingUIBackgroundColor = color;
  10286. },
  10287. enumerable: true,
  10288. configurable: true
  10289. });
  10290. Engine.prototype.attachContextLostEvent = function (callback) {
  10291. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10292. };
  10293. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10294. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10295. };
  10296. Engine.prototype.getVertexShaderSource = function (program) {
  10297. var shaders = this._gl.getAttachedShaders(program);
  10298. return this._gl.getShaderSource(shaders[0]);
  10299. };
  10300. Engine.prototype.getFragmentShaderSource = function (program) {
  10301. var shaders = this._gl.getAttachedShaders(program);
  10302. return this._gl.getShaderSource(shaders[1]);
  10303. };
  10304. // FPS
  10305. Engine.prototype.getFps = function () {
  10306. return this.fps;
  10307. };
  10308. Engine.prototype.getDeltaTime = function () {
  10309. return this.deltaTime;
  10310. };
  10311. Engine.prototype._measureFps = function () {
  10312. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10313. var length = this.previousFramesDuration.length;
  10314. if (length >= 2) {
  10315. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10316. }
  10317. if (length >= this.fpsRange) {
  10318. if (length > this.fpsRange) {
  10319. this.previousFramesDuration.splice(0, 1);
  10320. length = this.previousFramesDuration.length;
  10321. }
  10322. var sum = 0;
  10323. for (var id = 0; id < length - 1; id++) {
  10324. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10325. }
  10326. this.fps = 1000.0 / (sum / (length - 1));
  10327. }
  10328. };
  10329. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10330. if (this._webGLVersion > 1) {
  10331. return this._caps.colorBufferFloat;
  10332. }
  10333. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10334. };
  10335. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10336. if (this._webGLVersion > 1) {
  10337. return this._caps.colorBufferFloat;
  10338. }
  10339. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10340. };
  10341. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10342. Engine.prototype._canRenderToFramebuffer = function (type) {
  10343. var gl = this._gl;
  10344. //clear existing errors
  10345. while (gl.getError() !== gl.NO_ERROR) { }
  10346. var successful = true;
  10347. var texture = gl.createTexture();
  10348. gl.bindTexture(gl.TEXTURE_2D, texture);
  10349. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10352. var fb = gl.createFramebuffer();
  10353. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10354. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10355. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10356. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10357. successful = successful && (gl.getError() === gl.NO_ERROR);
  10358. //try render by clearing frame buffer's color buffer
  10359. if (successful) {
  10360. gl.clear(gl.COLOR_BUFFER_BIT);
  10361. successful = successful && (gl.getError() === gl.NO_ERROR);
  10362. }
  10363. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10364. if (successful) {
  10365. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10366. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10367. var readFormat = gl.RGBA;
  10368. var readType = gl.UNSIGNED_BYTE;
  10369. var buffer = new Uint8Array(4);
  10370. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10371. successful = successful && (gl.getError() === gl.NO_ERROR);
  10372. }
  10373. //clean up
  10374. gl.deleteTexture(texture);
  10375. gl.deleteFramebuffer(fb);
  10376. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10377. //clear accumulated errors
  10378. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10379. return successful;
  10380. };
  10381. Engine.prototype._getWebGLTextureType = function (type) {
  10382. if (type === Engine.TEXTURETYPE_FLOAT) {
  10383. return this._gl.FLOAT;
  10384. }
  10385. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10386. // Add Half Float Constant.
  10387. return Engine.HALF_FLOAT_OES;
  10388. }
  10389. return this._gl.UNSIGNED_BYTE;
  10390. };
  10391. ;
  10392. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10393. if (this._webGLVersion === 1) {
  10394. return this._gl.RGBA;
  10395. }
  10396. if (type === Engine.TEXTURETYPE_FLOAT) {
  10397. return Engine.RGBA32F;
  10398. }
  10399. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10400. return Engine.RGBA16F;
  10401. }
  10402. return this._gl.RGBA;
  10403. };
  10404. ;
  10405. // Statics
  10406. Engine.isSupported = function () {
  10407. try {
  10408. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10409. if (navigator.isCocoonJS) {
  10410. return true;
  10411. }
  10412. var tempcanvas = document.createElement("canvas");
  10413. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10414. return gl != null && !!window.WebGLRenderingContext;
  10415. }
  10416. catch (e) {
  10417. return false;
  10418. }
  10419. };
  10420. return Engine;
  10421. }());
  10422. // Const statics
  10423. Engine._ALPHA_DISABLE = 0;
  10424. Engine._ALPHA_ADD = 1;
  10425. Engine._ALPHA_COMBINE = 2;
  10426. Engine._ALPHA_SUBTRACT = 3;
  10427. Engine._ALPHA_MULTIPLY = 4;
  10428. Engine._ALPHA_MAXIMIZED = 5;
  10429. Engine._ALPHA_ONEONE = 6;
  10430. Engine._ALPHA_PREMULTIPLIED = 7;
  10431. Engine._DELAYLOADSTATE_NONE = 0;
  10432. Engine._DELAYLOADSTATE_LOADED = 1;
  10433. Engine._DELAYLOADSTATE_LOADING = 2;
  10434. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10435. Engine._TEXTUREFORMAT_ALPHA = 0;
  10436. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10437. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10438. Engine._TEXTUREFORMAT_RGB = 4;
  10439. Engine._TEXTUREFORMAT_RGBA = 5;
  10440. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10441. Engine._TEXTURETYPE_FLOAT = 1;
  10442. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10443. // Depht or Stencil test Constants.
  10444. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10445. 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.
  10446. 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.
  10447. 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.
  10448. 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.
  10449. 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.
  10450. 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.
  10451. 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.
  10452. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10453. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10454. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10455. // Stencil Actions Constants.
  10456. Engine._KEEP = 0x1E00;
  10457. Engine._REPLACE = 0x1E01;
  10458. Engine._INCR = 0x1E02;
  10459. Engine._DECR = 0x1E03;
  10460. Engine._INVERT = 0x150A;
  10461. Engine._INCR_WRAP = 0x8507;
  10462. Engine._DECR_WRAP = 0x8508;
  10463. // Updatable statics so stick with vars here
  10464. Engine.CollisionsEpsilon = 0.001;
  10465. Engine.CodeRepository = "src/";
  10466. Engine.ShadersRepository = "src/Shaders/";
  10467. BABYLON.Engine = Engine;
  10468. })(BABYLON || (BABYLON = {}));
  10469. //# sourceMappingURL=babylon.engine.js.map
  10470. /// <reference path="Tools\babylon.decorators.ts" />
  10471. var BABYLON;
  10472. (function (BABYLON) {
  10473. /**
  10474. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10475. */
  10476. var Node = (function () {
  10477. /**
  10478. * @constructor
  10479. * @param {string} name - the name and id to be given to this node
  10480. * @param {BABYLON.Scene} the scene this node will be added to
  10481. */
  10482. function Node(name, scene) {
  10483. this.state = "";
  10484. this.metadata = null;
  10485. this.doNotSerialize = false;
  10486. this.animations = new Array();
  10487. this._ranges = {};
  10488. this._childrenFlag = -1;
  10489. this._isEnabled = true;
  10490. this._isReady = true;
  10491. this._currentRenderId = -1;
  10492. this._parentRenderId = -1;
  10493. /**
  10494. * An event triggered when the mesh is disposed.
  10495. * @type {BABYLON.Observable}
  10496. */
  10497. this.onDisposeObservable = new BABYLON.Observable();
  10498. this.name = name;
  10499. this.id = name;
  10500. this._scene = scene;
  10501. this._initCache();
  10502. }
  10503. Object.defineProperty(Node.prototype, "parent", {
  10504. get: function () {
  10505. return this._parentNode;
  10506. },
  10507. set: function (parent) {
  10508. if (this._parentNode === parent) {
  10509. return;
  10510. }
  10511. if (this._parentNode) {
  10512. var index = this._parentNode._children.indexOf(this);
  10513. if (index !== -1) {
  10514. this._parentNode._children.splice(index, 1);
  10515. }
  10516. }
  10517. this._parentNode = parent;
  10518. if (this._parentNode) {
  10519. if (!this._parentNode._children) {
  10520. this._parentNode._children = new Array();
  10521. }
  10522. this._parentNode._children.push(this);
  10523. }
  10524. },
  10525. enumerable: true,
  10526. configurable: true
  10527. });
  10528. Node.prototype.getClassName = function () {
  10529. return "Node";
  10530. };
  10531. Object.defineProperty(Node.prototype, "onDispose", {
  10532. set: function (callback) {
  10533. if (this._onDisposeObserver) {
  10534. this.onDisposeObservable.remove(this._onDisposeObserver);
  10535. }
  10536. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10537. },
  10538. enumerable: true,
  10539. configurable: true
  10540. });
  10541. Node.prototype.getScene = function () {
  10542. return this._scene;
  10543. };
  10544. Node.prototype.getEngine = function () {
  10545. return this._scene.getEngine();
  10546. };
  10547. // override it in derived class
  10548. Node.prototype.getWorldMatrix = function () {
  10549. return BABYLON.Matrix.Identity();
  10550. };
  10551. // override it in derived class if you add new variables to the cache
  10552. // and call the parent class method
  10553. Node.prototype._initCache = function () {
  10554. this._cache = {};
  10555. this._cache.parent = undefined;
  10556. };
  10557. Node.prototype.updateCache = function (force) {
  10558. if (!force && this.isSynchronized())
  10559. return;
  10560. this._cache.parent = this.parent;
  10561. this._updateCache();
  10562. };
  10563. // override it in derived class if you add new variables to the cache
  10564. // and call the parent class method if !ignoreParentClass
  10565. Node.prototype._updateCache = function (ignoreParentClass) {
  10566. };
  10567. // override it in derived class if you add new variables to the cache
  10568. Node.prototype._isSynchronized = function () {
  10569. return true;
  10570. };
  10571. Node.prototype._markSyncedWithParent = function () {
  10572. this._parentRenderId = this.parent._currentRenderId;
  10573. };
  10574. Node.prototype.isSynchronizedWithParent = function () {
  10575. if (!this.parent) {
  10576. return true;
  10577. }
  10578. if (this._parentRenderId !== this.parent._currentRenderId) {
  10579. return false;
  10580. }
  10581. return this.parent.isSynchronized();
  10582. };
  10583. Node.prototype.isSynchronized = function (updateCache) {
  10584. var check = this.hasNewParent();
  10585. check = check || !this.isSynchronizedWithParent();
  10586. check = check || !this._isSynchronized();
  10587. if (updateCache)
  10588. this.updateCache(true);
  10589. return !check;
  10590. };
  10591. Node.prototype.hasNewParent = function (update) {
  10592. if (this._cache.parent === this.parent)
  10593. return false;
  10594. if (update)
  10595. this._cache.parent = this.parent;
  10596. return true;
  10597. };
  10598. /**
  10599. * Is this node ready to be used/rendered
  10600. * @return {boolean} is it ready
  10601. */
  10602. Node.prototype.isReady = function () {
  10603. return this._isReady;
  10604. };
  10605. /**
  10606. * Is this node enabled.
  10607. * If the node has a parent and is enabled, the parent will be inspected as well.
  10608. * @return {boolean} whether this node (and its parent) is enabled.
  10609. * @see setEnabled
  10610. */
  10611. Node.prototype.isEnabled = function () {
  10612. if (!this._isEnabled) {
  10613. return false;
  10614. }
  10615. if (this.parent) {
  10616. return this.parent.isEnabled();
  10617. }
  10618. return true;
  10619. };
  10620. /**
  10621. * Set the enabled state of this node.
  10622. * @param {boolean} value - the new enabled state
  10623. * @see isEnabled
  10624. */
  10625. Node.prototype.setEnabled = function (value) {
  10626. this._isEnabled = value;
  10627. };
  10628. /**
  10629. * Is this node a descendant of the given node.
  10630. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10631. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10632. * @see parent
  10633. */
  10634. Node.prototype.isDescendantOf = function (ancestor) {
  10635. if (this.parent) {
  10636. if (this.parent === ancestor) {
  10637. return true;
  10638. }
  10639. return this.parent.isDescendantOf(ancestor);
  10640. }
  10641. return false;
  10642. };
  10643. /**
  10644. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10645. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10646. * @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.
  10647. * @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.
  10648. */
  10649. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10650. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10651. if (!this._children) {
  10652. return;
  10653. }
  10654. for (var index = 0; index < this._children.length; index++) {
  10655. var item = this._children[index];
  10656. if (!predicate || predicate(item)) {
  10657. results.push(item);
  10658. }
  10659. if (!directDescendantsOnly) {
  10660. item._getDescendants(results, false, predicate);
  10661. }
  10662. }
  10663. };
  10664. /**
  10665. * Will return all nodes that have this node as ascendant.
  10666. * @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.
  10667. * @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.
  10668. * @return {BABYLON.Node[]} all children nodes of all types.
  10669. */
  10670. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10671. var results = [];
  10672. this._getDescendants(results, directDescendantsOnly, predicate);
  10673. return results;
  10674. };
  10675. /**
  10676. * @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.
  10677. * @Deprecated, legacy support.
  10678. * use getDecendants instead.
  10679. */
  10680. Node.prototype.getChildren = function (predicate) {
  10681. return this.getDescendants(true, predicate);
  10682. };
  10683. /**
  10684. * Get all child-meshes of this node.
  10685. */
  10686. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10687. var results = [];
  10688. this._getDescendants(results, directDecendantsOnly, function (node) {
  10689. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10690. });
  10691. return results;
  10692. };
  10693. Node.prototype._setReady = function (state) {
  10694. if (state === this._isReady) {
  10695. return;
  10696. }
  10697. if (!state) {
  10698. this._isReady = false;
  10699. return;
  10700. }
  10701. this._isReady = true;
  10702. if (this.onReady) {
  10703. this.onReady(this);
  10704. }
  10705. };
  10706. Node.prototype.getAnimationByName = function (name) {
  10707. for (var i = 0; i < this.animations.length; i++) {
  10708. var animation = this.animations[i];
  10709. if (animation.name === name) {
  10710. return animation;
  10711. }
  10712. }
  10713. return null;
  10714. };
  10715. Node.prototype.createAnimationRange = function (name, from, to) {
  10716. // check name not already in use
  10717. if (!this._ranges[name]) {
  10718. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10719. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10720. if (this.animations[i]) {
  10721. this.animations[i].createRange(name, from, to);
  10722. }
  10723. }
  10724. }
  10725. };
  10726. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10727. if (deleteFrames === void 0) { deleteFrames = true; }
  10728. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10729. if (this.animations[i]) {
  10730. this.animations[i].deleteRange(name, deleteFrames);
  10731. }
  10732. }
  10733. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10734. };
  10735. Node.prototype.getAnimationRange = function (name) {
  10736. return this._ranges[name];
  10737. };
  10738. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10739. var range = this.getAnimationRange(name);
  10740. if (!range) {
  10741. return null;
  10742. }
  10743. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10744. };
  10745. Node.prototype.serializeAnimationRanges = function () {
  10746. var serializationRanges = [];
  10747. for (var name in this._ranges) {
  10748. var range = {};
  10749. range.name = name;
  10750. range.from = this._ranges[name].from;
  10751. range.to = this._ranges[name].to;
  10752. serializationRanges.push(range);
  10753. }
  10754. return serializationRanges;
  10755. };
  10756. Node.prototype.dispose = function () {
  10757. this.parent = null;
  10758. // Callback
  10759. this.onDisposeObservable.notifyObservers(this);
  10760. this.onDisposeObservable.clear();
  10761. };
  10762. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10763. if (parsedNode.ranges) {
  10764. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10765. var data = parsedNode.ranges[index];
  10766. node.createAnimationRange(data.name, data.from, data.to);
  10767. }
  10768. }
  10769. };
  10770. return Node;
  10771. }());
  10772. __decorate([
  10773. BABYLON.serialize()
  10774. ], Node.prototype, "name", void 0);
  10775. __decorate([
  10776. BABYLON.serialize()
  10777. ], Node.prototype, "id", void 0);
  10778. __decorate([
  10779. BABYLON.serialize()
  10780. ], Node.prototype, "uniqueId", void 0);
  10781. __decorate([
  10782. BABYLON.serialize()
  10783. ], Node.prototype, "state", void 0);
  10784. __decorate([
  10785. BABYLON.serialize()
  10786. ], Node.prototype, "metadata", void 0);
  10787. BABYLON.Node = Node;
  10788. })(BABYLON || (BABYLON = {}));
  10789. //# sourceMappingURL=babylon.node.js.map
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. var FilesInput = (function () {
  10793. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  10794. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  10795. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  10796. this._engine = p_engine;
  10797. this._canvas = p_canvas;
  10798. this._currentScene = p_scene;
  10799. this._sceneLoadedCallback = p_sceneLoadedCallback;
  10800. this._progressCallback = p_progressCallback;
  10801. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  10802. this._textureLoadingCallback = p_textureLoadingCallback;
  10803. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  10804. }
  10805. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  10806. var _this = this;
  10807. if (p_elementToMonitor) {
  10808. this._elementToMonitor = p_elementToMonitor;
  10809. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  10810. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  10811. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  10812. }
  10813. };
  10814. FilesInput.prototype.renderFunction = function () {
  10815. if (this._additionnalRenderLoopLogicCallback) {
  10816. this._additionnalRenderLoopLogicCallback();
  10817. }
  10818. if (this._currentScene) {
  10819. if (this._textureLoadingCallback) {
  10820. var remaining = this._currentScene.getWaitingItemsCount();
  10821. if (remaining > 0) {
  10822. this._textureLoadingCallback(remaining);
  10823. }
  10824. }
  10825. this._currentScene.render();
  10826. }
  10827. };
  10828. FilesInput.prototype.drag = function (e) {
  10829. e.stopPropagation();
  10830. e.preventDefault();
  10831. };
  10832. FilesInput.prototype.drop = function (eventDrop) {
  10833. eventDrop.stopPropagation();
  10834. eventDrop.preventDefault();
  10835. this.loadFiles(eventDrop);
  10836. };
  10837. FilesInput.prototype.loadFiles = function (event) {
  10838. if (this._startingProcessingFilesCallback)
  10839. this._startingProcessingFilesCallback();
  10840. // Handling data transfer via drag'n'drop
  10841. if (event && event.dataTransfer && event.dataTransfer.files) {
  10842. this._filesToLoad = event.dataTransfer.files;
  10843. }
  10844. // Handling files from input files
  10845. if (event && event.target && event.target.files) {
  10846. this._filesToLoad = event.target.files;
  10847. }
  10848. if (this._filesToLoad && this._filesToLoad.length > 0) {
  10849. for (var i = 0; i < this._filesToLoad.length; i++) {
  10850. var name_1 = this._filesToLoad[i].name.toLowerCase();
  10851. var extension = name_1.split('.').pop();
  10852. var type = this._filesToLoad[i].type;
  10853. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  10854. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  10855. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  10856. }
  10857. else {
  10858. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  10859. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  10860. this._sceneFileToLoad = this._filesToLoad[i];
  10861. }
  10862. else {
  10863. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  10864. }
  10865. }
  10866. }
  10867. this.reload();
  10868. }
  10869. };
  10870. FilesInput.prototype.reload = function () {
  10871. var _this = this;
  10872. var that = this;
  10873. // If a ".babylon" file has been provided
  10874. if (this._sceneFileToLoad) {
  10875. if (this._currentScene) {
  10876. if (BABYLON.Tools.errorsCount > 0) {
  10877. BABYLON.Tools.ClearLogCache();
  10878. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  10879. }
  10880. this._engine.stopRenderLoop();
  10881. this._currentScene.dispose();
  10882. }
  10883. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  10884. that._currentScene = newScene;
  10885. // Wait for textures and shaders to be ready
  10886. that._currentScene.executeWhenReady(function () {
  10887. // Attach camera to canvas inputs
  10888. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  10889. that._currentScene.createDefaultCameraOrLight();
  10890. }
  10891. that._currentScene.activeCamera.attachControl(that._canvas);
  10892. if (that._sceneLoadedCallback) {
  10893. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  10894. }
  10895. that._engine.runRenderLoop(function () { that.renderFunction(); });
  10896. });
  10897. }, function (progress) {
  10898. if (_this._progressCallback) {
  10899. _this._progressCallback(progress);
  10900. }
  10901. });
  10902. }
  10903. else {
  10904. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  10905. }
  10906. };
  10907. return FilesInput;
  10908. }());
  10909. FilesInput.FilesTextures = new Array();
  10910. FilesInput.FilesToLoad = new Array();
  10911. BABYLON.FilesInput = FilesInput;
  10912. })(BABYLON || (BABYLON = {}));
  10913. //# sourceMappingURL=babylon.filesInput.js.map
  10914. var BABYLON;
  10915. (function (BABYLON) {
  10916. var IntersectionInfo = (function () {
  10917. function IntersectionInfo(bu, bv, distance) {
  10918. this.bu = bu;
  10919. this.bv = bv;
  10920. this.distance = distance;
  10921. this.faceId = 0;
  10922. this.subMeshId = 0;
  10923. }
  10924. return IntersectionInfo;
  10925. }());
  10926. BABYLON.IntersectionInfo = IntersectionInfo;
  10927. var PickingInfo = (function () {
  10928. function PickingInfo() {
  10929. this.hit = false;
  10930. this.distance = 0;
  10931. this.pickedPoint = null;
  10932. this.pickedMesh = null;
  10933. this.bu = 0;
  10934. this.bv = 0;
  10935. this.faceId = -1;
  10936. this.subMeshId = 0;
  10937. this.pickedSprite = null;
  10938. }
  10939. // Methods
  10940. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  10941. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  10942. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  10943. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10944. return null;
  10945. }
  10946. var indices = this.pickedMesh.getIndices();
  10947. var result;
  10948. if (useVerticesNormals) {
  10949. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10950. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  10951. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  10952. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  10953. normal0 = normal0.scale(this.bu);
  10954. normal1 = normal1.scale(this.bv);
  10955. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  10956. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  10957. }
  10958. else {
  10959. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10960. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  10961. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  10962. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  10963. var p1p2 = vertex1.subtract(vertex2);
  10964. var p3p2 = vertex3.subtract(vertex2);
  10965. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  10966. }
  10967. if (useWorldCoordinates) {
  10968. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  10969. }
  10970. return BABYLON.Vector3.Normalize(result);
  10971. };
  10972. PickingInfo.prototype.getTextureCoordinates = function () {
  10973. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10974. return null;
  10975. }
  10976. var indices = this.pickedMesh.getIndices();
  10977. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10978. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  10979. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  10980. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  10981. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  10982. uv1 = uv1.scale(this.bu);
  10983. uv2 = uv2.scale(this.bv);
  10984. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  10985. };
  10986. return PickingInfo;
  10987. }());
  10988. BABYLON.PickingInfo = PickingInfo;
  10989. })(BABYLON || (BABYLON = {}));
  10990. //# sourceMappingURL=babylon.pickingInfo.js.map
  10991. var BABYLON;
  10992. (function (BABYLON) {
  10993. var BoundingSphere = (function () {
  10994. function BoundingSphere(minimum, maximum) {
  10995. this.minimum = minimum;
  10996. this.maximum = maximum;
  10997. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10998. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10999. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11000. this.radius = distance * 0.5;
  11001. this.centerWorld = BABYLON.Vector3.Zero();
  11002. this._update(BABYLON.Matrix.Identity());
  11003. }
  11004. // Methods
  11005. BoundingSphere.prototype._update = function (world) {
  11006. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11007. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11008. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11009. };
  11010. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11011. for (var i = 0; i < 6; i++) {
  11012. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11013. return false;
  11014. }
  11015. return true;
  11016. };
  11017. BoundingSphere.prototype.intersectsPoint = function (point) {
  11018. var x = this.centerWorld.x - point.x;
  11019. var y = this.centerWorld.y - point.y;
  11020. var z = this.centerWorld.z - point.z;
  11021. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11022. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11023. return false;
  11024. return true;
  11025. };
  11026. // Statics
  11027. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11028. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11029. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11030. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11031. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11032. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11033. return false;
  11034. return true;
  11035. };
  11036. return BoundingSphere;
  11037. }());
  11038. BABYLON.BoundingSphere = BoundingSphere;
  11039. })(BABYLON || (BABYLON = {}));
  11040. //# sourceMappingURL=babylon.boundingSphere.js.map
  11041. var BABYLON;
  11042. (function (BABYLON) {
  11043. var BoundingBox = (function () {
  11044. function BoundingBox(minimum, maximum) {
  11045. this.minimum = minimum;
  11046. this.maximum = maximum;
  11047. this.vectors = new Array();
  11048. this.vectorsWorld = new Array();
  11049. // Bounding vectors
  11050. this.vectors.push(this.minimum.clone());
  11051. this.vectors.push(this.maximum.clone());
  11052. this.vectors.push(this.minimum.clone());
  11053. this.vectors[2].x = this.maximum.x;
  11054. this.vectors.push(this.minimum.clone());
  11055. this.vectors[3].y = this.maximum.y;
  11056. this.vectors.push(this.minimum.clone());
  11057. this.vectors[4].z = this.maximum.z;
  11058. this.vectors.push(this.maximum.clone());
  11059. this.vectors[5].z = this.minimum.z;
  11060. this.vectors.push(this.maximum.clone());
  11061. this.vectors[6].x = this.minimum.x;
  11062. this.vectors.push(this.maximum.clone());
  11063. this.vectors[7].y = this.minimum.y;
  11064. // OBB
  11065. this.center = this.maximum.add(this.minimum).scale(0.5);
  11066. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11067. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11068. // World
  11069. for (var index = 0; index < this.vectors.length; index++) {
  11070. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11071. }
  11072. this.minimumWorld = BABYLON.Vector3.Zero();
  11073. this.maximumWorld = BABYLON.Vector3.Zero();
  11074. this._update(BABYLON.Matrix.Identity());
  11075. }
  11076. // Methods
  11077. BoundingBox.prototype.getWorldMatrix = function () {
  11078. return this._worldMatrix;
  11079. };
  11080. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11081. this._worldMatrix.copyFrom(matrix);
  11082. return this;
  11083. };
  11084. BoundingBox.prototype._update = function (world) {
  11085. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11086. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11087. for (var index = 0; index < this.vectors.length; index++) {
  11088. var v = this.vectorsWorld[index];
  11089. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11090. if (v.x < this.minimumWorld.x)
  11091. this.minimumWorld.x = v.x;
  11092. if (v.y < this.minimumWorld.y)
  11093. this.minimumWorld.y = v.y;
  11094. if (v.z < this.minimumWorld.z)
  11095. this.minimumWorld.z = v.z;
  11096. if (v.x > this.maximumWorld.x)
  11097. this.maximumWorld.x = v.x;
  11098. if (v.y > this.maximumWorld.y)
  11099. this.maximumWorld.y = v.y;
  11100. if (v.z > this.maximumWorld.z)
  11101. this.maximumWorld.z = v.z;
  11102. }
  11103. // OBB
  11104. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  11105. this.center.scaleInPlace(0.5);
  11106. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11107. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11108. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11109. this._worldMatrix = world;
  11110. };
  11111. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11112. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11113. };
  11114. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11115. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11116. };
  11117. BoundingBox.prototype.intersectsPoint = function (point) {
  11118. var delta = -BABYLON.Epsilon;
  11119. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11120. return false;
  11121. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11122. return false;
  11123. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11124. return false;
  11125. return true;
  11126. };
  11127. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11128. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11129. };
  11130. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11131. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11132. return false;
  11133. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11134. return false;
  11135. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11136. return false;
  11137. return true;
  11138. };
  11139. // Statics
  11140. BoundingBox.Intersects = function (box0, box1) {
  11141. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11142. return false;
  11143. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11144. return false;
  11145. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11146. return false;
  11147. return true;
  11148. };
  11149. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11150. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11151. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11152. return (num <= (sphereRadius * sphereRadius));
  11153. };
  11154. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11155. for (var p = 0; p < 6; p++) {
  11156. for (var i = 0; i < 8; i++) {
  11157. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11158. return false;
  11159. }
  11160. }
  11161. }
  11162. return true;
  11163. };
  11164. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11165. for (var p = 0; p < 6; p++) {
  11166. var inCount = 8;
  11167. for (var i = 0; i < 8; i++) {
  11168. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11169. --inCount;
  11170. }
  11171. else {
  11172. break;
  11173. }
  11174. }
  11175. if (inCount === 0)
  11176. return false;
  11177. }
  11178. return true;
  11179. };
  11180. return BoundingBox;
  11181. }());
  11182. BABYLON.BoundingBox = BoundingBox;
  11183. })(BABYLON || (BABYLON = {}));
  11184. //# sourceMappingURL=babylon.boundingBox.js.map
  11185. var BABYLON;
  11186. (function (BABYLON) {
  11187. var computeBoxExtents = function (axis, box) {
  11188. var p = BABYLON.Vector3.Dot(box.center, axis);
  11189. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11190. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11191. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11192. var r = r0 + r1 + r2;
  11193. return {
  11194. min: p - r,
  11195. max: p + r
  11196. };
  11197. };
  11198. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11199. var axisOverlap = function (axis, box0, box1) {
  11200. var result0 = computeBoxExtents(axis, box0);
  11201. var result1 = computeBoxExtents(axis, box1);
  11202. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11203. };
  11204. var BoundingInfo = (function () {
  11205. function BoundingInfo(minimum, maximum) {
  11206. this.minimum = minimum;
  11207. this.maximum = maximum;
  11208. this._isLocked = false;
  11209. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11210. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11211. }
  11212. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11213. get: function () {
  11214. return this._isLocked;
  11215. },
  11216. set: function (value) {
  11217. this._isLocked = value;
  11218. },
  11219. enumerable: true,
  11220. configurable: true
  11221. });
  11222. // Methods
  11223. BoundingInfo.prototype.update = function (world) {
  11224. if (this._isLocked) {
  11225. return;
  11226. }
  11227. this.boundingBox._update(world);
  11228. this.boundingSphere._update(world);
  11229. };
  11230. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11231. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11232. return false;
  11233. return this.boundingBox.isInFrustum(frustumPlanes);
  11234. };
  11235. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11236. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11237. };
  11238. BoundingInfo.prototype._checkCollision = function (collider) {
  11239. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11240. };
  11241. BoundingInfo.prototype.intersectsPoint = function (point) {
  11242. if (!this.boundingSphere.centerWorld) {
  11243. return false;
  11244. }
  11245. if (!this.boundingSphere.intersectsPoint(point)) {
  11246. return false;
  11247. }
  11248. if (!this.boundingBox.intersectsPoint(point)) {
  11249. return false;
  11250. }
  11251. return true;
  11252. };
  11253. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11254. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11255. return false;
  11256. }
  11257. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11258. return false;
  11259. }
  11260. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11261. return false;
  11262. }
  11263. if (!precise) {
  11264. return true;
  11265. }
  11266. var box0 = this.boundingBox;
  11267. var box1 = boundingInfo.boundingBox;
  11268. if (!axisOverlap(box0.directions[0], box0, box1))
  11269. return false;
  11270. if (!axisOverlap(box0.directions[1], box0, box1))
  11271. return false;
  11272. if (!axisOverlap(box0.directions[2], box0, box1))
  11273. return false;
  11274. if (!axisOverlap(box1.directions[0], box0, box1))
  11275. return false;
  11276. if (!axisOverlap(box1.directions[1], box0, box1))
  11277. return false;
  11278. if (!axisOverlap(box1.directions[2], box0, box1))
  11279. return false;
  11280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11281. return false;
  11282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11283. return false;
  11284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11285. return false;
  11286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11287. return false;
  11288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11289. return false;
  11290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11291. return false;
  11292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11293. return false;
  11294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11295. return false;
  11296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11297. return false;
  11298. return true;
  11299. };
  11300. return BoundingInfo;
  11301. }());
  11302. BABYLON.BoundingInfo = BoundingInfo;
  11303. })(BABYLON || (BABYLON = {}));
  11304. //# sourceMappingURL=babylon.boundingInfo.js.map
  11305. var BABYLON;
  11306. (function (BABYLON) {
  11307. var Ray = (function () {
  11308. function Ray(origin, direction, length) {
  11309. if (length === void 0) { length = Number.MAX_VALUE; }
  11310. this.origin = origin;
  11311. this.direction = direction;
  11312. this.length = length;
  11313. }
  11314. // Methods
  11315. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11316. var d = 0.0;
  11317. var maxValue = Number.MAX_VALUE;
  11318. var inv;
  11319. var min;
  11320. var max;
  11321. var temp;
  11322. if (Math.abs(this.direction.x) < 0.0000001) {
  11323. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11324. return false;
  11325. }
  11326. }
  11327. else {
  11328. inv = 1.0 / this.direction.x;
  11329. min = (minimum.x - this.origin.x) * inv;
  11330. max = (maximum.x - this.origin.x) * inv;
  11331. if (max === -Infinity) {
  11332. max = Infinity;
  11333. }
  11334. if (min > max) {
  11335. temp = min;
  11336. min = max;
  11337. max = temp;
  11338. }
  11339. d = Math.max(min, d);
  11340. maxValue = Math.min(max, maxValue);
  11341. if (d > maxValue) {
  11342. return false;
  11343. }
  11344. }
  11345. if (Math.abs(this.direction.y) < 0.0000001) {
  11346. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11347. return false;
  11348. }
  11349. }
  11350. else {
  11351. inv = 1.0 / this.direction.y;
  11352. min = (minimum.y - this.origin.y) * inv;
  11353. max = (maximum.y - this.origin.y) * inv;
  11354. if (max === -Infinity) {
  11355. max = Infinity;
  11356. }
  11357. if (min > max) {
  11358. temp = min;
  11359. min = max;
  11360. max = temp;
  11361. }
  11362. d = Math.max(min, d);
  11363. maxValue = Math.min(max, maxValue);
  11364. if (d > maxValue) {
  11365. return false;
  11366. }
  11367. }
  11368. if (Math.abs(this.direction.z) < 0.0000001) {
  11369. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11370. return false;
  11371. }
  11372. }
  11373. else {
  11374. inv = 1.0 / this.direction.z;
  11375. min = (minimum.z - this.origin.z) * inv;
  11376. max = (maximum.z - this.origin.z) * inv;
  11377. if (max === -Infinity) {
  11378. max = Infinity;
  11379. }
  11380. if (min > max) {
  11381. temp = min;
  11382. min = max;
  11383. max = temp;
  11384. }
  11385. d = Math.max(min, d);
  11386. maxValue = Math.min(max, maxValue);
  11387. if (d > maxValue) {
  11388. return false;
  11389. }
  11390. }
  11391. return true;
  11392. };
  11393. Ray.prototype.intersectsBox = function (box) {
  11394. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11395. };
  11396. Ray.prototype.intersectsSphere = function (sphere) {
  11397. var x = sphere.center.x - this.origin.x;
  11398. var y = sphere.center.y - this.origin.y;
  11399. var z = sphere.center.z - this.origin.z;
  11400. var pyth = (x * x) + (y * y) + (z * z);
  11401. var rr = sphere.radius * sphere.radius;
  11402. if (pyth <= rr) {
  11403. return true;
  11404. }
  11405. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11406. if (dot < 0.0) {
  11407. return false;
  11408. }
  11409. var temp = pyth - (dot * dot);
  11410. return temp <= rr;
  11411. };
  11412. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11413. if (!this._edge1) {
  11414. this._edge1 = BABYLON.Vector3.Zero();
  11415. this._edge2 = BABYLON.Vector3.Zero();
  11416. this._pvec = BABYLON.Vector3.Zero();
  11417. this._tvec = BABYLON.Vector3.Zero();
  11418. this._qvec = BABYLON.Vector3.Zero();
  11419. }
  11420. vertex1.subtractToRef(vertex0, this._edge1);
  11421. vertex2.subtractToRef(vertex0, this._edge2);
  11422. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11423. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11424. if (det === 0) {
  11425. return null;
  11426. }
  11427. var invdet = 1 / det;
  11428. this.origin.subtractToRef(vertex0, this._tvec);
  11429. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11430. if (bu < 0 || bu > 1.0) {
  11431. return null;
  11432. }
  11433. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11434. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11435. if (bv < 0 || bu + bv > 1.0) {
  11436. return null;
  11437. }
  11438. //check if the distance is longer than the predefined length.
  11439. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11440. if (distance > this.length) {
  11441. return null;
  11442. }
  11443. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11444. };
  11445. Ray.prototype.intersectsPlane = function (plane) {
  11446. var distance;
  11447. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11448. if (Math.abs(result1) < 9.99999997475243E-07) {
  11449. return null;
  11450. }
  11451. else {
  11452. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11453. distance = (-plane.d - result2) / result1;
  11454. if (distance < 0.0) {
  11455. if (distance < -9.99999997475243E-07) {
  11456. return null;
  11457. }
  11458. else {
  11459. return 0;
  11460. }
  11461. }
  11462. return distance;
  11463. }
  11464. };
  11465. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11466. var tm = BABYLON.Tmp.Matrix[0];
  11467. mesh.getWorldMatrix().invertToRef(tm);
  11468. if (this._tmpRay) {
  11469. Ray.TransformToRef(this, tm, this._tmpRay);
  11470. }
  11471. else {
  11472. this._tmpRay = Ray.Transform(this, tm);
  11473. }
  11474. return mesh.intersects(this._tmpRay, fastCheck);
  11475. };
  11476. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11477. if (results) {
  11478. results.length = 0;
  11479. }
  11480. else {
  11481. results = [];
  11482. }
  11483. for (var i = 0; i < meshes.length; i++) {
  11484. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11485. if (pickInfo.hit) {
  11486. results.push(pickInfo);
  11487. }
  11488. }
  11489. results.sort(this._comparePickingInfo);
  11490. return results;
  11491. };
  11492. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11493. if (pickingInfoA.distance < pickingInfoB.distance) {
  11494. return -1;
  11495. }
  11496. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11497. return 1;
  11498. }
  11499. else {
  11500. return 0;
  11501. }
  11502. };
  11503. /**
  11504. * @Deprecated. Use new RayHelper.show() instead.
  11505. * */
  11506. Ray.prototype.show = function (scene, color) {
  11507. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  11508. if (!this._rayHelper) {
  11509. this._rayHelper = new BABYLON.RayHelper(this);
  11510. }
  11511. this._rayHelper.show(scene, color);
  11512. };
  11513. /**
  11514. * @Deprecated. Use new RayHelper.hide() instead.
  11515. * */
  11516. Ray.prototype.hide = function () {
  11517. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  11518. if (this._rayHelper) {
  11519. this._rayHelper.hide();
  11520. this._rayHelper = null;
  11521. }
  11522. };
  11523. /**
  11524. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11525. * @param sega the first point of the segment to test the intersection against
  11526. * @param segb the second point of the segment to test the intersection against
  11527. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11528. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11529. */
  11530. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11531. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11532. var u = segb.subtract(sega);
  11533. var v = rsegb.subtract(this.origin);
  11534. var w = sega.subtract(this.origin);
  11535. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11536. var b = BABYLON.Vector3.Dot(u, v);
  11537. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11538. var d = BABYLON.Vector3.Dot(u, w);
  11539. var e = BABYLON.Vector3.Dot(v, w);
  11540. var D = a * c - b * b; // always >= 0
  11541. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11542. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11543. // compute the line parameters of the two closest points
  11544. if (D < Ray.smallnum) {
  11545. sN = 0.0; // force using point P0 on segment S1
  11546. sD = 1.0; // to prevent possible division by 0.0 later
  11547. tN = e;
  11548. tD = c;
  11549. }
  11550. else {
  11551. sN = (b * e - c * d);
  11552. tN = (a * e - b * d);
  11553. if (sN < 0.0) {
  11554. sN = 0.0;
  11555. tN = e;
  11556. tD = c;
  11557. }
  11558. else if (sN > sD) {
  11559. sN = sD;
  11560. tN = e + b;
  11561. tD = c;
  11562. }
  11563. }
  11564. if (tN < 0.0) {
  11565. tN = 0.0;
  11566. // recompute sc for this edge
  11567. if (-d < 0.0) {
  11568. sN = 0.0;
  11569. }
  11570. else if (-d > a)
  11571. sN = sD;
  11572. else {
  11573. sN = -d;
  11574. sD = a;
  11575. }
  11576. }
  11577. else if (tN > tD) {
  11578. tN = tD;
  11579. // recompute sc for this edge
  11580. if ((-d + b) < 0.0) {
  11581. sN = 0;
  11582. }
  11583. else if ((-d + b) > a) {
  11584. sN = sD;
  11585. }
  11586. else {
  11587. sN = (-d + b);
  11588. sD = a;
  11589. }
  11590. }
  11591. // finally do the division to get sc and tc
  11592. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11593. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11594. // get the difference of the two closest points
  11595. var qtc = v.multiplyByFloats(tc, tc, tc);
  11596. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11597. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11598. if (isIntersected) {
  11599. return qtc.length();
  11600. }
  11601. return -1;
  11602. };
  11603. // Statics
  11604. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11605. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11606. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11607. var direction = end.subtract(start);
  11608. direction.normalize();
  11609. return new Ray(start, direction);
  11610. };
  11611. /**
  11612. * 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
  11613. * transformed to the given world matrix.
  11614. * @param origin The origin point
  11615. * @param end The end point
  11616. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11617. */
  11618. Ray.CreateNewFromTo = function (origin, end, world) {
  11619. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11620. var direction = end.subtract(origin);
  11621. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11622. direction.normalize();
  11623. return Ray.Transform(new Ray(origin, direction, length), world);
  11624. };
  11625. Ray.Transform = function (ray, matrix) {
  11626. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11627. Ray.TransformToRef(ray, matrix, result);
  11628. return result;
  11629. };
  11630. Ray.TransformToRef = function (ray, matrix, result) {
  11631. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11632. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11633. result.length = ray.length;
  11634. var dir = result.direction;
  11635. var len = dir.length();
  11636. if (!(len === 0 || len === 1)) {
  11637. var num = 1.0 / len;
  11638. dir.x *= num;
  11639. dir.y *= num;
  11640. dir.z *= num;
  11641. result.length *= len;
  11642. }
  11643. };
  11644. return Ray;
  11645. }());
  11646. Ray.smallnum = 0.00000001;
  11647. Ray.rayl = 10e8;
  11648. BABYLON.Ray = Ray;
  11649. })(BABYLON || (BABYLON = {}));
  11650. //# sourceMappingURL=babylon.ray.js.map
  11651. var BABYLON;
  11652. (function (BABYLON) {
  11653. var RayHelper = (function () {
  11654. function RayHelper(ray) {
  11655. this.ray = ray;
  11656. }
  11657. RayHelper.prototype.show = function (scene, color) {
  11658. if (!this._renderFunction) {
  11659. var ray = this.ray;
  11660. this._renderFunction = this._render.bind(this);
  11661. this._scene = scene;
  11662. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11663. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11664. this._scene.registerBeforeRender(this._renderFunction);
  11665. }
  11666. if (color) {
  11667. this._renderLine.color.copyFrom(color);
  11668. }
  11669. };
  11670. RayHelper.prototype.hide = function () {
  11671. if (this._renderFunction) {
  11672. this._scene.unregisterBeforeRender(this._renderFunction);
  11673. this._scene = null;
  11674. this._renderFunction = null;
  11675. this._renderLine.dispose();
  11676. this._renderLine = null;
  11677. this._renderPoints = null;
  11678. }
  11679. };
  11680. RayHelper.prototype._render = function () {
  11681. var ray = this.ray;
  11682. var point = this._renderPoints[1];
  11683. var len = Math.min(ray.length, 1000000);
  11684. point.copyFrom(ray.direction);
  11685. point.scaleInPlace(len);
  11686. point.addInPlace(ray.origin);
  11687. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11688. };
  11689. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11690. this._attachedToMesh = mesh;
  11691. var ray = this.ray;
  11692. if (!ray.direction) {
  11693. ray.direction = BABYLON.Vector3.Zero();
  11694. }
  11695. if (!ray.origin) {
  11696. ray.origin = BABYLON.Vector3.Zero();
  11697. }
  11698. if (length) {
  11699. ray.length = length;
  11700. }
  11701. if (!meshSpaceOrigin) {
  11702. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11703. }
  11704. if (!meshSpaceDirection) {
  11705. // -1 so that this will work with Mesh.lookAt
  11706. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11707. }
  11708. if (!this._meshSpaceDirection) {
  11709. this._meshSpaceDirection = meshSpaceDirection.clone();
  11710. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11711. }
  11712. else {
  11713. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11714. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11715. }
  11716. if (!this._updateToMeshFunction) {
  11717. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11718. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11719. }
  11720. this._updateToMesh();
  11721. };
  11722. RayHelper.prototype.detachFromMesh = function () {
  11723. if (this._attachedToMesh) {
  11724. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11725. this._attachedToMesh = null;
  11726. this._updateToMeshFunction = null;
  11727. }
  11728. };
  11729. RayHelper.prototype._updateToMesh = function () {
  11730. var ray = this.ray;
  11731. if (this._attachedToMesh._isDisposed) {
  11732. this.detachFromMesh();
  11733. return;
  11734. }
  11735. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  11736. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  11737. };
  11738. RayHelper.prototype.dispose = function () {
  11739. this.hide();
  11740. this.detachFromMesh();
  11741. this.ray = null;
  11742. };
  11743. return RayHelper;
  11744. }());
  11745. BABYLON.RayHelper = RayHelper;
  11746. })(BABYLON || (BABYLON = {}));
  11747. //# sourceMappingURL=babylon.rayHelper.js.map
  11748. var BABYLON;
  11749. (function (BABYLON) {
  11750. var AbstractMesh = (function (_super) {
  11751. __extends(AbstractMesh, _super);
  11752. // Constructor
  11753. function AbstractMesh(name, scene) {
  11754. var _this = _super.call(this, name, scene) || this;
  11755. _this._facetNb = 0; // facet number
  11756. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11757. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11758. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11759. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11760. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11761. _this._subDiv = {
  11762. max: 1,
  11763. X: 1,
  11764. Y: 1,
  11765. Z: 1
  11766. };
  11767. // Events
  11768. /**
  11769. * An event triggered when this mesh collides with another one
  11770. * @type {BABYLON.Observable}
  11771. */
  11772. _this.onCollideObservable = new BABYLON.Observable();
  11773. /**
  11774. * An event triggered when the collision's position changes
  11775. * @type {BABYLON.Observable}
  11776. */
  11777. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11778. /**
  11779. * An event triggered after the world matrix is updated
  11780. * @type {BABYLON.Observable}
  11781. */
  11782. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11783. // Properties
  11784. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11785. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11786. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11787. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11788. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11789. _this.visibility = 1.0;
  11790. _this.alphaIndex = Number.MAX_VALUE;
  11791. _this.infiniteDistance = false;
  11792. _this.isVisible = true;
  11793. _this.isPickable = true;
  11794. _this.showBoundingBox = false;
  11795. _this.showSubMeshesBoundingBox = false;
  11796. _this.isBlocker = false;
  11797. _this.renderingGroupId = 0;
  11798. _this.receiveShadows = false;
  11799. _this.renderOutline = false;
  11800. _this.outlineColor = BABYLON.Color3.Red();
  11801. _this.outlineWidth = 0.02;
  11802. _this.renderOverlay = false;
  11803. _this.overlayColor = BABYLON.Color3.Red();
  11804. _this.overlayAlpha = 0.5;
  11805. _this.hasVertexAlpha = false;
  11806. _this.useVertexColors = true;
  11807. _this.applyFog = true;
  11808. _this.computeBonesUsingShaders = true;
  11809. _this.scalingDeterminant = 1;
  11810. _this.numBoneInfluencers = 4;
  11811. _this.useOctreeForRenderingSelection = true;
  11812. _this.useOctreeForPicking = true;
  11813. _this.useOctreeForCollisions = true;
  11814. _this.layerMask = 0x0FFFFFFF;
  11815. /**
  11816. * True if the mesh must be rendered in any case.
  11817. */
  11818. _this.alwaysSelectAsActiveMesh = false;
  11819. // Collisions
  11820. _this._checkCollisions = false;
  11821. _this._collisionMask = -1;
  11822. _this._collisionGroup = -1;
  11823. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11824. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11825. _this._collider = new BABYLON.Collider();
  11826. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11827. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11828. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11829. // Edges
  11830. _this.edgesWidth = 1;
  11831. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11832. // Cache
  11833. _this._localWorld = BABYLON.Matrix.Zero();
  11834. _this._worldMatrix = BABYLON.Matrix.Zero();
  11835. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  11836. _this._absolutePosition = BABYLON.Vector3.Zero();
  11837. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11838. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11839. _this._isDirty = false;
  11840. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11841. _this._isDisposed = false;
  11842. _this._renderId = 0;
  11843. _this._intersectionsInProgress = new Array();
  11844. _this._isWorldMatrixFrozen = false;
  11845. _this._unIndexed = false;
  11846. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11847. if (collidedMesh === void 0) { collidedMesh = null; }
  11848. //TODO move this to the collision coordinator!
  11849. if (_this.getScene().workerCollisions)
  11850. newPosition.multiplyInPlace(_this._collider.radius);
  11851. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11852. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11853. _this.position.addInPlace(_this._diffPositionForCollisions);
  11854. }
  11855. if (collidedMesh) {
  11856. _this.onCollideObservable.notifyObservers(collidedMesh);
  11857. }
  11858. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11859. };
  11860. scene.addMesh(_this);
  11861. return _this;
  11862. }
  11863. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11864. get: function () {
  11865. return AbstractMesh._BILLBOARDMODE_NONE;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11871. get: function () {
  11872. return AbstractMesh._BILLBOARDMODE_X;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11878. get: function () {
  11879. return AbstractMesh._BILLBOARDMODE_Y;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11885. get: function () {
  11886. return AbstractMesh._BILLBOARDMODE_Z;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11892. get: function () {
  11893. return AbstractMesh._BILLBOARDMODE_ALL;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11899. /**
  11900. * Read-only : the number of facets in the mesh
  11901. */
  11902. get: function () {
  11903. return this._facetNb;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11909. /**
  11910. * The number (integer) of subdivisions per axis in the partioning space
  11911. */
  11912. get: function () {
  11913. return this._partitioningSubdivisions;
  11914. },
  11915. set: function (nb) {
  11916. this._partitioningSubdivisions = nb;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11922. /**
  11923. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11924. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11925. */
  11926. get: function () {
  11927. return this._partitioningBBoxRatio;
  11928. },
  11929. set: function (ratio) {
  11930. this._partitioningBBoxRatio = ratio;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11936. /**
  11937. * Read-only boolean : is the feature facetData enabled ?
  11938. */
  11939. get: function () {
  11940. return this._facetDataEnabled;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11946. set: function (callback) {
  11947. if (this._onCollideObserver) {
  11948. this.onCollideObservable.remove(this._onCollideObserver);
  11949. }
  11950. this._onCollideObserver = this.onCollideObservable.add(callback);
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11956. set: function (callback) {
  11957. if (this._onCollisionPositionChangeObserver) {
  11958. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11959. }
  11960. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11966. get: function () {
  11967. return this._collisionMask;
  11968. },
  11969. set: function (mask) {
  11970. this._collisionMask = !isNaN(mask) ? mask : -1;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11976. get: function () {
  11977. return this._collisionGroup;
  11978. },
  11979. set: function (mask) {
  11980. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11986. get: function () {
  11987. return this._skeleton;
  11988. },
  11989. set: function (value) {
  11990. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11991. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11992. }
  11993. if (value && value.needInitialSkinMatrix) {
  11994. value._registerMeshWithPoseMatrix(this);
  11995. }
  11996. this._skeleton = value;
  11997. if (!this._skeleton) {
  11998. this._bonesTransformMatrices = null;
  11999. }
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. /**
  12005. * Returns the string "AbstractMesh"
  12006. */
  12007. AbstractMesh.prototype.getClassName = function () {
  12008. return "AbstractMesh";
  12009. };
  12010. /**
  12011. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12012. */
  12013. AbstractMesh.prototype.toString = function (fullDetails) {
  12014. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12015. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12016. if (this._skeleton) {
  12017. ret += ", skeleton: " + this._skeleton.name;
  12018. }
  12019. if (fullDetails) {
  12020. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12021. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12022. }
  12023. return ret;
  12024. };
  12025. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12026. /**
  12027. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12028. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12029. * Default : (0.0, 0.0, 0.0)
  12030. */
  12031. get: function () {
  12032. return this._rotation;
  12033. },
  12034. set: function (newRotation) {
  12035. this._rotation = newRotation;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12041. /**
  12042. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12043. * Default : (1.0, 1.0, 1.0)
  12044. */
  12045. get: function () {
  12046. return this._scaling;
  12047. },
  12048. set: function (newScaling) {
  12049. this._scaling = newScaling;
  12050. if (this.physicsImpostor) {
  12051. this.physicsImpostor.forceUpdate();
  12052. }
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12058. /**
  12059. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12060. * It's null by default.
  12061. * 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)
  12062. */
  12063. get: function () {
  12064. return this._rotationQuaternion;
  12065. },
  12066. set: function (quaternion) {
  12067. this._rotationQuaternion = quaternion;
  12068. //reset the rotation vector.
  12069. if (quaternion && this.rotation.length()) {
  12070. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12071. }
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. // Methods
  12077. /**
  12078. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12079. * Returns the AbstractMesh.
  12080. */
  12081. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12082. this._poseMatrix.copyFrom(matrix);
  12083. return this;
  12084. };
  12085. /**
  12086. * Returns the mesh Pose matrix.
  12087. * Returned object : Matrix
  12088. */
  12089. AbstractMesh.prototype.getPoseMatrix = function () {
  12090. return this._poseMatrix;
  12091. };
  12092. /**
  12093. * Disables the mesh edger rendering mode.
  12094. * Returns the AbstractMesh.
  12095. */
  12096. AbstractMesh.prototype.disableEdgesRendering = function () {
  12097. if (this._edgesRenderer !== undefined) {
  12098. this._edgesRenderer.dispose();
  12099. this._edgesRenderer = undefined;
  12100. }
  12101. return this;
  12102. };
  12103. /**
  12104. * Enables the edge rendering mode on the mesh.
  12105. * This mode makes the mesh edges visible.
  12106. * Returns the AbstractMesh.
  12107. */
  12108. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12109. if (epsilon === void 0) { epsilon = 0.95; }
  12110. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12111. this.disableEdgesRendering();
  12112. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12113. return this;
  12114. };
  12115. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12116. /**
  12117. * Returns true if the mesh is blocked. Used by the class Mesh.
  12118. * Returns the boolean `false` by default.
  12119. */
  12120. get: function () {
  12121. return false;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. /**
  12127. * Returns the mesh itself by default, used by the class Mesh.
  12128. * Returned type : AbstractMesh
  12129. */
  12130. AbstractMesh.prototype.getLOD = function (camera) {
  12131. return this;
  12132. };
  12133. /**
  12134. * Returns 0 by default, used by the class Mesh.
  12135. * Returns an integer.
  12136. */
  12137. AbstractMesh.prototype.getTotalVertices = function () {
  12138. return 0;
  12139. };
  12140. /**
  12141. * Returns null by default, used by the class Mesh.
  12142. * Returned type : integer array
  12143. */
  12144. AbstractMesh.prototype.getIndices = function () {
  12145. return null;
  12146. };
  12147. /**
  12148. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12149. * Returned type : float array or Float32Array
  12150. */
  12151. AbstractMesh.prototype.getVerticesData = function (kind) {
  12152. return null;
  12153. };
  12154. /** Returns false by default, used by the class Mesh.
  12155. * Returns a boolean
  12156. */
  12157. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12158. return false;
  12159. };
  12160. /**
  12161. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12162. * Returns a BoundingInfo
  12163. */
  12164. AbstractMesh.prototype.getBoundingInfo = function () {
  12165. if (this._masterMesh) {
  12166. return this._masterMesh.getBoundingInfo();
  12167. }
  12168. if (!this._boundingInfo) {
  12169. this._updateBoundingInfo();
  12170. }
  12171. return this._boundingInfo;
  12172. };
  12173. /**
  12174. * Sets a mesh new object BoundingInfo.
  12175. * Returns the AbstractMesh.
  12176. */
  12177. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12178. this._boundingInfo = boundingInfo;
  12179. return this;
  12180. };
  12181. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12182. get: function () {
  12183. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. AbstractMesh.prototype._preActivate = function () {
  12189. };
  12190. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12191. };
  12192. AbstractMesh.prototype._activate = function (renderId) {
  12193. this._renderId = renderId;
  12194. };
  12195. /**
  12196. * Returns the last update of the World matrix
  12197. * Returns a Matrix.
  12198. */
  12199. AbstractMesh.prototype.getWorldMatrix = function () {
  12200. if (this._masterMesh) {
  12201. return this._masterMesh.getWorldMatrix();
  12202. }
  12203. if (this._currentRenderId !== this.getScene().getRenderId()) {
  12204. this.computeWorldMatrix();
  12205. }
  12206. return this._worldMatrix;
  12207. };
  12208. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12209. /**
  12210. * Returns directly the last state of the mesh World matrix.
  12211. * A Matrix is returned.
  12212. */
  12213. get: function () {
  12214. return this._worldMatrix;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12220. /**
  12221. * Returns the current mesh absolute position.
  12222. * Retuns a Vector3.
  12223. */
  12224. get: function () {
  12225. return this._absolutePosition;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. /**
  12231. * Prevents the World matrix to be computed any longer.
  12232. * Returns the AbstractMesh.
  12233. */
  12234. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12235. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12236. this.computeWorldMatrix(true);
  12237. this._isWorldMatrixFrozen = true;
  12238. return this;
  12239. };
  12240. /**
  12241. * Allows back the World matrix computation.
  12242. * Returns the AbstractMesh.
  12243. */
  12244. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12245. this._isWorldMatrixFrozen = false;
  12246. this.computeWorldMatrix(true);
  12247. return this;
  12248. };
  12249. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12250. /**
  12251. * True if the World matrix has been frozen.
  12252. * Returns a boolean.
  12253. */
  12254. get: function () {
  12255. return this._isWorldMatrixFrozen;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. /**
  12261. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12262. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12263. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12264. * The passed axis is also normalized.
  12265. * Returns the AbstractMesh.
  12266. */
  12267. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12268. axis.normalize();
  12269. if (!this.rotationQuaternion) {
  12270. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12271. this.rotation = BABYLON.Vector3.Zero();
  12272. }
  12273. var rotationQuaternion;
  12274. if (!space || space === BABYLON.Space.LOCAL) {
  12275. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12276. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12277. }
  12278. else {
  12279. if (this.parent) {
  12280. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12281. invertParentWorldMatrix.invert();
  12282. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12283. }
  12284. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12285. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12286. }
  12287. return this;
  12288. };
  12289. /**
  12290. * Translates the mesh along the axis vector for the passed distance in the given space.
  12291. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12292. * Returns the AbstractMesh.
  12293. */
  12294. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12295. var displacementVector = axis.scale(distance);
  12296. if (!space || space === BABYLON.Space.LOCAL) {
  12297. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12298. this.setPositionWithLocalVector(tempV3);
  12299. }
  12300. else {
  12301. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12302. }
  12303. return this;
  12304. };
  12305. /**
  12306. * Adds a rotation step to the mesh current rotation.
  12307. * x, y, z are Euler angles expressed in radians.
  12308. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12309. * This means this rotation is made in the mesh local space only.
  12310. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12311. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12312. * ```javascript
  12313. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12314. * ```
  12315. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12316. * 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.
  12317. * Returns the AbstractMesh.
  12318. */
  12319. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12320. var rotationQuaternion;
  12321. if (this.rotationQuaternion) {
  12322. rotationQuaternion = this.rotationQuaternion;
  12323. }
  12324. else {
  12325. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12326. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12327. }
  12328. var accumulation = BABYLON.Tmp.Quaternion[0];
  12329. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12330. rotationQuaternion.multiplyInPlace(accumulation);
  12331. if (!this.rotationQuaternion) {
  12332. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12333. }
  12334. return this;
  12335. };
  12336. /**
  12337. * Retuns the mesh absolute position in the World.
  12338. * Returns a Vector3.
  12339. */
  12340. AbstractMesh.prototype.getAbsolutePosition = function () {
  12341. this.computeWorldMatrix();
  12342. return this._absolutePosition;
  12343. };
  12344. /**
  12345. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12346. * Returns the AbstractMesh.
  12347. */
  12348. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12349. if (!absolutePosition) {
  12350. return;
  12351. }
  12352. var absolutePositionX;
  12353. var absolutePositionY;
  12354. var absolutePositionZ;
  12355. if (absolutePosition.x === undefined) {
  12356. if (arguments.length < 3) {
  12357. return;
  12358. }
  12359. absolutePositionX = arguments[0];
  12360. absolutePositionY = arguments[1];
  12361. absolutePositionZ = arguments[2];
  12362. }
  12363. else {
  12364. absolutePositionX = absolutePosition.x;
  12365. absolutePositionY = absolutePosition.y;
  12366. absolutePositionZ = absolutePosition.z;
  12367. }
  12368. if (this.parent) {
  12369. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12370. invertParentWorldMatrix.invert();
  12371. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12372. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12373. }
  12374. else {
  12375. this.position.x = absolutePositionX;
  12376. this.position.y = absolutePositionY;
  12377. this.position.z = absolutePositionZ;
  12378. }
  12379. return this;
  12380. };
  12381. // ================================== Point of View Movement =================================
  12382. /**
  12383. * Perform relative position change from the point of view of behind the front of the mesh.
  12384. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12385. * Supports definition of mesh facing forward or backward.
  12386. * @param {number} amountRight
  12387. * @param {number} amountUp
  12388. * @param {number} amountForward
  12389. *
  12390. * Returns the AbstractMesh.
  12391. */
  12392. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12393. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12394. return this;
  12395. };
  12396. /**
  12397. * Calculate relative position change from the point of view of behind the front of the mesh.
  12398. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12399. * Supports definition of mesh facing forward or backward.
  12400. * @param {number} amountRight
  12401. * @param {number} amountUp
  12402. * @param {number} amountForward
  12403. *
  12404. * Returns a new Vector3.
  12405. */
  12406. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12407. var rotMatrix = new BABYLON.Matrix();
  12408. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12409. rotQuaternion.toRotationMatrix(rotMatrix);
  12410. var translationDelta = BABYLON.Vector3.Zero();
  12411. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12413. return translationDelta;
  12414. };
  12415. // ================================== Point of View Rotation =================================
  12416. /**
  12417. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12418. * Supports definition of mesh facing forward or backward.
  12419. * @param {number} flipBack
  12420. * @param {number} twirlClockwise
  12421. * @param {number} tiltRight
  12422. *
  12423. * Returns the AbstractMesh.
  12424. */
  12425. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12426. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12427. return this;
  12428. };
  12429. /**
  12430. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12431. * Supports definition of mesh facing forward or backward.
  12432. * @param {number} flipBack
  12433. * @param {number} twirlClockwise
  12434. * @param {number} tiltRight
  12435. *
  12436. * Returns a new Vector3.
  12437. */
  12438. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12439. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12440. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12441. };
  12442. /**
  12443. * Sets a new pivot matrix to the mesh.
  12444. * Returns the AbstractMesh.
  12445. */
  12446. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12447. this._pivotMatrix = matrix;
  12448. this._cache.pivotMatrixUpdated = true;
  12449. return this;
  12450. };
  12451. /**
  12452. * Returns the mesh pivot matrix.
  12453. * Default : Identity.
  12454. * A Matrix is returned.
  12455. */
  12456. AbstractMesh.prototype.getPivotMatrix = function () {
  12457. return this._pivotMatrix;
  12458. };
  12459. AbstractMesh.prototype._isSynchronized = function () {
  12460. if (this._isDirty) {
  12461. return false;
  12462. }
  12463. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12464. return false;
  12465. if (this._cache.pivotMatrixUpdated) {
  12466. return false;
  12467. }
  12468. if (this.infiniteDistance) {
  12469. return false;
  12470. }
  12471. if (!this._cache.position.equals(this.position))
  12472. return false;
  12473. if (this.rotationQuaternion) {
  12474. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12475. return false;
  12476. }
  12477. if (!this._cache.rotation.equals(this.rotation))
  12478. return false;
  12479. if (!this._cache.scaling.equals(this.scaling))
  12480. return false;
  12481. return true;
  12482. };
  12483. AbstractMesh.prototype._initCache = function () {
  12484. _super.prototype._initCache.call(this);
  12485. this._cache.localMatrixUpdated = false;
  12486. this._cache.position = BABYLON.Vector3.Zero();
  12487. this._cache.scaling = BABYLON.Vector3.Zero();
  12488. this._cache.rotation = BABYLON.Vector3.Zero();
  12489. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12490. this._cache.billboardMode = -1;
  12491. };
  12492. AbstractMesh.prototype.markAsDirty = function (property) {
  12493. if (property === "rotation") {
  12494. this.rotationQuaternion = null;
  12495. }
  12496. this._currentRenderId = Number.MAX_VALUE;
  12497. this._isDirty = true;
  12498. return this;
  12499. };
  12500. /**
  12501. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12502. * Returns the AbstractMesh.
  12503. */
  12504. AbstractMesh.prototype._updateBoundingInfo = function () {
  12505. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12506. this._boundingInfo.update(this.worldMatrixFromCache);
  12507. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12508. return this;
  12509. };
  12510. /**
  12511. * Update a mesh's children BoundingInfo objects only.
  12512. * Returns the AbstractMesh.
  12513. */
  12514. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12515. if (!this.subMeshes) {
  12516. return;
  12517. }
  12518. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12519. var subMesh = this.subMeshes[subIndex];
  12520. if (!subMesh.IsGlobal) {
  12521. subMesh.updateBoundingInfo(matrix);
  12522. }
  12523. }
  12524. return this;
  12525. };
  12526. /**
  12527. * Computes the mesh World matrix and returns it.
  12528. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12529. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12530. * If the parameter `force`is set to `true`, the actual computation is done.
  12531. * Returns the mesh World Matrix.
  12532. */
  12533. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12534. if (this._isWorldMatrixFrozen) {
  12535. return this._worldMatrix;
  12536. }
  12537. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  12538. this._currentRenderId = this.getScene().getRenderId();
  12539. return this._worldMatrix;
  12540. }
  12541. this._cache.position.copyFrom(this.position);
  12542. this._cache.scaling.copyFrom(this.scaling);
  12543. this._cache.pivotMatrixUpdated = false;
  12544. this._cache.billboardMode = this.billboardMode;
  12545. this._currentRenderId = this.getScene().getRenderId();
  12546. this._isDirty = false;
  12547. // Scaling
  12548. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12549. // Rotation
  12550. //rotate, if quaternion is set and rotation was used
  12551. if (this.rotationQuaternion) {
  12552. var len = this.rotation.length();
  12553. if (len) {
  12554. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12555. this.rotation.copyFromFloats(0, 0, 0);
  12556. }
  12557. }
  12558. if (this.rotationQuaternion) {
  12559. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12560. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12561. }
  12562. else {
  12563. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12564. this._cache.rotation.copyFrom(this.rotation);
  12565. }
  12566. // Translation
  12567. if (this.infiniteDistance && !this.parent) {
  12568. var camera = this.getScene().activeCamera;
  12569. if (camera) {
  12570. var cameraWorldMatrix = camera.getWorldMatrix();
  12571. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12572. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12573. }
  12574. }
  12575. else {
  12576. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12577. }
  12578. // Composing transformations
  12579. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12580. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12581. // Billboarding
  12582. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12583. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  12584. var localPosition = BABYLON.Tmp.Vector3[0];
  12585. if (this.parent && this.parent.getWorldMatrix) {
  12586. this._markSyncedWithParent();
  12587. var parentMatrix;
  12588. if (this._meshToBoneReferal) {
  12589. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12590. parentMatrix = BABYLON.Tmp.Matrix[6];
  12591. }
  12592. else {
  12593. parentMatrix = this.parent.getWorldMatrix();
  12594. }
  12595. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  12596. localPosition = BABYLON.Tmp.Vector3[1];
  12597. }
  12598. var zero = this.getScene().activeCamera.globalPosition.clone();
  12599. if (this.parent && this.parent.position) {
  12600. localPosition.addInPlace(this.parent.position);
  12601. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  12602. }
  12603. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12604. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  12605. zero.x = localPosition.x + BABYLON.Epsilon;
  12606. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  12607. zero.y = localPosition.y + BABYLON.Epsilon;
  12608. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  12609. zero.z = localPosition.z + BABYLON.Epsilon;
  12610. }
  12611. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  12612. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  12613. BABYLON.Tmp.Matrix[3].invert();
  12614. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  12615. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  12616. }
  12617. // Local world
  12618. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12619. // Parent
  12620. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  12621. this._markSyncedWithParent();
  12622. if (this._meshToBoneReferal) {
  12623. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12624. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12625. }
  12626. else {
  12627. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12628. }
  12629. }
  12630. else {
  12631. this._worldMatrix.copyFrom(this._localWorld);
  12632. }
  12633. // Bounding info
  12634. this._updateBoundingInfo();
  12635. // Absolute position
  12636. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12637. // Callbacks
  12638. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12639. if (!this._poseMatrix) {
  12640. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12641. }
  12642. return this._worldMatrix;
  12643. };
  12644. /**
  12645. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12646. * @param func: callback function to add
  12647. *
  12648. * Returns the AbstractMesh.
  12649. */
  12650. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12651. this.onAfterWorldMatrixUpdateObservable.add(func);
  12652. return this;
  12653. };
  12654. /**
  12655. * Removes a registered callback function.
  12656. * Returns the AbstractMesh.
  12657. */
  12658. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12659. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12660. return this;
  12661. };
  12662. /**
  12663. * Sets the mesh position in its local space.
  12664. * Returns the AbstractMesh.
  12665. */
  12666. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12667. this.computeWorldMatrix();
  12668. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12669. return this;
  12670. };
  12671. /**
  12672. * Returns the mesh position in the local space from the current World matrix values.
  12673. * Returns a new Vector3.
  12674. */
  12675. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12676. this.computeWorldMatrix();
  12677. var invLocalWorldMatrix = this._localWorld.clone();
  12678. invLocalWorldMatrix.invert();
  12679. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12680. };
  12681. /**
  12682. * Translates the mesh along the passed Vector3 in its local space.
  12683. * Returns the AbstractMesh.
  12684. */
  12685. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12686. this.computeWorldMatrix(true);
  12687. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12688. return this;
  12689. };
  12690. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12691. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12692. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12693. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12694. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12695. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12696. /// <returns>Mesh oriented towards targetMesh</returns>
  12697. if (yawCor === void 0) { yawCor = 0; }
  12698. if (pitchCor === void 0) { pitchCor = 0; }
  12699. if (rollCor === void 0) { rollCor = 0; }
  12700. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12701. var dv = AbstractMesh._lookAtVectorCache;
  12702. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12703. targetPoint.subtractToRef(pos, dv);
  12704. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12705. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12706. var pitch = Math.atan2(dv.y, len);
  12707. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12708. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12709. return this;
  12710. };
  12711. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12712. this._meshToBoneReferal = affectedMesh;
  12713. this.parent = bone;
  12714. if (bone.getWorldMatrix().determinant() < 0) {
  12715. this.scalingDeterminant *= -1;
  12716. }
  12717. return this;
  12718. };
  12719. AbstractMesh.prototype.detachFromBone = function () {
  12720. if (this.parent.getWorldMatrix().determinant() < 0) {
  12721. this.scalingDeterminant *= -1;
  12722. }
  12723. this._meshToBoneReferal = null;
  12724. this.parent = null;
  12725. return this;
  12726. };
  12727. /**
  12728. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12729. * A mesh is in the frustum if its bounding box intersects the frustum.
  12730. * Boolean returned.
  12731. */
  12732. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12733. return this._boundingInfo.isInFrustum(frustumPlanes);
  12734. };
  12735. /**
  12736. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12737. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12738. * Boolean returned.
  12739. */
  12740. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12741. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12742. ;
  12743. };
  12744. /**
  12745. * True if the mesh intersects another mesh or a SolidParticle object.
  12746. * 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)
  12747. * Returns a boolean.
  12748. */
  12749. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12750. if (!this._boundingInfo || !mesh._boundingInfo) {
  12751. return false;
  12752. }
  12753. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12754. };
  12755. /**
  12756. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12757. * Returns a boolean.
  12758. */
  12759. AbstractMesh.prototype.intersectsPoint = function (point) {
  12760. if (!this._boundingInfo) {
  12761. return false;
  12762. }
  12763. return this._boundingInfo.intersectsPoint(point);
  12764. };
  12765. // Physics
  12766. /**
  12767. * @Deprecated. Use new PhysicsImpostor instead.
  12768. * */
  12769. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  12770. //legacy support
  12771. if (impostor.impostor) {
  12772. options = impostor;
  12773. impostor = impostor.impostor;
  12774. }
  12775. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  12776. return this.physicsImpostor.physicsBody;
  12777. };
  12778. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12779. return this.physicsImpostor;
  12780. };
  12781. /**
  12782. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  12783. */
  12784. AbstractMesh.prototype.getPhysicsMass = function () {
  12785. return this.physicsImpostor.getParam("mass");
  12786. };
  12787. /**
  12788. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  12789. */
  12790. AbstractMesh.prototype.getPhysicsFriction = function () {
  12791. return this.physicsImpostor.getParam("friction");
  12792. };
  12793. /**
  12794. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  12795. */
  12796. AbstractMesh.prototype.getPhysicsRestitution = function () {
  12797. return this.physicsImpostor.getParam("restitution");
  12798. };
  12799. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12800. if (!camera) {
  12801. camera = this.getScene().activeCamera;
  12802. }
  12803. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12804. };
  12805. /**
  12806. * Returns the distance from the mesh to the active camera.
  12807. * Returns a float.
  12808. */
  12809. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12810. if (!camera) {
  12811. camera = this.getScene().activeCamera;
  12812. }
  12813. return this.absolutePosition.subtract(camera.position).length();
  12814. };
  12815. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12816. if (!this.physicsImpostor) {
  12817. return;
  12818. }
  12819. this.physicsImpostor.applyImpulse(force, contactPoint);
  12820. return this;
  12821. };
  12822. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12823. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12824. return;
  12825. }
  12826. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12827. mainPivot: pivot1,
  12828. connectedPivot: pivot2,
  12829. nativeParams: options
  12830. });
  12831. return this;
  12832. };
  12833. /**
  12834. * @Deprecated
  12835. */
  12836. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  12837. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  12838. this.updatePhysicsBody();
  12839. };
  12840. /**
  12841. * @Deprecated
  12842. * Calling this function is not needed anymore.
  12843. * The physics engine takes care of transofmration automatically.
  12844. */
  12845. AbstractMesh.prototype.updatePhysicsBody = function () {
  12846. //Unneeded
  12847. };
  12848. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12849. // Collisions
  12850. /**
  12851. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12852. * Default `false`.
  12853. */
  12854. get: function () {
  12855. return this._checkCollisions;
  12856. },
  12857. set: function (collisionEnabled) {
  12858. this._checkCollisions = collisionEnabled;
  12859. if (this.getScene().workerCollisions) {
  12860. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12861. }
  12862. },
  12863. enumerable: true,
  12864. configurable: true
  12865. });
  12866. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12867. var globalPosition = this.getAbsolutePosition();
  12868. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12869. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12870. this._collider.radius = this.ellipsoid;
  12871. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12872. return this;
  12873. };
  12874. // Submeshes octree
  12875. /**
  12876. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12877. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12878. * Returns an Octree of submeshes.
  12879. */
  12880. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12881. if (maxCapacity === void 0) { maxCapacity = 64; }
  12882. if (maxDepth === void 0) { maxDepth = 2; }
  12883. if (!this._submeshesOctree) {
  12884. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12885. }
  12886. this.computeWorldMatrix(true);
  12887. // Update octree
  12888. var bbox = this.getBoundingInfo().boundingBox;
  12889. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12890. return this._submeshesOctree;
  12891. };
  12892. // Collisions
  12893. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12894. this._generatePointsArray();
  12895. // Transformation
  12896. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12897. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12898. subMesh._lastColliderWorldVertices = [];
  12899. subMesh._trianglePlanes = [];
  12900. var start = subMesh.verticesStart;
  12901. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12902. for (var i = start; i < end; i++) {
  12903. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12904. }
  12905. }
  12906. // Collide
  12907. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12908. if (collider.collisionFound) {
  12909. collider.collidedMesh = this;
  12910. }
  12911. return this;
  12912. };
  12913. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12914. var subMeshes;
  12915. var len;
  12916. // Octrees
  12917. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12918. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12919. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12920. len = intersections.length;
  12921. subMeshes = intersections.data;
  12922. }
  12923. else {
  12924. subMeshes = this.subMeshes;
  12925. len = subMeshes.length;
  12926. }
  12927. for (var index = 0; index < len; index++) {
  12928. var subMesh = subMeshes[index];
  12929. // Bounding test
  12930. if (len > 1 && !subMesh._checkCollision(collider))
  12931. continue;
  12932. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12933. }
  12934. return this;
  12935. };
  12936. AbstractMesh.prototype._checkCollision = function (collider) {
  12937. // Bounding box test
  12938. if (!this._boundingInfo._checkCollision(collider))
  12939. return this;
  12940. // Transformation matrix
  12941. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12942. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12943. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12944. return this;
  12945. };
  12946. // Picking
  12947. AbstractMesh.prototype._generatePointsArray = function () {
  12948. return false;
  12949. };
  12950. /**
  12951. * Checks if the passed Ray intersects with the mesh.
  12952. * Returns an object PickingInfo.
  12953. */
  12954. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12955. var pickingInfo = new BABYLON.PickingInfo();
  12956. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12957. return pickingInfo;
  12958. }
  12959. if (!this._generatePointsArray()) {
  12960. return pickingInfo;
  12961. }
  12962. var intersectInfo = null;
  12963. // Octrees
  12964. var subMeshes;
  12965. var len;
  12966. if (this._submeshesOctree && this.useOctreeForPicking) {
  12967. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12968. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12969. len = intersections.length;
  12970. subMeshes = intersections.data;
  12971. }
  12972. else {
  12973. subMeshes = this.subMeshes;
  12974. len = subMeshes.length;
  12975. }
  12976. for (var index = 0; index < len; index++) {
  12977. var subMesh = subMeshes[index];
  12978. // Bounding test
  12979. if (len > 1 && !subMesh.canIntersects(ray))
  12980. continue;
  12981. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12982. if (currentIntersectInfo) {
  12983. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12984. intersectInfo = currentIntersectInfo;
  12985. intersectInfo.subMeshId = index;
  12986. if (fastCheck) {
  12987. break;
  12988. }
  12989. }
  12990. }
  12991. }
  12992. if (intersectInfo) {
  12993. // Get picked point
  12994. var world = this.getWorldMatrix();
  12995. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12996. var direction = ray.direction.clone();
  12997. direction = direction.scale(intersectInfo.distance);
  12998. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12999. var pickedPoint = worldOrigin.add(worldDirection);
  13000. // Return result
  13001. pickingInfo.hit = true;
  13002. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13003. pickingInfo.pickedPoint = pickedPoint;
  13004. pickingInfo.pickedMesh = this;
  13005. pickingInfo.bu = intersectInfo.bu;
  13006. pickingInfo.bv = intersectInfo.bv;
  13007. pickingInfo.faceId = intersectInfo.faceId;
  13008. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13009. return pickingInfo;
  13010. }
  13011. return pickingInfo;
  13012. };
  13013. /**
  13014. * Clones the mesh, used by the class Mesh.
  13015. * Just returns `null` for an AbstractMesh.
  13016. */
  13017. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13018. return null;
  13019. };
  13020. /**
  13021. * Disposes all the mesh submeshes.
  13022. * Returns the AbstractMesh.
  13023. */
  13024. AbstractMesh.prototype.releaseSubMeshes = function () {
  13025. if (this.subMeshes) {
  13026. while (this.subMeshes.length) {
  13027. this.subMeshes[0].dispose();
  13028. }
  13029. }
  13030. else {
  13031. this.subMeshes = new Array();
  13032. }
  13033. return this;
  13034. };
  13035. /**
  13036. * Disposes the AbstractMesh.
  13037. * Some internal references are kept for further use.
  13038. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13039. * Returns nothing.
  13040. */
  13041. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13042. var _this = this;
  13043. var index;
  13044. // Action manager
  13045. if (this.actionManager) {
  13046. this.actionManager.dispose();
  13047. this.actionManager = null;
  13048. }
  13049. // Skeleton
  13050. this.skeleton = null;
  13051. // Animations
  13052. this.getScene().stopAnimation(this);
  13053. // Physics
  13054. if (this.physicsImpostor) {
  13055. this.physicsImpostor.dispose();
  13056. }
  13057. // Intersections in progress
  13058. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13059. var other = this._intersectionsInProgress[index];
  13060. var pos = other._intersectionsInProgress.indexOf(this);
  13061. other._intersectionsInProgress.splice(pos, 1);
  13062. }
  13063. this._intersectionsInProgress = [];
  13064. // Lights
  13065. var lights = this.getScene().lights;
  13066. lights.forEach(function (light) {
  13067. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13068. if (meshIndex !== -1) {
  13069. light.includedOnlyMeshes.splice(meshIndex, 1);
  13070. }
  13071. meshIndex = light.excludedMeshes.indexOf(_this);
  13072. if (meshIndex !== -1) {
  13073. light.excludedMeshes.splice(meshIndex, 1);
  13074. }
  13075. // Shadow generators
  13076. var generator = light.getShadowGenerator();
  13077. if (generator) {
  13078. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13079. if (meshIndex !== -1) {
  13080. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13081. }
  13082. }
  13083. });
  13084. // Edges
  13085. if (this._edgesRenderer) {
  13086. this._edgesRenderer.dispose();
  13087. this._edgesRenderer = null;
  13088. }
  13089. // SubMeshes
  13090. if (this.getClassName() !== "InstancedMesh") {
  13091. this.releaseSubMeshes();
  13092. }
  13093. // Engine
  13094. this.getScene().getEngine().wipeCaches();
  13095. // Remove from scene
  13096. this.getScene().removeMesh(this);
  13097. if (!doNotRecurse) {
  13098. // Particles
  13099. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13100. if (this.getScene().particleSystems[index].emitter === this) {
  13101. this.getScene().particleSystems[index].dispose();
  13102. index--;
  13103. }
  13104. }
  13105. // Children
  13106. var objects = this.getDescendants(true);
  13107. for (index = 0; index < objects.length; index++) {
  13108. objects[index].dispose();
  13109. }
  13110. }
  13111. else {
  13112. var childMeshes = this.getChildMeshes(true);
  13113. for (index = 0; index < childMeshes.length; index++) {
  13114. var child = childMeshes[index];
  13115. child.parent = null;
  13116. child.computeWorldMatrix(true);
  13117. }
  13118. }
  13119. // facet data
  13120. if (this._facetDataEnabled) {
  13121. this.disableFacetData();
  13122. }
  13123. this.onAfterWorldMatrixUpdateObservable.clear();
  13124. this.onCollideObservable.clear();
  13125. this.onCollisionPositionChangeObservable.clear();
  13126. this._isDisposed = true;
  13127. _super.prototype.dispose.call(this);
  13128. };
  13129. /**
  13130. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13131. * This Vector3 is expressed in the World space.
  13132. */
  13133. AbstractMesh.prototype.getDirection = function (localAxis) {
  13134. var result = BABYLON.Vector3.Zero();
  13135. this.getDirectionToRef(localAxis, result);
  13136. return result;
  13137. };
  13138. /**
  13139. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13140. * localAxis is expressed in the mesh local space.
  13141. * result is computed in the Wordl space from the mesh World matrix.
  13142. * Returns the AbstractMesh.
  13143. */
  13144. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13145. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13146. return this;
  13147. };
  13148. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13150. if (this.getScene().getRenderId() == 0) {
  13151. this.computeWorldMatrix(true);
  13152. }
  13153. var wm = this.getWorldMatrix();
  13154. if (space == BABYLON.Space.WORLD) {
  13155. var tmat = BABYLON.Tmp.Matrix[0];
  13156. wm.invertToRef(tmat);
  13157. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13158. }
  13159. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13160. this._pivotMatrix.m[12] = -point.x;
  13161. this._pivotMatrix.m[13] = -point.y;
  13162. this._pivotMatrix.m[14] = -point.z;
  13163. this._cache.pivotMatrixUpdated = true;
  13164. return this;
  13165. };
  13166. /**
  13167. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13168. */
  13169. AbstractMesh.prototype.getPivotPoint = function () {
  13170. var point = BABYLON.Vector3.Zero();
  13171. this.getPivotPointToRef(point);
  13172. return point;
  13173. };
  13174. /**
  13175. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13176. * Returns the AbstractMesh.
  13177. */
  13178. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13179. result.x = -this._pivotMatrix.m[12];
  13180. result.y = -this._pivotMatrix.m[13];
  13181. result.z = -this._pivotMatrix.m[14];
  13182. return this;
  13183. };
  13184. /**
  13185. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13186. */
  13187. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13188. var point = BABYLON.Vector3.Zero();
  13189. this.getAbsolutePivotPointToRef(point);
  13190. return point;
  13191. };
  13192. /**
  13193. * Defines the passed mesh as the parent of the current mesh.
  13194. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13195. * Returns the AbstractMesh.
  13196. */
  13197. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13198. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13199. var child = this;
  13200. var parent = mesh;
  13201. if (mesh == null) {
  13202. if (child.parent && keepWorldPositionRotation) {
  13203. var rotation = BABYLON.Tmp.Quaternion[0];
  13204. var position = BABYLON.Tmp.Vector3[0];
  13205. var scale = BABYLON.Tmp.Vector3[1];
  13206. child.getWorldMatrix().decompose(scale, rotation, position);
  13207. if (child.rotationQuaternion) {
  13208. child.rotationQuaternion.copyFrom(rotation);
  13209. }
  13210. else {
  13211. rotation.toEulerAnglesToRef(child.rotation);
  13212. }
  13213. child.position.x = position.x;
  13214. child.position.y = position.y;
  13215. child.position.z = position.z;
  13216. }
  13217. }
  13218. else {
  13219. if (keepWorldPositionRotation) {
  13220. var rotation = BABYLON.Tmp.Quaternion[0];
  13221. var position = BABYLON.Tmp.Vector3[0];
  13222. var scale = BABYLON.Tmp.Vector3[1];
  13223. var m1 = BABYLON.Tmp.Matrix[0];
  13224. var m2 = BABYLON.Tmp.Matrix[1];
  13225. parent.getWorldMatrix().decompose(scale, rotation, position);
  13226. rotation.toRotationMatrix(m1);
  13227. m2.setTranslation(position);
  13228. m2.multiplyToRef(m1, m1);
  13229. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13230. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13231. m.decompose(scale, rotation, position);
  13232. if (child.rotationQuaternion) {
  13233. child.rotationQuaternion.copyFrom(rotation);
  13234. }
  13235. else {
  13236. rotation.toEulerAnglesToRef(child.rotation);
  13237. }
  13238. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13239. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13240. m.decompose(scale, rotation, position);
  13241. child.position.x = position.x;
  13242. child.position.y = position.y;
  13243. child.position.z = position.z;
  13244. }
  13245. }
  13246. child.parent = parent;
  13247. return this;
  13248. };
  13249. /**
  13250. * Adds the passed mesh as a child to the current mesh.
  13251. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13252. * Returns the AbstractMesh.
  13253. */
  13254. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13255. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13256. mesh.setParent(this, keepWorldPositionRotation);
  13257. return this;
  13258. };
  13259. /**
  13260. * Removes the passed mesh from the current mesh children list.
  13261. * Returns the AbstractMesh.
  13262. */
  13263. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13264. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13265. mesh.setParent(null, keepWorldPositionRotation);
  13266. return this;
  13267. };
  13268. /**
  13269. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13270. * Returns the AbstractMesh.
  13271. */
  13272. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13273. result.x = this._pivotMatrix.m[12];
  13274. result.y = this._pivotMatrix.m[13];
  13275. result.z = this._pivotMatrix.m[14];
  13276. this.getPivotPointToRef(result);
  13277. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13278. return this;
  13279. };
  13280. // Facet data
  13281. /**
  13282. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13283. * Returns the AbstractMesh.
  13284. */
  13285. AbstractMesh.prototype._initFacetData = function () {
  13286. if (!this._facetNormals) {
  13287. this._facetNormals = new Array();
  13288. }
  13289. if (!this._facetPositions) {
  13290. this._facetPositions = new Array();
  13291. }
  13292. if (!this._facetPartitioning) {
  13293. this._facetPartitioning = new Array();
  13294. }
  13295. this._facetNb = this.getIndices().length / 3;
  13296. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13297. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13298. for (var f = 0; f < this._facetNb; f++) {
  13299. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13300. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13301. }
  13302. this._facetDataEnabled = true;
  13303. return this;
  13304. };
  13305. /**
  13306. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13307. * This method can be called within the render loop.
  13308. * 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.
  13309. * Returns the AbstractMesh.
  13310. */
  13311. AbstractMesh.prototype.updateFacetData = function () {
  13312. if (!this._facetDataEnabled) {
  13313. this._initFacetData();
  13314. }
  13315. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13316. var indices = this.getIndices();
  13317. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13318. var bInfo = this.getBoundingInfo();
  13319. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13320. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13321. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13322. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13323. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13324. this._subDiv.max = this._partitioningSubdivisions;
  13325. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13326. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13327. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13328. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13329. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13330. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13331. // set the parameters for ComputeNormals()
  13332. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13333. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13334. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13335. this._facetParameters.bInfo = bInfo;
  13336. this._facetParameters.bbSize = this._bbSize;
  13337. this._facetParameters.subDiv = this._subDiv;
  13338. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13339. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13340. return this;
  13341. };
  13342. /**
  13343. * Returns the facetLocalNormals array.
  13344. * The normals are expressed in the mesh local space.
  13345. */
  13346. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13347. if (!this._facetNormals) {
  13348. this.updateFacetData();
  13349. }
  13350. return this._facetNormals;
  13351. };
  13352. /**
  13353. * Returns the facetLocalPositions array.
  13354. * The facet positions are expressed in the mesh local space.
  13355. */
  13356. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13357. if (!this._facetPositions) {
  13358. this.updateFacetData();
  13359. }
  13360. return this._facetPositions;
  13361. };
  13362. /**
  13363. * Returns the facetLocalPartioning array.
  13364. */
  13365. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13366. if (!this._facetPartitioning) {
  13367. this.updateFacetData();
  13368. }
  13369. return this._facetPartitioning;
  13370. };
  13371. /**
  13372. * Returns the i-th facet position in the world system.
  13373. * This method allocates a new Vector3 per call.
  13374. */
  13375. AbstractMesh.prototype.getFacetPosition = function (i) {
  13376. var pos = BABYLON.Vector3.Zero();
  13377. this.getFacetPositionToRef(i, pos);
  13378. return pos;
  13379. };
  13380. /**
  13381. * Sets the reference Vector3 with the i-th facet position in the world system.
  13382. * Returns the AbstractMesh.
  13383. */
  13384. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13385. var localPos = (this.getFacetLocalPositions())[i];
  13386. var world = this.getWorldMatrix();
  13387. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13388. return this;
  13389. };
  13390. /**
  13391. * Returns the i-th facet normal in the world system.
  13392. * This method allocates a new Vector3 per call.
  13393. */
  13394. AbstractMesh.prototype.getFacetNormal = function (i) {
  13395. var norm = BABYLON.Vector3.Zero();
  13396. this.getFacetNormalToRef(i, norm);
  13397. return norm;
  13398. };
  13399. /**
  13400. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13401. * Returns the AbstractMesh.
  13402. */
  13403. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13404. var localNorm = (this.getFacetLocalNormals())[i];
  13405. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13406. return this;
  13407. };
  13408. /**
  13409. * 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).
  13410. */
  13411. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13412. var bInfo = this.getBoundingInfo();
  13413. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13414. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13415. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13416. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13417. return null;
  13418. }
  13419. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13420. };
  13421. /**
  13422. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13423. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13424. * 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.
  13425. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13426. * 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.
  13427. */
  13428. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13429. if (checkFace === void 0) { checkFace = false; }
  13430. if (facing === void 0) { facing = true; }
  13431. var world = this.getWorldMatrix();
  13432. var invMat = BABYLON.Tmp.Matrix[5];
  13433. world.invertToRef(invMat);
  13434. var invVect = BABYLON.Tmp.Vector3[8];
  13435. var closest = null;
  13436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13437. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13438. if (projected) {
  13439. // tranform the local computed projected vector to world coordinates
  13440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13441. }
  13442. return closest;
  13443. };
  13444. /**
  13445. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13446. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13447. * 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.
  13448. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13449. * 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.
  13450. */
  13451. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13452. if (checkFace === void 0) { checkFace = false; }
  13453. if (facing === void 0) { facing = true; }
  13454. var closest = null;
  13455. var tmpx = 0.0;
  13456. var tmpy = 0.0;
  13457. var tmpz = 0.0;
  13458. var d = 0.0; // tmp dot facet normal * facet position
  13459. var t0 = 0.0;
  13460. var projx = 0.0;
  13461. var projy = 0.0;
  13462. var projz = 0.0;
  13463. // Get all the facets in the same partitioning block than (x, y, z)
  13464. var facetPositions = this.getFacetLocalPositions();
  13465. var facetNormals = this.getFacetLocalNormals();
  13466. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13467. if (!facetsInBlock) {
  13468. return null;
  13469. }
  13470. // Get the closest facet to (x, y, z)
  13471. var shortest = Number.MAX_VALUE; // init distance vars
  13472. var tmpDistance = shortest;
  13473. var fib; // current facet in the block
  13474. var norm; // current facet normal
  13475. var p0; // current facet barycenter position
  13476. // loop on all the facets in the current partitioning block
  13477. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13478. fib = facetsInBlock[idx];
  13479. norm = facetNormals[fib];
  13480. p0 = facetPositions[fib];
  13481. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13482. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13483. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13484. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13485. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13486. projx = x + norm.x * t0;
  13487. projy = y + norm.y * t0;
  13488. projz = z + norm.z * t0;
  13489. tmpx = projx - x;
  13490. tmpy = projy - y;
  13491. tmpz = projz - z;
  13492. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13493. if (tmpDistance < shortest) {
  13494. shortest = tmpDistance;
  13495. closest = fib;
  13496. if (projected) {
  13497. projected.x = projx;
  13498. projected.y = projy;
  13499. projected.z = projz;
  13500. }
  13501. }
  13502. }
  13503. }
  13504. return closest;
  13505. };
  13506. /**
  13507. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13508. */
  13509. AbstractMesh.prototype.getFacetDataParameters = function () {
  13510. return this._facetParameters;
  13511. };
  13512. /**
  13513. * Disables the feature FacetData and frees the related memory.
  13514. * Returns the AbstractMesh.
  13515. */
  13516. AbstractMesh.prototype.disableFacetData = function () {
  13517. if (this._facetDataEnabled) {
  13518. this._facetDataEnabled = false;
  13519. this._facetPositions = null;
  13520. this._facetNormals = null;
  13521. this._facetPartitioning = null;
  13522. this._facetParameters = null;
  13523. }
  13524. return this;
  13525. };
  13526. return AbstractMesh;
  13527. }(BABYLON.Node));
  13528. // Statics
  13529. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13530. AbstractMesh._BILLBOARDMODE_X = 1;
  13531. AbstractMesh._BILLBOARDMODE_Y = 2;
  13532. AbstractMesh._BILLBOARDMODE_Z = 4;
  13533. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13534. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13535. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13536. BABYLON.AbstractMesh = AbstractMesh;
  13537. })(BABYLON || (BABYLON = {}));
  13538. //# sourceMappingURL=babylon.abstractMesh.js.map
  13539. var BABYLON;
  13540. (function (BABYLON) {
  13541. var Light = (function (_super) {
  13542. __extends(Light, _super);
  13543. /**
  13544. * Creates a Light object in the scene.
  13545. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13546. */
  13547. function Light(name, scene) {
  13548. var _this = _super.call(this, name, scene) || this;
  13549. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13550. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13551. _this.intensity = 1.0;
  13552. _this.range = Number.MAX_VALUE;
  13553. _this.includeOnlyWithLayerMask = 0;
  13554. _this.includedOnlyMeshes = new Array();
  13555. _this.excludedMeshes = new Array();
  13556. _this.excludeWithLayerMask = 0;
  13557. _this.lightmapMode = 0;
  13558. // PBR Properties.
  13559. _this.radius = 0.00001;
  13560. _this._excludedMeshesIds = new Array();
  13561. _this._includedOnlyMeshesIds = new Array();
  13562. scene.addLight(_this);
  13563. return _this;
  13564. }
  13565. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13566. /**
  13567. * If every light affecting the material is in this lightmapMode,
  13568. * material.lightmapTexture adds or multiplies
  13569. * (depends on material.useLightmapAsShadowmap)
  13570. * after every other light calculations.
  13571. */
  13572. get: function () {
  13573. return Light._LIGHTMAP_DEFAULT;
  13574. },
  13575. enumerable: true,
  13576. configurable: true
  13577. });
  13578. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13579. /**
  13580. * material.lightmapTexture as only diffuse lighting from this light
  13581. * adds pnly specular lighting from this light
  13582. * adds dynamic shadows
  13583. */
  13584. get: function () {
  13585. return Light._LIGHTMAP_SPECULAR;
  13586. },
  13587. enumerable: true,
  13588. configurable: true
  13589. });
  13590. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13591. /**
  13592. * material.lightmapTexture as only lighting
  13593. * no light calculation from this light
  13594. * only adds dynamic shadows from this light
  13595. */
  13596. get: function () {
  13597. return Light._LIGHTMAP_SHADOWSONLY;
  13598. },
  13599. enumerable: true,
  13600. configurable: true
  13601. });
  13602. /**
  13603. * Returns the string "Light".
  13604. */
  13605. Light.prototype.getClassName = function () {
  13606. return "Light";
  13607. };
  13608. /**
  13609. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13610. */
  13611. Light.prototype.toString = function (fullDetails) {
  13612. var ret = "Name: " + this.name;
  13613. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13614. if (this.animations) {
  13615. for (var i = 0; i < this.animations.length; i++) {
  13616. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13617. }
  13618. }
  13619. if (fullDetails) {
  13620. }
  13621. return ret;
  13622. };
  13623. /**
  13624. * Returns the Light associated shadow generator.
  13625. */
  13626. Light.prototype.getShadowGenerator = function () {
  13627. return this._shadowGenerator;
  13628. };
  13629. /**
  13630. * Returns a Vector3, the absolute light position in the World.
  13631. */
  13632. Light.prototype.getAbsolutePosition = function () {
  13633. return BABYLON.Vector3.Zero();
  13634. };
  13635. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13636. };
  13637. Light.prototype._getWorldMatrix = function () {
  13638. return BABYLON.Matrix.Identity();
  13639. };
  13640. /**
  13641. * Boolean : True if the light will affect the passed mesh.
  13642. */
  13643. Light.prototype.canAffectMesh = function (mesh) {
  13644. if (!mesh) {
  13645. return true;
  13646. }
  13647. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13648. return false;
  13649. }
  13650. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13651. return false;
  13652. }
  13653. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13654. return false;
  13655. }
  13656. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13657. return false;
  13658. }
  13659. return true;
  13660. };
  13661. /**
  13662. * Returns the light World matrix.
  13663. */
  13664. Light.prototype.getWorldMatrix = function () {
  13665. this._currentRenderId = this.getScene().getRenderId();
  13666. var worldMatrix = this._getWorldMatrix();
  13667. if (this.parent && this.parent.getWorldMatrix) {
  13668. if (!this._parentedWorldMatrix) {
  13669. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13670. }
  13671. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13672. this._markSyncedWithParent();
  13673. return this._parentedWorldMatrix;
  13674. }
  13675. return worldMatrix;
  13676. };
  13677. /**
  13678. * Disposes the light.
  13679. */
  13680. Light.prototype.dispose = function () {
  13681. if (this._shadowGenerator) {
  13682. this._shadowGenerator.dispose();
  13683. this._shadowGenerator = null;
  13684. }
  13685. // Animations
  13686. this.getScene().stopAnimation(this);
  13687. // Remove from scene
  13688. this.getScene().removeLight(this);
  13689. _super.prototype.dispose.call(this);
  13690. };
  13691. /**
  13692. * Returns the light type ID (integer).
  13693. */
  13694. Light.prototype.getTypeID = function () {
  13695. return 0;
  13696. };
  13697. /**
  13698. * Returns a new Light object, named "name", from the current one.
  13699. */
  13700. Light.prototype.clone = function (name) {
  13701. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13702. };
  13703. /**
  13704. * Serializes the current light into a Serialization object.
  13705. * Returns the serialized object.
  13706. */
  13707. Light.prototype.serialize = function () {
  13708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13709. // Type
  13710. serializationObject.type = this.getTypeID();
  13711. // Parent
  13712. if (this.parent) {
  13713. serializationObject.parentId = this.parent.id;
  13714. }
  13715. // Inclusion / exclusions
  13716. if (this.excludedMeshes.length > 0) {
  13717. serializationObject.excludedMeshesIds = [];
  13718. this.excludedMeshes.forEach(function (mesh) {
  13719. serializationObject.excludedMeshesIds.push(mesh.id);
  13720. });
  13721. }
  13722. if (this.includedOnlyMeshes.length > 0) {
  13723. serializationObject.includedOnlyMeshesIds = [];
  13724. this.includedOnlyMeshes.forEach(function (mesh) {
  13725. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13726. });
  13727. }
  13728. // Animations
  13729. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13730. serializationObject.ranges = this.serializeAnimationRanges();
  13731. return serializationObject;
  13732. };
  13733. /**
  13734. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13735. * This new light is named "name" and added to the passed scene.
  13736. */
  13737. Light.GetConstructorFromName = function (type, name, scene) {
  13738. switch (type) {
  13739. case 0:
  13740. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13741. case 1:
  13742. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13743. case 2:
  13744. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13745. case 3:
  13746. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13747. }
  13748. };
  13749. /**
  13750. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13751. */
  13752. Light.Parse = function (parsedLight, scene) {
  13753. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13754. // Inclusion / exclusions
  13755. if (parsedLight.excludedMeshesIds) {
  13756. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13757. }
  13758. if (parsedLight.includedOnlyMeshesIds) {
  13759. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13760. }
  13761. // Parent
  13762. if (parsedLight.parentId) {
  13763. light._waitingParentId = parsedLight.parentId;
  13764. }
  13765. // Animations
  13766. if (parsedLight.animations) {
  13767. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13768. var parsedAnimation = parsedLight.animations[animationIndex];
  13769. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13770. }
  13771. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13772. }
  13773. if (parsedLight.autoAnimate) {
  13774. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13775. }
  13776. return light;
  13777. };
  13778. return Light;
  13779. }(BABYLON.Node));
  13780. //lightmapMode Consts
  13781. Light._LIGHTMAP_DEFAULT = 0;
  13782. Light._LIGHTMAP_SPECULAR = 1;
  13783. Light._LIGHTMAP_SHADOWSONLY = 2;
  13784. __decorate([
  13785. BABYLON.serializeAsColor3()
  13786. ], Light.prototype, "diffuse", void 0);
  13787. __decorate([
  13788. BABYLON.serializeAsColor3()
  13789. ], Light.prototype, "specular", void 0);
  13790. __decorate([
  13791. BABYLON.serialize()
  13792. ], Light.prototype, "intensity", void 0);
  13793. __decorate([
  13794. BABYLON.serialize()
  13795. ], Light.prototype, "range", void 0);
  13796. __decorate([
  13797. BABYLON.serialize()
  13798. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  13799. __decorate([
  13800. BABYLON.serialize()
  13801. ], Light.prototype, "excludeWithLayerMask", void 0);
  13802. __decorate([
  13803. BABYLON.serialize()
  13804. ], Light.prototype, "lightmapMode", void 0);
  13805. __decorate([
  13806. BABYLON.serialize()
  13807. ], Light.prototype, "radius", void 0);
  13808. BABYLON.Light = Light;
  13809. })(BABYLON || (BABYLON = {}));
  13810. //# sourceMappingURL=babylon.light.js.map
  13811. var BABYLON;
  13812. (function (BABYLON) {
  13813. var PointLight = (function (_super) {
  13814. __extends(PointLight, _super);
  13815. /**
  13816. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  13817. * A PointLight emits the light in every direction.
  13818. * It can cast shadows.
  13819. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  13820. * ```javascript
  13821. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  13822. * ```
  13823. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13824. */
  13825. function PointLight(name, position, scene) {
  13826. var _this = _super.call(this, name, scene) || this;
  13827. _this.position = position;
  13828. return _this;
  13829. }
  13830. /**
  13831. * Returns the string "PointLight"
  13832. */
  13833. PointLight.prototype.getClassName = function () {
  13834. return "PointLight";
  13835. };
  13836. /**
  13837. * Returns a Vector3, the PointLight absolute position in the World.
  13838. */
  13839. PointLight.prototype.getAbsolutePosition = function () {
  13840. return this.transformedPosition ? this.transformedPosition : this.position;
  13841. };
  13842. /**
  13843. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  13844. */
  13845. PointLight.prototype.computeTransformedPosition = function () {
  13846. if (this.parent && this.parent.getWorldMatrix) {
  13847. if (!this.transformedPosition) {
  13848. this.transformedPosition = BABYLON.Vector3.Zero();
  13849. }
  13850. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  13851. return true;
  13852. }
  13853. return false;
  13854. };
  13855. /**
  13856. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  13857. * Returns the PointLight.
  13858. */
  13859. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  13860. if (this.parent && this.parent.getWorldMatrix) {
  13861. this.computeTransformedPosition();
  13862. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  13863. return this;
  13864. }
  13865. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  13866. return this;
  13867. };
  13868. /**
  13869. * Boolean : returns true by default.
  13870. */
  13871. PointLight.prototype.needCube = function () {
  13872. return true;
  13873. };
  13874. /**
  13875. * Boolean : returns false by default.
  13876. */
  13877. PointLight.prototype.supportsVSM = function () {
  13878. return false;
  13879. };
  13880. /**
  13881. * Boolean : returns false by default.
  13882. */
  13883. PointLight.prototype.needRefreshPerFrame = function () {
  13884. return false;
  13885. };
  13886. /**
  13887. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  13888. */
  13889. PointLight.prototype.getShadowDirection = function (faceIndex) {
  13890. switch (faceIndex) {
  13891. case 0:
  13892. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  13893. case 1:
  13894. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  13895. case 2:
  13896. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  13897. case 3:
  13898. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  13899. case 4:
  13900. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  13901. case 5:
  13902. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  13903. }
  13904. return BABYLON.Vector3.Zero();
  13905. };
  13906. /**
  13907. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  13908. * - fov = PI / 2
  13909. * - aspect ratio : 1.0
  13910. * - z-near and far equal to the active camera minZ and maxZ.
  13911. * Returns the PointLight.
  13912. */
  13913. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  13914. var activeCamera = this.getScene().activeCamera;
  13915. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  13916. return this;
  13917. };
  13918. PointLight.prototype._getWorldMatrix = function () {
  13919. if (!this._worldMatrix) {
  13920. this._worldMatrix = BABYLON.Matrix.Identity();
  13921. }
  13922. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  13923. return this._worldMatrix;
  13924. };
  13925. /**
  13926. * Returns the integer 0.
  13927. */
  13928. PointLight.prototype.getTypeID = function () {
  13929. return 0;
  13930. };
  13931. return PointLight;
  13932. }(BABYLON.Light));
  13933. __decorate([
  13934. BABYLON.serializeAsVector3()
  13935. ], PointLight.prototype, "position", void 0);
  13936. BABYLON.PointLight = PointLight;
  13937. })(BABYLON || (BABYLON = {}));
  13938. //# sourceMappingURL=babylon.pointLight.js.map
  13939. var BABYLON;
  13940. (function (BABYLON) {
  13941. var SpotLight = (function (_super) {
  13942. __extends(SpotLight, _super);
  13943. /**
  13944. * Creates a SpotLight object in the scene with the passed parameters :
  13945. * - `position` (Vector3) is the initial SpotLight position,
  13946. * - `direction` (Vector3) is the initial SpotLight direction,
  13947. * - `angle` (float, in radians) is the spot light cone angle,
  13948. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  13949. * A spot light is a simply light oriented cone.
  13950. * It can cast shadows.
  13951. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13952. */
  13953. function SpotLight(name, position, direction, angle, exponent, scene) {
  13954. var _this = _super.call(this, name, scene) || this;
  13955. _this.position = position;
  13956. _this.direction = direction;
  13957. _this.angle = angle;
  13958. _this.exponent = exponent;
  13959. return _this;
  13960. }
  13961. /**
  13962. * Returns the string "SpotLight".
  13963. */
  13964. SpotLight.prototype.getClassName = function () {
  13965. return "SpotLight";
  13966. };
  13967. /**
  13968. * Returns the SpotLight absolute position in the World (Vector3).
  13969. */
  13970. SpotLight.prototype.getAbsolutePosition = function () {
  13971. return this.transformedPosition ? this.transformedPosition : this.position;
  13972. };
  13973. /**
  13974. * 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.
  13975. * Returns the SpotLight.
  13976. */
  13977. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  13978. var activeCamera = this.getScene().activeCamera;
  13979. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  13980. return this;
  13981. };
  13982. /**
  13983. * Boolean : false by default.
  13984. */
  13985. SpotLight.prototype.needCube = function () {
  13986. return false;
  13987. };
  13988. /**
  13989. * Boolean : true by default.
  13990. */
  13991. SpotLight.prototype.supportsVSM = function () {
  13992. return true;
  13993. };
  13994. /**
  13995. * Boolean : false by default.
  13996. */
  13997. SpotLight.prototype.needRefreshPerFrame = function () {
  13998. return false;
  13999. };
  14000. /**
  14001. * Returns the SpotLight direction (Vector3) for any passed face index.
  14002. */
  14003. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14004. return this.direction;
  14005. };
  14006. /**
  14007. * Updates the SpotLight direction towards the passed target (Vector3).
  14008. * Returns the updated direction.
  14009. */
  14010. SpotLight.prototype.setDirectionToTarget = function (target) {
  14011. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14012. return this.direction;
  14013. };
  14014. /**
  14015. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14016. */
  14017. SpotLight.prototype.computeTransformedPosition = function () {
  14018. if (this.parent && this.parent.getWorldMatrix) {
  14019. if (!this.transformedPosition) {
  14020. this.transformedPosition = BABYLON.Vector3.Zero();
  14021. }
  14022. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14023. return true;
  14024. }
  14025. return false;
  14026. };
  14027. /**
  14028. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14029. * Return the SpotLight.
  14030. */
  14031. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14032. var normalizeDirection;
  14033. if (this.parent && this.parent.getWorldMatrix) {
  14034. if (!this._transformedDirection) {
  14035. this._transformedDirection = BABYLON.Vector3.Zero();
  14036. }
  14037. this.computeTransformedPosition();
  14038. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14039. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14040. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14041. }
  14042. else {
  14043. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14044. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14045. }
  14046. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14047. return this;
  14048. };
  14049. SpotLight.prototype._getWorldMatrix = function () {
  14050. if (!this._worldMatrix) {
  14051. this._worldMatrix = BABYLON.Matrix.Identity();
  14052. }
  14053. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14054. return this._worldMatrix;
  14055. };
  14056. /**
  14057. * Returns the integer 2.
  14058. */
  14059. SpotLight.prototype.getTypeID = function () {
  14060. return 2;
  14061. };
  14062. /**
  14063. * Returns the SpotLight rotation (Vector3).
  14064. */
  14065. SpotLight.prototype.getRotation = function () {
  14066. this.direction.normalize();
  14067. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14068. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14069. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14070. };
  14071. return SpotLight;
  14072. }(BABYLON.Light));
  14073. __decorate([
  14074. BABYLON.serializeAsVector3()
  14075. ], SpotLight.prototype, "position", void 0);
  14076. __decorate([
  14077. BABYLON.serializeAsVector3()
  14078. ], SpotLight.prototype, "direction", void 0);
  14079. __decorate([
  14080. BABYLON.serialize()
  14081. ], SpotLight.prototype, "angle", void 0);
  14082. __decorate([
  14083. BABYLON.serialize()
  14084. ], SpotLight.prototype, "exponent", void 0);
  14085. BABYLON.SpotLight = SpotLight;
  14086. })(BABYLON || (BABYLON = {}));
  14087. //# sourceMappingURL=babylon.spotLight.js.map
  14088. var BABYLON;
  14089. (function (BABYLON) {
  14090. var HemisphericLight = (function (_super) {
  14091. __extends(HemisphericLight, _super);
  14092. /**
  14093. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14094. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14095. * The HemisphericLight can't cast shadows.
  14096. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14097. */
  14098. function HemisphericLight(name, direction, scene) {
  14099. var _this = _super.call(this, name, scene) || this;
  14100. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14101. _this.direction = direction;
  14102. return _this;
  14103. }
  14104. /**
  14105. * Returns the string "HemisphericLight".
  14106. */
  14107. HemisphericLight.prototype.getClassName = function () {
  14108. return "HemisphericLight";
  14109. };
  14110. /**
  14111. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14112. * Returns the updated direction.
  14113. */
  14114. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14115. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14116. return this.direction;
  14117. };
  14118. HemisphericLight.prototype.getShadowGenerator = function () {
  14119. return null;
  14120. };
  14121. /**
  14122. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14123. * Returns the HemisphericLight.
  14124. */
  14125. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14126. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14127. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14128. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14129. return this;
  14130. };
  14131. HemisphericLight.prototype._getWorldMatrix = function () {
  14132. if (!this._worldMatrix) {
  14133. this._worldMatrix = BABYLON.Matrix.Identity();
  14134. }
  14135. return this._worldMatrix;
  14136. };
  14137. /**
  14138. * Returns the integer 3.
  14139. */
  14140. HemisphericLight.prototype.getTypeID = function () {
  14141. return 3;
  14142. };
  14143. return HemisphericLight;
  14144. }(BABYLON.Light));
  14145. __decorate([
  14146. BABYLON.serializeAsColor3()
  14147. ], HemisphericLight.prototype, "groundColor", void 0);
  14148. __decorate([
  14149. BABYLON.serializeAsVector3()
  14150. ], HemisphericLight.prototype, "direction", void 0);
  14151. BABYLON.HemisphericLight = HemisphericLight;
  14152. })(BABYLON || (BABYLON = {}));
  14153. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14154. /// <reference path="babylon.light.ts" />
  14155. var BABYLON;
  14156. (function (BABYLON) {
  14157. var DirectionalLight = (function (_super) {
  14158. __extends(DirectionalLight, _super);
  14159. /**
  14160. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14161. * The directional light is emitted from everywhere in the given direction.
  14162. * It can cast shawdows.
  14163. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14164. */
  14165. function DirectionalLight(name, direction, scene) {
  14166. var _this = _super.call(this, name, scene) || this;
  14167. _this.shadowOrthoScale = 0.5;
  14168. _this.autoUpdateExtends = true;
  14169. // Cache
  14170. _this._orthoLeft = Number.MAX_VALUE;
  14171. _this._orthoRight = Number.MIN_VALUE;
  14172. _this._orthoTop = Number.MIN_VALUE;
  14173. _this._orthoBottom = Number.MAX_VALUE;
  14174. _this.position = direction.scale(-1.0);
  14175. _this.direction = direction;
  14176. return _this;
  14177. }
  14178. /**
  14179. * Returns the string "DirectionalLight".
  14180. */
  14181. DirectionalLight.prototype.getClassName = function () {
  14182. return "DirectionalLight";
  14183. };
  14184. /**
  14185. * Returns the DirectionalLight absolute position in the World.
  14186. */
  14187. DirectionalLight.prototype.getAbsolutePosition = function () {
  14188. return this.transformedPosition ? this.transformedPosition : this.position;
  14189. };
  14190. /**
  14191. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14192. * Returns the updated DirectionalLight direction (Vector3).
  14193. */
  14194. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14195. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14196. return this.direction;
  14197. };
  14198. /**
  14199. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14200. * Returns the DirectionalLight.
  14201. */
  14202. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14203. var activeCamera = this.getScene().activeCamera;
  14204. // Check extends
  14205. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14206. var tempVector3 = BABYLON.Vector3.Zero();
  14207. this._orthoLeft = Number.MAX_VALUE;
  14208. this._orthoRight = Number.MIN_VALUE;
  14209. this._orthoTop = Number.MIN_VALUE;
  14210. this._orthoBottom = Number.MAX_VALUE;
  14211. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14212. var mesh = renderList[meshIndex];
  14213. if (!mesh) {
  14214. continue;
  14215. }
  14216. var boundingInfo = mesh.getBoundingInfo();
  14217. if (!boundingInfo) {
  14218. continue;
  14219. }
  14220. var boundingBox = boundingInfo.boundingBox;
  14221. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14222. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14223. if (tempVector3.x < this._orthoLeft)
  14224. this._orthoLeft = tempVector3.x;
  14225. if (tempVector3.y < this._orthoBottom)
  14226. this._orthoBottom = tempVector3.y;
  14227. if (tempVector3.x > this._orthoRight)
  14228. this._orthoRight = tempVector3.x;
  14229. if (tempVector3.y > this._orthoTop)
  14230. this._orthoTop = tempVector3.y;
  14231. }
  14232. }
  14233. }
  14234. var xOffset = this._orthoRight - this._orthoLeft;
  14235. var yOffset = this._orthoTop - this._orthoBottom;
  14236. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  14237. return this;
  14238. };
  14239. /**
  14240. * Boolean : true by default.
  14241. */
  14242. DirectionalLight.prototype.supportsVSM = function () {
  14243. return true;
  14244. };
  14245. /**
  14246. * Boolean : true by default.
  14247. */
  14248. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14249. return true;
  14250. };
  14251. /**
  14252. * Boolean : false by default.
  14253. */
  14254. DirectionalLight.prototype.needCube = function () {
  14255. return false;
  14256. };
  14257. /**
  14258. * Returns the light direction (Vector3) for any passed face index.
  14259. */
  14260. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14261. return this.direction;
  14262. };
  14263. /**
  14264. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14265. */
  14266. DirectionalLight.prototype.computeTransformedPosition = function () {
  14267. if (this.parent && this.parent.getWorldMatrix) {
  14268. if (!this.transformedPosition) {
  14269. this.transformedPosition = BABYLON.Vector3.Zero();
  14270. }
  14271. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14272. return true;
  14273. }
  14274. return false;
  14275. };
  14276. /**
  14277. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14278. * Returns the DirectionalLight.
  14279. */
  14280. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14281. if (this.parent && this.parent.getWorldMatrix) {
  14282. if (!this._transformedDirection) {
  14283. this._transformedDirection = BABYLON.Vector3.Zero();
  14284. }
  14285. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14286. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14287. return this;
  14288. }
  14289. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14290. return this;
  14291. };
  14292. DirectionalLight.prototype._getWorldMatrix = function () {
  14293. if (!this._worldMatrix) {
  14294. this._worldMatrix = BABYLON.Matrix.Identity();
  14295. }
  14296. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14297. return this._worldMatrix;
  14298. };
  14299. /**
  14300. * Returns the integer 1.
  14301. */
  14302. DirectionalLight.prototype.getTypeID = function () {
  14303. return 1;
  14304. };
  14305. return DirectionalLight;
  14306. }(BABYLON.Light));
  14307. __decorate([
  14308. BABYLON.serializeAsVector3()
  14309. ], DirectionalLight.prototype, "position", void 0);
  14310. __decorate([
  14311. BABYLON.serializeAsVector3()
  14312. ], DirectionalLight.prototype, "direction", void 0);
  14313. __decorate([
  14314. BABYLON.serialize()
  14315. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14316. __decorate([
  14317. BABYLON.serialize()
  14318. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14319. BABYLON.DirectionalLight = DirectionalLight;
  14320. })(BABYLON || (BABYLON = {}));
  14321. //# sourceMappingURL=babylon.directionalLight.js.map
  14322. var BABYLON;
  14323. (function (BABYLON) {
  14324. var ShadowGenerator = (function () {
  14325. /**
  14326. * Creates a ShadowGenerator object.
  14327. * A ShadowGenerator is the required tool to use the shadows.
  14328. * Each light casting shadows needs to use its own ShadowGenerator.
  14329. * Required parameters :
  14330. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14331. * - `light` : the light object generating the shadows.
  14332. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14333. */
  14334. function ShadowGenerator(mapSize, light) {
  14335. var _this = this;
  14336. // Members
  14337. this._filter = ShadowGenerator.FILTER_NONE;
  14338. this.blurScale = 2;
  14339. this._blurBoxOffset = 0;
  14340. this._bias = 0.00005;
  14341. this._lightDirection = BABYLON.Vector3.Zero();
  14342. this.forceBackFacesOnly = false;
  14343. this._darkness = 0;
  14344. this._transparencyShadow = false;
  14345. this._viewMatrix = BABYLON.Matrix.Zero();
  14346. this._projectionMatrix = BABYLON.Matrix.Zero();
  14347. this._transformMatrix = BABYLON.Matrix.Zero();
  14348. this._worldViewProjection = BABYLON.Matrix.Zero();
  14349. this._currentFaceIndex = 0;
  14350. this._currentFaceIndexCache = 0;
  14351. this._useFullFloat = true;
  14352. this._light = light;
  14353. this._scene = light.getScene();
  14354. this._mapSize = mapSize;
  14355. light._shadowGenerator = this;
  14356. // Texture type fallback from float to int if not supported.
  14357. var textureType;
  14358. var caps = this._scene.getEngine().getCaps();
  14359. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14360. this._useFullFloat = true;
  14361. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14362. }
  14363. else {
  14364. this._useFullFloat = false;
  14365. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14366. }
  14367. // Render target
  14368. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14369. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14370. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14371. this._shadowMap.anisotropicFilteringLevel = 1;
  14372. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14373. this._shadowMap.renderParticles = false;
  14374. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14375. _this._currentFaceIndex = faceIndex;
  14376. });
  14377. this._shadowMap.onAfterUnbindObservable.add(function () {
  14378. if (!_this.useBlurVarianceShadowMap) {
  14379. return;
  14380. }
  14381. if (!_this._shadowMap2) {
  14382. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14383. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14384. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14385. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14386. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14387. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14388. effect.setTexture("textureSampler", _this._shadowMap);
  14389. });
  14390. _this.blurBoxOffset = 1;
  14391. }
  14392. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14393. });
  14394. // Custom render function
  14395. var renderSubMesh = function (subMesh) {
  14396. var mesh = subMesh.getRenderingMesh();
  14397. var scene = _this._scene;
  14398. var engine = scene.getEngine();
  14399. // Culling
  14400. engine.setState(subMesh.getMaterial().backFaceCulling);
  14401. // Managing instances
  14402. var batch = mesh._getInstancesRenderList(subMesh._id);
  14403. if (batch.mustReturn) {
  14404. return;
  14405. }
  14406. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14407. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14408. engine.enableEffect(_this._effect);
  14409. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14410. var material = subMesh.getMaterial();
  14411. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14412. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14413. if (_this.getLight().needCube()) {
  14414. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14415. }
  14416. // Alpha test
  14417. if (material && material.needAlphaTesting()) {
  14418. var alphaTexture = material.getAlphaTestTexture();
  14419. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14420. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14421. }
  14422. // Bones
  14423. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14424. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14425. }
  14426. if (_this.forceBackFacesOnly) {
  14427. engine.setState(true, 0, false, true);
  14428. }
  14429. // Draw
  14430. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14431. if (_this.forceBackFacesOnly) {
  14432. engine.setState(true, 0, false, false);
  14433. }
  14434. }
  14435. else {
  14436. // Need to reset refresh rate of the shadowMap
  14437. _this._shadowMap.resetRefreshCounter();
  14438. }
  14439. };
  14440. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14441. var index;
  14442. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14443. renderSubMesh(opaqueSubMeshes.data[index]);
  14444. }
  14445. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14446. renderSubMesh(alphaTestSubMeshes.data[index]);
  14447. }
  14448. if (_this._transparencyShadow) {
  14449. for (index = 0; index < transparentSubMeshes.length; index++) {
  14450. renderSubMesh(transparentSubMeshes.data[index]);
  14451. }
  14452. }
  14453. };
  14454. this._shadowMap.onClearObservable.add(function (engine) {
  14455. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14456. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14457. }
  14458. else {
  14459. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14460. }
  14461. });
  14462. }
  14463. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14464. // Static
  14465. get: function () {
  14466. return ShadowGenerator._FILTER_NONE;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14472. get: function () {
  14473. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14474. },
  14475. enumerable: true,
  14476. configurable: true
  14477. });
  14478. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14479. get: function () {
  14480. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14486. get: function () {
  14487. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14488. },
  14489. enumerable: true,
  14490. configurable: true
  14491. });
  14492. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14493. get: function () {
  14494. return this._bias;
  14495. },
  14496. set: function (bias) {
  14497. this._bias = bias;
  14498. },
  14499. enumerable: true,
  14500. configurable: true
  14501. });
  14502. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14503. get: function () {
  14504. return this._blurBoxOffset;
  14505. },
  14506. set: function (value) {
  14507. var _this = this;
  14508. if (this._blurBoxOffset === value) {
  14509. return;
  14510. }
  14511. this._blurBoxOffset = value;
  14512. if (this._boxBlurPostprocess) {
  14513. this._boxBlurPostprocess.dispose();
  14514. }
  14515. 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);
  14516. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14517. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14518. });
  14519. },
  14520. enumerable: true,
  14521. configurable: true
  14522. });
  14523. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14524. get: function () {
  14525. return this._filter;
  14526. },
  14527. set: function (value) {
  14528. if (this._filter === value) {
  14529. return;
  14530. }
  14531. this._filter = value;
  14532. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14533. this._shadowMap.anisotropicFilteringLevel = 16;
  14534. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14535. }
  14536. else {
  14537. this._shadowMap.anisotropicFilteringLevel = 1;
  14538. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14539. }
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14545. get: function () {
  14546. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14547. },
  14548. set: function (value) {
  14549. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14555. get: function () {
  14556. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14557. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14558. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14559. },
  14560. set: function (value) {
  14561. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14567. get: function () {
  14568. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14569. },
  14570. set: function (value) {
  14571. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. /**
  14577. * Boolean : true when the ShadowGenerator is finally computed.
  14578. */
  14579. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14580. var defines = [];
  14581. if (this._useFullFloat) {
  14582. defines.push("#define FULLFLOAT");
  14583. }
  14584. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14585. defines.push("#define VSM");
  14586. }
  14587. if (this.getLight().needCube()) {
  14588. defines.push("#define CUBEMAP");
  14589. }
  14590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14591. var mesh = subMesh.getMesh();
  14592. var material = subMesh.getMaterial();
  14593. // Alpha test
  14594. if (material && material.needAlphaTesting()) {
  14595. defines.push("#define ALPHATEST");
  14596. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14597. attribs.push(BABYLON.VertexBuffer.UVKind);
  14598. defines.push("#define UV1");
  14599. }
  14600. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14601. var alphaTexture = material.getAlphaTestTexture();
  14602. if (alphaTexture.coordinatesIndex === 1) {
  14603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14604. defines.push("#define UV2");
  14605. }
  14606. }
  14607. }
  14608. // Bones
  14609. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14610. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14611. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14612. if (mesh.numBoneInfluencers > 4) {
  14613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14615. }
  14616. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14617. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14618. }
  14619. else {
  14620. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14621. }
  14622. // Instances
  14623. if (useInstances) {
  14624. defines.push("#define INSTANCES");
  14625. attribs.push("world0");
  14626. attribs.push("world1");
  14627. attribs.push("world2");
  14628. attribs.push("world3");
  14629. }
  14630. // Get correct effect
  14631. var join = defines.join("\n");
  14632. if (this._cachedDefines !== join) {
  14633. this._cachedDefines = join;
  14634. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14635. }
  14636. return this._effect.isReady();
  14637. };
  14638. /**
  14639. * Returns a RenderTargetTexture object : the shadow map texture.
  14640. */
  14641. ShadowGenerator.prototype.getShadowMap = function () {
  14642. return this._shadowMap;
  14643. };
  14644. /**
  14645. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14646. */
  14647. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14648. if (this._shadowMap2) {
  14649. return this._shadowMap2;
  14650. }
  14651. return this._shadowMap;
  14652. };
  14653. /**
  14654. * Returns the associated light object.
  14655. */
  14656. ShadowGenerator.prototype.getLight = function () {
  14657. return this._light;
  14658. };
  14659. // Methods
  14660. /**
  14661. * Returns a Matrix object : the updated transformation matrix.
  14662. */
  14663. ShadowGenerator.prototype.getTransformMatrix = function () {
  14664. var scene = this._scene;
  14665. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14666. return this._transformMatrix;
  14667. }
  14668. this._currentRenderID = scene.getRenderId();
  14669. this._currentFaceIndexCache = this._currentFaceIndex;
  14670. var lightPosition = this._light.position;
  14671. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14672. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14673. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14674. }
  14675. if (this._light.computeTransformedPosition()) {
  14676. lightPosition = this._light.transformedPosition;
  14677. }
  14678. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14679. this._cachedPosition = lightPosition.clone();
  14680. this._cachedDirection = this._lightDirection.clone();
  14681. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14682. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14683. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14684. }
  14685. return this._transformMatrix;
  14686. };
  14687. /**
  14688. * Returns the darkness value (float).
  14689. */
  14690. ShadowGenerator.prototype.getDarkness = function () {
  14691. return this._darkness;
  14692. };
  14693. /**
  14694. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14695. * Returns the ShadowGenerator.
  14696. */
  14697. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14698. if (darkness >= 1.0)
  14699. this._darkness = 1.0;
  14700. else if (darkness <= 0.0)
  14701. this._darkness = 0.0;
  14702. else
  14703. this._darkness = darkness;
  14704. return this;
  14705. };
  14706. /**
  14707. * Sets the ability to have transparent shadow (boolean).
  14708. * Returns the ShadowGenerator.
  14709. */
  14710. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14711. this._transparencyShadow = hasShadow;
  14712. return this;
  14713. };
  14714. ShadowGenerator.prototype._packHalf = function (depth) {
  14715. var scale = depth * 255.0;
  14716. var fract = scale - Math.floor(scale);
  14717. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14718. };
  14719. /**
  14720. * Disposes the ShadowGenerator.
  14721. * Returns nothing.
  14722. */
  14723. ShadowGenerator.prototype.dispose = function () {
  14724. this._shadowMap.dispose();
  14725. if (this._shadowMap2) {
  14726. this._shadowMap2.dispose();
  14727. }
  14728. if (this._downSamplePostprocess) {
  14729. this._downSamplePostprocess.dispose();
  14730. }
  14731. if (this._boxBlurPostprocess) {
  14732. this._boxBlurPostprocess.dispose();
  14733. }
  14734. this._light._shadowGenerator = null;
  14735. };
  14736. /**
  14737. * Serializes the ShadowGenerator and returns a serializationObject.
  14738. */
  14739. ShadowGenerator.prototype.serialize = function () {
  14740. var serializationObject = {};
  14741. serializationObject.lightId = this._light.id;
  14742. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  14743. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  14744. serializationObject.usePoissonSampling = this.usePoissonSampling;
  14745. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  14746. serializationObject.renderList = [];
  14747. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  14748. var mesh = this.getShadowMap().renderList[meshIndex];
  14749. serializationObject.renderList.push(mesh.id);
  14750. }
  14751. return serializationObject;
  14752. };
  14753. /**
  14754. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  14755. */
  14756. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  14757. //casting to point light, as light is missing the position attr and typescript complains.
  14758. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14759. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14760. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14761. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  14762. meshes.forEach(function (mesh) {
  14763. shadowGenerator.getShadowMap().renderList.push(mesh);
  14764. });
  14765. }
  14766. if (parsedShadowGenerator.usePoissonSampling) {
  14767. shadowGenerator.usePoissonSampling = true;
  14768. }
  14769. else if (parsedShadowGenerator.useVarianceShadowMap) {
  14770. shadowGenerator.useVarianceShadowMap = true;
  14771. }
  14772. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  14773. shadowGenerator.useBlurVarianceShadowMap = true;
  14774. if (parsedShadowGenerator.blurScale) {
  14775. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  14776. }
  14777. if (parsedShadowGenerator.blurBoxOffset) {
  14778. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  14779. }
  14780. }
  14781. if (parsedShadowGenerator.bias !== undefined) {
  14782. shadowGenerator.bias = parsedShadowGenerator.bias;
  14783. }
  14784. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  14785. return shadowGenerator;
  14786. };
  14787. return ShadowGenerator;
  14788. }());
  14789. ShadowGenerator._FILTER_NONE = 0;
  14790. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  14791. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  14792. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  14793. BABYLON.ShadowGenerator = ShadowGenerator;
  14794. })(BABYLON || (BABYLON = {}));
  14795. //# sourceMappingURL=babylon.shadowGenerator.js.map
  14796. var BABYLON;
  14797. (function (BABYLON) {
  14798. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  14799. if (boxMin.x > sphereCenter.x + sphereRadius)
  14800. return false;
  14801. if (sphereCenter.x - sphereRadius > boxMax.x)
  14802. return false;
  14803. if (boxMin.y > sphereCenter.y + sphereRadius)
  14804. return false;
  14805. if (sphereCenter.y - sphereRadius > boxMax.y)
  14806. return false;
  14807. if (boxMin.z > sphereCenter.z + sphereRadius)
  14808. return false;
  14809. if (sphereCenter.z - sphereRadius > boxMax.z)
  14810. return false;
  14811. return true;
  14812. };
  14813. var getLowestRoot = (function () {
  14814. var result = { root: 0, found: false };
  14815. return function (a, b, c, maxR) {
  14816. result.root = 0;
  14817. result.found = false;
  14818. var determinant = b * b - 4.0 * a * c;
  14819. if (determinant < 0)
  14820. return result;
  14821. var sqrtD = Math.sqrt(determinant);
  14822. var r1 = (-b - sqrtD) / (2.0 * a);
  14823. var r2 = (-b + sqrtD) / (2.0 * a);
  14824. if (r1 > r2) {
  14825. var temp = r2;
  14826. r2 = r1;
  14827. r1 = temp;
  14828. }
  14829. if (r1 > 0 && r1 < maxR) {
  14830. result.root = r1;
  14831. result.found = true;
  14832. return result;
  14833. }
  14834. if (r2 > 0 && r2 < maxR) {
  14835. result.root = r2;
  14836. result.found = true;
  14837. return result;
  14838. }
  14839. return result;
  14840. };
  14841. })();
  14842. var Collider = (function () {
  14843. function Collider() {
  14844. this.radius = new BABYLON.Vector3(1, 1, 1);
  14845. this.retry = 0;
  14846. this.basePointWorld = BABYLON.Vector3.Zero();
  14847. this.velocityWorld = BABYLON.Vector3.Zero();
  14848. this.normalizedVelocity = BABYLON.Vector3.Zero();
  14849. this._collisionPoint = BABYLON.Vector3.Zero();
  14850. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  14851. this._tempVector = BABYLON.Vector3.Zero();
  14852. this._tempVector2 = BABYLON.Vector3.Zero();
  14853. this._tempVector3 = BABYLON.Vector3.Zero();
  14854. this._tempVector4 = BABYLON.Vector3.Zero();
  14855. this._edge = BABYLON.Vector3.Zero();
  14856. this._baseToVertex = BABYLON.Vector3.Zero();
  14857. this._destinationPoint = BABYLON.Vector3.Zero();
  14858. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  14859. this._displacementVector = BABYLON.Vector3.Zero();
  14860. this._collisionMask = -1;
  14861. }
  14862. Object.defineProperty(Collider.prototype, "collisionMask", {
  14863. get: function () {
  14864. return this._collisionMask;
  14865. },
  14866. set: function (mask) {
  14867. this._collisionMask = !isNaN(mask) ? mask : -1;
  14868. },
  14869. enumerable: true,
  14870. configurable: true
  14871. });
  14872. // Methods
  14873. Collider.prototype._initialize = function (source, dir, e) {
  14874. this.velocity = dir;
  14875. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  14876. this.basePoint = source;
  14877. source.multiplyToRef(this.radius, this.basePointWorld);
  14878. dir.multiplyToRef(this.radius, this.velocityWorld);
  14879. this.velocityWorldLength = this.velocityWorld.length();
  14880. this.epsilon = e;
  14881. this.collisionFound = false;
  14882. };
  14883. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  14884. pa.subtractToRef(point, this._tempVector);
  14885. pb.subtractToRef(point, this._tempVector2);
  14886. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  14887. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14888. if (d < 0)
  14889. return false;
  14890. pc.subtractToRef(point, this._tempVector3);
  14891. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  14892. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14893. if (d < 0)
  14894. return false;
  14895. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  14896. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14897. return d >= 0;
  14898. };
  14899. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  14900. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  14901. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  14902. if (distance > this.velocityWorldLength + max + sphereRadius) {
  14903. return false;
  14904. }
  14905. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  14906. return false;
  14907. return true;
  14908. };
  14909. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  14910. var t0;
  14911. var embeddedInPlane = false;
  14912. //defensive programming, actually not needed.
  14913. if (!trianglePlaneArray) {
  14914. trianglePlaneArray = [];
  14915. }
  14916. if (!trianglePlaneArray[faceIndex]) {
  14917. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  14918. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  14919. }
  14920. var trianglePlane = trianglePlaneArray[faceIndex];
  14921. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  14922. return;
  14923. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  14924. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  14925. if (normalDotVelocity == 0) {
  14926. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  14927. return;
  14928. embeddedInPlane = true;
  14929. t0 = 0;
  14930. }
  14931. else {
  14932. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  14933. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  14934. if (t0 > t1) {
  14935. var temp = t1;
  14936. t1 = t0;
  14937. t0 = temp;
  14938. }
  14939. if (t0 > 1.0 || t1 < 0.0)
  14940. return;
  14941. if (t0 < 0)
  14942. t0 = 0;
  14943. if (t0 > 1.0)
  14944. t0 = 1.0;
  14945. }
  14946. this._collisionPoint.copyFromFloats(0, 0, 0);
  14947. var found = false;
  14948. var t = 1.0;
  14949. if (!embeddedInPlane) {
  14950. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  14951. this.velocity.scaleToRef(t0, this._tempVector);
  14952. this._planeIntersectionPoint.addInPlace(this._tempVector);
  14953. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  14954. found = true;
  14955. t = t0;
  14956. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  14957. }
  14958. }
  14959. if (!found) {
  14960. var velocitySquaredLength = this.velocity.lengthSquared();
  14961. var a = velocitySquaredLength;
  14962. this.basePoint.subtractToRef(p1, this._tempVector);
  14963. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  14964. var c = this._tempVector.lengthSquared() - 1.0;
  14965. var lowestRoot = getLowestRoot(a, b, c, t);
  14966. if (lowestRoot.found) {
  14967. t = lowestRoot.root;
  14968. found = true;
  14969. this._collisionPoint.copyFrom(p1);
  14970. }
  14971. this.basePoint.subtractToRef(p2, this._tempVector);
  14972. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  14973. c = this._tempVector.lengthSquared() - 1.0;
  14974. lowestRoot = getLowestRoot(a, b, c, t);
  14975. if (lowestRoot.found) {
  14976. t = lowestRoot.root;
  14977. found = true;
  14978. this._collisionPoint.copyFrom(p2);
  14979. }
  14980. this.basePoint.subtractToRef(p3, this._tempVector);
  14981. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  14982. c = this._tempVector.lengthSquared() - 1.0;
  14983. lowestRoot = getLowestRoot(a, b, c, t);
  14984. if (lowestRoot.found) {
  14985. t = lowestRoot.root;
  14986. found = true;
  14987. this._collisionPoint.copyFrom(p3);
  14988. }
  14989. p2.subtractToRef(p1, this._edge);
  14990. p1.subtractToRef(this.basePoint, this._baseToVertex);
  14991. var edgeSquaredLength = this._edge.lengthSquared();
  14992. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  14993. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  14994. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  14995. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  14996. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  14997. lowestRoot = getLowestRoot(a, b, c, t);
  14998. if (lowestRoot.found) {
  14999. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15000. if (f >= 0.0 && f <= 1.0) {
  15001. t = lowestRoot.root;
  15002. found = true;
  15003. this._edge.scaleInPlace(f);
  15004. p1.addToRef(this._edge, this._collisionPoint);
  15005. }
  15006. }
  15007. p3.subtractToRef(p2, this._edge);
  15008. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15009. edgeSquaredLength = this._edge.lengthSquared();
  15010. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15011. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15012. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15013. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15014. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15015. lowestRoot = getLowestRoot(a, b, c, t);
  15016. if (lowestRoot.found) {
  15017. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15018. if (f >= 0.0 && f <= 1.0) {
  15019. t = lowestRoot.root;
  15020. found = true;
  15021. this._edge.scaleInPlace(f);
  15022. p2.addToRef(this._edge, this._collisionPoint);
  15023. }
  15024. }
  15025. p1.subtractToRef(p3, this._edge);
  15026. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15027. edgeSquaredLength = this._edge.lengthSquared();
  15028. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15029. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15030. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15031. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15032. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15033. lowestRoot = getLowestRoot(a, b, c, t);
  15034. if (lowestRoot.found) {
  15035. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15036. if (f >= 0.0 && f <= 1.0) {
  15037. t = lowestRoot.root;
  15038. found = true;
  15039. this._edge.scaleInPlace(f);
  15040. p3.addToRef(this._edge, this._collisionPoint);
  15041. }
  15042. }
  15043. }
  15044. if (found) {
  15045. var distToCollision = t * this.velocity.length();
  15046. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15047. if (!this.intersectionPoint) {
  15048. this.intersectionPoint = this._collisionPoint.clone();
  15049. }
  15050. else {
  15051. this.intersectionPoint.copyFrom(this._collisionPoint);
  15052. }
  15053. this.nearestDistance = distToCollision;
  15054. this.collisionFound = true;
  15055. }
  15056. }
  15057. };
  15058. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15059. for (var i = indexStart; i < indexEnd; i += 3) {
  15060. var p1 = pts[indices[i] - decal];
  15061. var p2 = pts[indices[i + 1] - decal];
  15062. var p3 = pts[indices[i + 2] - decal];
  15063. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15064. }
  15065. };
  15066. Collider.prototype._getResponse = function (pos, vel) {
  15067. pos.addToRef(vel, this._destinationPoint);
  15068. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15069. this.basePoint.addToRef(vel, pos);
  15070. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15071. this._slidePlaneNormal.normalize();
  15072. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15073. pos.addInPlace(this._displacementVector);
  15074. this.intersectionPoint.addInPlace(this._displacementVector);
  15075. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15076. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15077. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15078. };
  15079. return Collider;
  15080. }());
  15081. BABYLON.Collider = Collider;
  15082. })(BABYLON || (BABYLON = {}));
  15083. //# sourceMappingURL=babylon.collider.js.map
  15084. var BABYLON;
  15085. (function (BABYLON) {
  15086. //WebWorker code will be inserted to this variable.
  15087. BABYLON.CollisionWorker = "";
  15088. var WorkerTaskType;
  15089. (function (WorkerTaskType) {
  15090. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15091. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15092. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15093. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15094. var WorkerReplyType;
  15095. (function (WorkerReplyType) {
  15096. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15097. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15098. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15099. var CollisionCoordinatorWorker = (function () {
  15100. function CollisionCoordinatorWorker() {
  15101. var _this = this;
  15102. this._scaledPosition = BABYLON.Vector3.Zero();
  15103. this._scaledVelocity = BABYLON.Vector3.Zero();
  15104. this.onMeshUpdated = function (mesh) {
  15105. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15106. };
  15107. this.onGeometryUpdated = function (geometry) {
  15108. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15109. };
  15110. this._afterRender = function () {
  15111. if (!_this._init)
  15112. return;
  15113. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15114. return;
  15115. }
  15116. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15117. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15118. if (_this._runningUpdated > 4) {
  15119. return;
  15120. }
  15121. ++_this._runningUpdated;
  15122. var payload = {
  15123. updatedMeshes: _this._addUpdateMeshesList,
  15124. updatedGeometries: _this._addUpdateGeometriesList,
  15125. removedGeometries: _this._toRemoveGeometryArray,
  15126. removedMeshes: _this._toRemoveMeshesArray
  15127. };
  15128. var message = {
  15129. payload: payload,
  15130. taskType: WorkerTaskType.UPDATE
  15131. };
  15132. var serializable = [];
  15133. for (var id in payload.updatedGeometries) {
  15134. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15135. //prepare transferables
  15136. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15137. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15138. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15139. }
  15140. }
  15141. _this._worker.postMessage(message, serializable);
  15142. _this._addUpdateMeshesList = {};
  15143. _this._addUpdateGeometriesList = {};
  15144. _this._toRemoveGeometryArray = [];
  15145. _this._toRemoveMeshesArray = [];
  15146. };
  15147. this._onMessageFromWorker = function (e) {
  15148. var returnData = e.data;
  15149. if (returnData.error != WorkerReplyType.SUCCESS) {
  15150. //TODO what errors can be returned from the worker?
  15151. BABYLON.Tools.Warn("error returned from worker!");
  15152. return;
  15153. }
  15154. switch (returnData.taskType) {
  15155. case WorkerTaskType.INIT:
  15156. _this._init = true;
  15157. //Update the worked with ALL of the scene's current state
  15158. _this._scene.meshes.forEach(function (mesh) {
  15159. _this.onMeshAdded(mesh);
  15160. });
  15161. _this._scene.getGeometries().forEach(function (geometry) {
  15162. _this.onGeometryAdded(geometry);
  15163. });
  15164. break;
  15165. case WorkerTaskType.UPDATE:
  15166. _this._runningUpdated--;
  15167. break;
  15168. case WorkerTaskType.COLLIDE:
  15169. _this._runningCollisionTask = false;
  15170. var returnPayload = returnData.payload;
  15171. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15172. return;
  15173. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15174. //cleanup
  15175. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15176. break;
  15177. }
  15178. };
  15179. this._collisionsCallbackArray = [];
  15180. this._init = false;
  15181. this._runningUpdated = 0;
  15182. this._runningCollisionTask = false;
  15183. this._addUpdateMeshesList = {};
  15184. this._addUpdateGeometriesList = {};
  15185. this._toRemoveGeometryArray = [];
  15186. this._toRemoveMeshesArray = [];
  15187. }
  15188. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15189. if (!this._init)
  15190. return;
  15191. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15192. return;
  15193. position.divideToRef(collider.radius, this._scaledPosition);
  15194. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15195. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15196. var payload = {
  15197. collider: {
  15198. position: this._scaledPosition.asArray(),
  15199. velocity: this._scaledVelocity.asArray(),
  15200. radius: collider.radius.asArray()
  15201. },
  15202. collisionId: collisionIndex,
  15203. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15204. maximumRetry: maximumRetry
  15205. };
  15206. var message = {
  15207. payload: payload,
  15208. taskType: WorkerTaskType.COLLIDE
  15209. };
  15210. this._worker.postMessage(message);
  15211. };
  15212. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15213. this._scene = scene;
  15214. this._scene.registerAfterRender(this._afterRender);
  15215. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15216. this._worker = new Worker(workerUrl);
  15217. this._worker.onmessage = this._onMessageFromWorker;
  15218. var message = {
  15219. payload: {},
  15220. taskType: WorkerTaskType.INIT
  15221. };
  15222. this._worker.postMessage(message);
  15223. };
  15224. CollisionCoordinatorWorker.prototype.destroy = function () {
  15225. this._scene.unregisterAfterRender(this._afterRender);
  15226. this._worker.terminate();
  15227. };
  15228. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15229. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15230. this.onMeshUpdated(mesh);
  15231. };
  15232. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15233. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15234. };
  15235. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15236. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15237. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15238. this.onGeometryUpdated(geometry);
  15239. };
  15240. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15241. this._toRemoveGeometryArray.push(geometry.id);
  15242. };
  15243. return CollisionCoordinatorWorker;
  15244. }());
  15245. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15246. var submeshes = [];
  15247. if (mesh.subMeshes) {
  15248. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15249. return {
  15250. position: idx,
  15251. verticesStart: sm.verticesStart,
  15252. verticesCount: sm.verticesCount,
  15253. indexStart: sm.indexStart,
  15254. indexCount: sm.indexCount,
  15255. hasMaterial: !!sm.getMaterial(),
  15256. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15257. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15258. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15259. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15260. };
  15261. });
  15262. }
  15263. var geometryId = null;
  15264. if (mesh instanceof BABYLON.Mesh) {
  15265. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15266. }
  15267. else if (mesh instanceof BABYLON.InstancedMesh) {
  15268. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15269. }
  15270. return {
  15271. uniqueId: mesh.uniqueId,
  15272. id: mesh.id,
  15273. name: mesh.name,
  15274. geometryId: geometryId,
  15275. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15276. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15277. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15278. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15279. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15280. subMeshes: submeshes,
  15281. checkCollisions: mesh.checkCollisions
  15282. };
  15283. };
  15284. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15285. return {
  15286. id: geometry.id,
  15287. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15288. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15289. indices: new Uint32Array(geometry.getIndices() || []),
  15290. };
  15291. };
  15292. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15293. var CollisionCoordinatorLegacy = (function () {
  15294. function CollisionCoordinatorLegacy() {
  15295. this._scaledPosition = BABYLON.Vector3.Zero();
  15296. this._scaledVelocity = BABYLON.Vector3.Zero();
  15297. this._finalPosition = BABYLON.Vector3.Zero();
  15298. }
  15299. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15300. position.divideToRef(collider.radius, this._scaledPosition);
  15301. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15302. collider.collidedMesh = null;
  15303. collider.retry = 0;
  15304. collider.initialVelocity = this._scaledVelocity;
  15305. collider.initialPosition = this._scaledPosition;
  15306. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15307. this._finalPosition.multiplyInPlace(collider.radius);
  15308. //run the callback
  15309. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15310. };
  15311. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15312. this._scene = scene;
  15313. };
  15314. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15315. //Legacy need no destruction method.
  15316. };
  15317. //No update in legacy mode
  15318. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15319. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15320. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15321. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15322. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15323. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15324. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15325. if (excludedMesh === void 0) { excludedMesh = null; }
  15326. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15327. if (collider.retry >= maximumRetry) {
  15328. finalPosition.copyFrom(position);
  15329. return;
  15330. }
  15331. // Check if this is a mesh else camera or -1
  15332. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15333. collider._initialize(position, velocity, closeDistance);
  15334. // Check all meshes
  15335. for (var index = 0; index < this._scene.meshes.length; index++) {
  15336. var mesh = this._scene.meshes[index];
  15337. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15338. mesh._checkCollision(collider);
  15339. }
  15340. }
  15341. if (!collider.collisionFound) {
  15342. position.addToRef(velocity, finalPosition);
  15343. return;
  15344. }
  15345. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15346. collider._getResponse(position, velocity);
  15347. }
  15348. if (velocity.length() <= closeDistance) {
  15349. finalPosition.copyFrom(position);
  15350. return;
  15351. }
  15352. collider.retry++;
  15353. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15354. };
  15355. return CollisionCoordinatorLegacy;
  15356. }());
  15357. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15358. })(BABYLON || (BABYLON = {}));
  15359. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15360. var BABYLON;
  15361. (function (BABYLON) {
  15362. var Camera = (function (_super) {
  15363. __extends(Camera, _super);
  15364. function Camera(name, position, scene) {
  15365. var _this = _super.call(this, name, scene) || this;
  15366. _this.upVector = BABYLON.Vector3.Up();
  15367. _this.orthoLeft = null;
  15368. _this.orthoRight = null;
  15369. _this.orthoBottom = null;
  15370. _this.orthoTop = null;
  15371. _this.fov = 0.8;
  15372. _this.minZ = 1.0;
  15373. _this.maxZ = 10000.0;
  15374. _this.inertia = 0.9;
  15375. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15376. _this.isIntermediate = false;
  15377. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15378. _this.layerMask = 0x0FFFFFFF;
  15379. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15380. // Camera rig members
  15381. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15382. _this._rigCameras = new Array();
  15383. // Cache
  15384. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15385. _this._projectionMatrix = new BABYLON.Matrix();
  15386. _this._doNotComputeProjectionMatrix = false;
  15387. _this._postProcesses = new Array();
  15388. _this._transformMatrix = BABYLON.Matrix.Zero();
  15389. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15390. _this._activeMeshes = new BABYLON.SmartArray(256);
  15391. _this._globalPosition = BABYLON.Vector3.Zero();
  15392. _this._refreshFrustumPlanes = true;
  15393. scene.addCamera(_this);
  15394. if (!scene.activeCamera) {
  15395. scene.activeCamera = _this;
  15396. }
  15397. _this.position = position;
  15398. return _this;
  15399. }
  15400. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15401. get: function () {
  15402. return Camera._PERSPECTIVE_CAMERA;
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15408. get: function () {
  15409. return Camera._ORTHOGRAPHIC_CAMERA;
  15410. },
  15411. enumerable: true,
  15412. configurable: true
  15413. });
  15414. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15415. get: function () {
  15416. return Camera._FOVMODE_VERTICAL_FIXED;
  15417. },
  15418. enumerable: true,
  15419. configurable: true
  15420. });
  15421. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15422. get: function () {
  15423. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15424. },
  15425. enumerable: true,
  15426. configurable: true
  15427. });
  15428. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15429. get: function () {
  15430. return Camera._RIG_MODE_NONE;
  15431. },
  15432. enumerable: true,
  15433. configurable: true
  15434. });
  15435. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15436. get: function () {
  15437. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15438. },
  15439. enumerable: true,
  15440. configurable: true
  15441. });
  15442. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15443. get: function () {
  15444. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15445. },
  15446. enumerable: true,
  15447. configurable: true
  15448. });
  15449. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15450. get: function () {
  15451. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15457. get: function () {
  15458. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15459. },
  15460. enumerable: true,
  15461. configurable: true
  15462. });
  15463. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15464. get: function () {
  15465. return Camera._RIG_MODE_VR;
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15471. get: function () {
  15472. return Camera._RIG_MODE_WEBVR;
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. Camera.prototype.getClassName = function () {
  15478. return "Camera";
  15479. };
  15480. /**
  15481. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15482. */
  15483. Camera.prototype.toString = function (fullDetails) {
  15484. var ret = "Name: " + this.name;
  15485. ret += ", type: " + this.getClassName();
  15486. if (this.animations) {
  15487. for (var i = 0; i < this.animations.length; i++) {
  15488. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15489. }
  15490. }
  15491. if (fullDetails) {
  15492. }
  15493. return ret;
  15494. };
  15495. Object.defineProperty(Camera.prototype, "globalPosition", {
  15496. get: function () {
  15497. return this._globalPosition;
  15498. },
  15499. enumerable: true,
  15500. configurable: true
  15501. });
  15502. Camera.prototype.getActiveMeshes = function () {
  15503. return this._activeMeshes;
  15504. };
  15505. Camera.prototype.isActiveMesh = function (mesh) {
  15506. return (this._activeMeshes.indexOf(mesh) !== -1);
  15507. };
  15508. //Cache
  15509. Camera.prototype._initCache = function () {
  15510. _super.prototype._initCache.call(this);
  15511. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15512. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15513. this._cache.mode = undefined;
  15514. this._cache.minZ = undefined;
  15515. this._cache.maxZ = undefined;
  15516. this._cache.fov = undefined;
  15517. this._cache.fovMode = undefined;
  15518. this._cache.aspectRatio = undefined;
  15519. this._cache.orthoLeft = undefined;
  15520. this._cache.orthoRight = undefined;
  15521. this._cache.orthoBottom = undefined;
  15522. this._cache.orthoTop = undefined;
  15523. this._cache.renderWidth = undefined;
  15524. this._cache.renderHeight = undefined;
  15525. };
  15526. Camera.prototype._updateCache = function (ignoreParentClass) {
  15527. if (!ignoreParentClass) {
  15528. _super.prototype._updateCache.call(this);
  15529. }
  15530. var engine = this.getEngine();
  15531. this._cache.position.copyFrom(this.position);
  15532. this._cache.upVector.copyFrom(this.upVector);
  15533. this._cache.mode = this.mode;
  15534. this._cache.minZ = this.minZ;
  15535. this._cache.maxZ = this.maxZ;
  15536. this._cache.fov = this.fov;
  15537. this._cache.fovMode = this.fovMode;
  15538. this._cache.aspectRatio = engine.getAspectRatio(this);
  15539. this._cache.orthoLeft = this.orthoLeft;
  15540. this._cache.orthoRight = this.orthoRight;
  15541. this._cache.orthoBottom = this.orthoBottom;
  15542. this._cache.orthoTop = this.orthoTop;
  15543. this._cache.renderWidth = engine.getRenderWidth();
  15544. this._cache.renderHeight = engine.getRenderHeight();
  15545. };
  15546. Camera.prototype._updateFromScene = function () {
  15547. this.updateCache();
  15548. this.update();
  15549. };
  15550. // Synchronized
  15551. Camera.prototype._isSynchronized = function () {
  15552. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15553. };
  15554. Camera.prototype._isSynchronizedViewMatrix = function () {
  15555. if (!_super.prototype._isSynchronized.call(this))
  15556. return false;
  15557. return this._cache.position.equals(this.position)
  15558. && this._cache.upVector.equals(this.upVector)
  15559. && this.isSynchronizedWithParent();
  15560. };
  15561. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15562. var check = this._cache.mode === this.mode
  15563. && this._cache.minZ === this.minZ
  15564. && this._cache.maxZ === this.maxZ;
  15565. if (!check) {
  15566. return false;
  15567. }
  15568. var engine = this.getEngine();
  15569. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15570. check = this._cache.fov === this.fov
  15571. && this._cache.fovMode === this.fovMode
  15572. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15573. }
  15574. else {
  15575. check = this._cache.orthoLeft === this.orthoLeft
  15576. && this._cache.orthoRight === this.orthoRight
  15577. && this._cache.orthoBottom === this.orthoBottom
  15578. && this._cache.orthoTop === this.orthoTop
  15579. && this._cache.renderWidth === engine.getRenderWidth()
  15580. && this._cache.renderHeight === engine.getRenderHeight();
  15581. }
  15582. return check;
  15583. };
  15584. // Controls
  15585. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15586. };
  15587. Camera.prototype.detachControl = function (element) {
  15588. };
  15589. Camera.prototype.update = function () {
  15590. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15591. this._updateRigCameras();
  15592. }
  15593. this._checkInputs();
  15594. };
  15595. Camera.prototype._checkInputs = function () {
  15596. };
  15597. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15598. // invalidate framebuffer
  15599. if (this._postProcesses.length > 0) {
  15600. this._postProcesses[0].markTextureDirty();
  15601. }
  15602. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15603. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15604. var cam = this._rigCameras[i];
  15605. var rigPostProcess = cam._rigPostProcess;
  15606. // for VR rig, there does not have to be a post process
  15607. if (rigPostProcess) {
  15608. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15609. if (isPass) {
  15610. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15611. cam.isIntermediate = this._postProcesses.length === 0;
  15612. }
  15613. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15614. rigPostProcess.markTextureDirty();
  15615. }
  15616. else {
  15617. cam._postProcesses = this._postProcesses.slice(0);
  15618. }
  15619. }
  15620. };
  15621. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15622. if (insertAt === void 0) { insertAt = null; }
  15623. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15624. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15625. return 0;
  15626. }
  15627. if (insertAt == null || insertAt < 0) {
  15628. this._postProcesses.push(postProcess);
  15629. }
  15630. else {
  15631. this._postProcesses.splice(insertAt, 0, postProcess);
  15632. }
  15633. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15634. return this._postProcesses.indexOf(postProcess);
  15635. };
  15636. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15637. if (atIndices === void 0) { atIndices = null; }
  15638. var result = [];
  15639. var i;
  15640. var index;
  15641. if (!atIndices) {
  15642. var idx = this._postProcesses.indexOf(postProcess);
  15643. if (idx !== -1) {
  15644. this._postProcesses.splice(idx, 1);
  15645. }
  15646. }
  15647. else {
  15648. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15649. // iterate descending, so can just splice as we go
  15650. for (i = atIndices.length - 1; i >= 0; i--) {
  15651. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15652. result.push(i);
  15653. continue;
  15654. }
  15655. index = atIndices[i];
  15656. this._postProcesses.splice(index, 1);
  15657. }
  15658. }
  15659. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15660. return result;
  15661. };
  15662. Camera.prototype.getWorldMatrix = function () {
  15663. if (!this._worldMatrix) {
  15664. this._worldMatrix = BABYLON.Matrix.Identity();
  15665. }
  15666. var viewMatrix = this.getViewMatrix();
  15667. viewMatrix.invertToRef(this._worldMatrix);
  15668. return this._worldMatrix;
  15669. };
  15670. Camera.prototype._getViewMatrix = function () {
  15671. return BABYLON.Matrix.Identity();
  15672. };
  15673. Camera.prototype.getViewMatrix = function (force) {
  15674. this._computedViewMatrix = this._computeViewMatrix(force);
  15675. if (!force && this._isSynchronizedViewMatrix()) {
  15676. return this._computedViewMatrix;
  15677. }
  15678. this._refreshFrustumPlanes = true;
  15679. if (!this.parent || !this.parent.getWorldMatrix) {
  15680. this._globalPosition.copyFrom(this.position);
  15681. }
  15682. else {
  15683. if (!this._worldMatrix) {
  15684. this._worldMatrix = BABYLON.Matrix.Identity();
  15685. }
  15686. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15687. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15688. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15689. this._computedViewMatrix.invert();
  15690. this._markSyncedWithParent();
  15691. }
  15692. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15693. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15694. }
  15695. this._currentRenderId = this.getScene().getRenderId();
  15696. return this._computedViewMatrix;
  15697. };
  15698. Camera.prototype._computeViewMatrix = function (force) {
  15699. if (!force && this._isSynchronizedViewMatrix()) {
  15700. return this._computedViewMatrix;
  15701. }
  15702. this._computedViewMatrix = this._getViewMatrix();
  15703. this._currentRenderId = this.getScene().getRenderId();
  15704. return this._computedViewMatrix;
  15705. };
  15706. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15707. this._doNotComputeProjectionMatrix = true;
  15708. if (projection !== undefined) {
  15709. this._projectionMatrix = projection;
  15710. }
  15711. };
  15712. ;
  15713. Camera.prototype.unfreezeProjectionMatrix = function () {
  15714. this._doNotComputeProjectionMatrix = false;
  15715. };
  15716. ;
  15717. Camera.prototype.getProjectionMatrix = function (force) {
  15718. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15719. return this._projectionMatrix;
  15720. }
  15721. this._refreshFrustumPlanes = true;
  15722. var engine = this.getEngine();
  15723. var scene = this.getScene();
  15724. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15725. if (this.minZ <= 0) {
  15726. this.minZ = 0.1;
  15727. }
  15728. if (scene.useRightHandedSystem) {
  15729. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15730. }
  15731. else {
  15732. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15733. }
  15734. return this._projectionMatrix;
  15735. }
  15736. var halfWidth = engine.getRenderWidth() / 2.0;
  15737. var halfHeight = engine.getRenderHeight() / 2.0;
  15738. if (scene.useRightHandedSystem) {
  15739. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15740. }
  15741. else {
  15742. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15743. }
  15744. return this._projectionMatrix;
  15745. };
  15746. Camera.prototype.getTranformationMatrix = function () {
  15747. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15748. return this._transformMatrix;
  15749. };
  15750. Camera.prototype.updateFrustumPlanes = function () {
  15751. if (!this._refreshFrustumPlanes) {
  15752. return;
  15753. }
  15754. this.getTranformationMatrix();
  15755. if (!this._frustumPlanes) {
  15756. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15757. }
  15758. else {
  15759. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15760. }
  15761. this._refreshFrustumPlanes = false;
  15762. };
  15763. Camera.prototype.isInFrustum = function (target) {
  15764. this.updateFrustumPlanes();
  15765. return target.isInFrustum(this._frustumPlanes);
  15766. };
  15767. Camera.prototype.isCompletelyInFrustum = function (target) {
  15768. this.updateFrustumPlanes();
  15769. return target.isCompletelyInFrustum(this._frustumPlanes);
  15770. };
  15771. Camera.prototype.dispose = function () {
  15772. // Animations
  15773. this.getScene().stopAnimation(this);
  15774. // Remove from scene
  15775. this.getScene().removeCamera(this);
  15776. while (this._rigCameras.length > 0) {
  15777. this._rigCameras.pop().dispose();
  15778. }
  15779. // Postprocesses
  15780. var i = this._postProcesses.length;
  15781. while (--i >= 0) {
  15782. this._postProcesses[i].dispose(this);
  15783. }
  15784. _super.prototype.dispose.call(this);
  15785. };
  15786. // ---- Camera rigs section ----
  15787. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15788. while (this._rigCameras.length > 0) {
  15789. this._rigCameras.pop().dispose();
  15790. }
  15791. this.cameraRigMode = mode;
  15792. this._cameraRigParams = {};
  15793. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15794. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15795. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15796. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15797. // create the rig cameras, unless none
  15798. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15799. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15800. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15801. }
  15802. switch (this.cameraRigMode) {
  15803. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15804. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15805. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15806. break;
  15807. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15808. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15809. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15810. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15812. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15813. break;
  15814. case Camera.RIG_MODE_VR:
  15815. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15816. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15817. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15818. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15819. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15820. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15821. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15822. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15823. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15824. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15825. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15826. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15827. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15828. if (metrics.compensateDistortion) {
  15829. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15830. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15831. }
  15832. break;
  15833. case Camera.RIG_MODE_WEBVR:
  15834. if (rigParams.vrDisplay) {
  15835. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15836. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15837. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15838. this._rigCameras[0].setCameraRigParameter("left", true);
  15839. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15840. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  15841. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15842. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15843. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15844. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15845. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15846. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  15847. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15848. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15849. }
  15850. break;
  15851. }
  15852. this._cascadePostProcessesToRigCams();
  15853. this.
  15854. update();
  15855. };
  15856. Camera.prototype._getVRProjectionMatrix = function () {
  15857. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15858. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15859. return this._projectionMatrix;
  15860. };
  15861. Camera.prototype._getWebVRProjectionMatrix = function () {
  15862. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  15863. //babylon compatible matrix
  15864. [8, 9, 10, 11].forEach(function (num) {
  15865. projectionArray[num] *= -1;
  15866. });
  15867. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  15868. return this._projectionMatrix;
  15869. };
  15870. //Can be used, but we'll use the free camera's view matrix calculation
  15871. Camera.prototype._getWebVRViewMatrix = function () {
  15872. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  15873. //babylon compatible matrix
  15874. [8, 9, 10, 11].forEach(function (num) {
  15875. projectionArray[num] *= -1;
  15876. });
  15877. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  15878. return this._webvrViewMatrix;
  15879. };
  15880. Camera.prototype.setCameraRigParameter = function (name, value) {
  15881. if (!this._cameraRigParams) {
  15882. this._cameraRigParams = {};
  15883. }
  15884. this._cameraRigParams[name] = value;
  15885. //provisionnally:
  15886. if (name === "interaxialDistance") {
  15887. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15888. }
  15889. };
  15890. /**
  15891. * needs to be overridden by children so sub has required properties to be copied
  15892. */
  15893. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15894. return null;
  15895. };
  15896. /**
  15897. * May need to be overridden by children
  15898. */
  15899. Camera.prototype._updateRigCameras = function () {
  15900. for (var i = 0; i < this._rigCameras.length; i++) {
  15901. this._rigCameras[i].minZ = this.minZ;
  15902. this._rigCameras[i].maxZ = this.maxZ;
  15903. this._rigCameras[i].fov = this.fov;
  15904. }
  15905. // only update viewport when ANAGLYPH
  15906. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15907. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15908. }
  15909. };
  15910. Camera.prototype._setupInputs = function () {
  15911. };
  15912. Camera.prototype.serialize = function () {
  15913. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15914. // Type
  15915. serializationObject.type = this.getClassName();
  15916. // Parent
  15917. if (this.parent) {
  15918. serializationObject.parentId = this.parent.id;
  15919. }
  15920. if (this.inputs) {
  15921. this.inputs.serialize(serializationObject);
  15922. }
  15923. // Animations
  15924. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15925. serializationObject.ranges = this.serializeAnimationRanges();
  15926. return serializationObject;
  15927. };
  15928. Camera.prototype.clone = function (name) {
  15929. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15930. };
  15931. Camera.prototype.getDirection = function (localAxis) {
  15932. var result = BABYLON.Vector3.Zero();
  15933. this.getDirectionToRef(localAxis, result);
  15934. return result;
  15935. };
  15936. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15937. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15938. };
  15939. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15940. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15941. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15942. switch (type) {
  15943. case "ArcRotateCamera":
  15944. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15945. case "DeviceOrientationCamera":
  15946. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15947. case "FollowCamera":
  15948. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15949. case "ArcFollowCamera":
  15950. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15951. case "GamepadCamera":
  15952. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15953. case "TouchCamera":
  15954. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15955. case "VirtualJoysticksCamera":
  15956. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15957. case "WebVRFreeCamera":
  15958. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15959. case "WebVRGamepadCamera":
  15960. return function () { return new BABYLON.WebVRGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15961. case "VRDeviceOrientationFreeCamera":
  15962. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15963. case "VRDeviceOrientationGamepadCamera":
  15964. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15965. case "AnaglyphArcRotateCamera":
  15966. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15967. case "AnaglyphFreeCamera":
  15968. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15969. case "AnaglyphGamepadCamera":
  15970. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15971. case "AnaglyphUniversalCamera":
  15972. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15973. case "StereoscopicArcRotateCamera":
  15974. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15975. case "StereoscopicFreeCamera":
  15976. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15977. case "StereoscopicGamepadCamera":
  15978. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15979. case "StereoscopicUniversalCamera":
  15980. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15981. case "FreeCamera":
  15982. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15983. default:
  15984. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15985. }
  15986. };
  15987. Camera.Parse = function (parsedCamera, scene) {
  15988. var type = parsedCamera.type;
  15989. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15990. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15991. // Parent
  15992. if (parsedCamera.parentId) {
  15993. camera._waitingParentId = parsedCamera.parentId;
  15994. }
  15995. //If camera has an input manager, let it parse inputs settings
  15996. if (camera.inputs) {
  15997. camera.inputs.parse(parsedCamera);
  15998. camera._setupInputs();
  15999. }
  16000. // Target
  16001. if (parsedCamera.target) {
  16002. if (camera.setTarget) {
  16003. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16004. }
  16005. }
  16006. // Apply 3d rig, when found
  16007. if (parsedCamera.cameraRigMode) {
  16008. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16009. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16010. }
  16011. // Animations
  16012. if (parsedCamera.animations) {
  16013. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16014. var parsedAnimation = parsedCamera.animations[animationIndex];
  16015. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16016. }
  16017. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16018. }
  16019. if (parsedCamera.autoAnimate) {
  16020. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16021. }
  16022. return camera;
  16023. };
  16024. return Camera;
  16025. }(BABYLON.Node));
  16026. // Statics
  16027. Camera._PERSPECTIVE_CAMERA = 0;
  16028. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16029. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16030. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16031. Camera._RIG_MODE_NONE = 0;
  16032. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16033. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16034. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16035. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16036. Camera._RIG_MODE_VR = 20;
  16037. Camera._RIG_MODE_WEBVR = 21;
  16038. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16039. __decorate([
  16040. BABYLON.serializeAsVector3()
  16041. ], Camera.prototype, "position", void 0);
  16042. __decorate([
  16043. BABYLON.serializeAsVector3()
  16044. ], Camera.prototype, "upVector", void 0);
  16045. __decorate([
  16046. BABYLON.serialize()
  16047. ], Camera.prototype, "orthoLeft", void 0);
  16048. __decorate([
  16049. BABYLON.serialize()
  16050. ], Camera.prototype, "orthoRight", void 0);
  16051. __decorate([
  16052. BABYLON.serialize()
  16053. ], Camera.prototype, "orthoBottom", void 0);
  16054. __decorate([
  16055. BABYLON.serialize()
  16056. ], Camera.prototype, "orthoTop", void 0);
  16057. __decorate([
  16058. BABYLON.serialize()
  16059. ], Camera.prototype, "fov", void 0);
  16060. __decorate([
  16061. BABYLON.serialize()
  16062. ], Camera.prototype, "minZ", void 0);
  16063. __decorate([
  16064. BABYLON.serialize()
  16065. ], Camera.prototype, "maxZ", void 0);
  16066. __decorate([
  16067. BABYLON.serialize()
  16068. ], Camera.prototype, "inertia", void 0);
  16069. __decorate([
  16070. BABYLON.serialize()
  16071. ], Camera.prototype, "mode", void 0);
  16072. __decorate([
  16073. BABYLON.serialize()
  16074. ], Camera.prototype, "layerMask", void 0);
  16075. __decorate([
  16076. BABYLON.serialize()
  16077. ], Camera.prototype, "fovMode", void 0);
  16078. __decorate([
  16079. BABYLON.serialize()
  16080. ], Camera.prototype, "cameraRigMode", void 0);
  16081. __decorate([
  16082. BABYLON.serialize()
  16083. ], Camera.prototype, "interaxialDistance", void 0);
  16084. __decorate([
  16085. BABYLON.serialize()
  16086. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16087. BABYLON.Camera = Camera;
  16088. })(BABYLON || (BABYLON = {}));
  16089. //# sourceMappingURL=babylon.camera.js.map
  16090. var BABYLON;
  16091. (function (BABYLON) {
  16092. BABYLON.CameraInputTypes = {};
  16093. var CameraInputsManager = (function () {
  16094. function CameraInputsManager(camera) {
  16095. this.attached = {};
  16096. this.camera = camera;
  16097. this.checkInputs = function () { };
  16098. }
  16099. CameraInputsManager.prototype.add = function (input) {
  16100. var type = input.getSimpleName();
  16101. if (this.attached[type]) {
  16102. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16103. return;
  16104. }
  16105. this.attached[type] = input;
  16106. input.camera = this.camera;
  16107. //for checkInputs, we are dynamically creating a function
  16108. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16109. if (input.checkInputs) {
  16110. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16111. }
  16112. if (this.attachedElement) {
  16113. input.attachControl(this.attachedElement);
  16114. }
  16115. };
  16116. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16117. for (var cam in this.attached) {
  16118. var input = this.attached[cam];
  16119. if (input === inputToRemove) {
  16120. input.detachControl(this.attachedElement);
  16121. delete this.attached[cam];
  16122. this.rebuildInputCheck();
  16123. }
  16124. }
  16125. };
  16126. CameraInputsManager.prototype.removeByType = function (inputType) {
  16127. for (var cam in this.attached) {
  16128. var input = this.attached[cam];
  16129. if (input.getTypeName() === inputType) {
  16130. input.detachControl(this.attachedElement);
  16131. delete this.attached[cam];
  16132. this.rebuildInputCheck();
  16133. }
  16134. }
  16135. };
  16136. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16137. var current = this.checkInputs;
  16138. return function () {
  16139. current();
  16140. fn();
  16141. };
  16142. };
  16143. CameraInputsManager.prototype.attachInput = function (input) {
  16144. input.attachControl(this.attachedElement, this.noPreventDefault);
  16145. };
  16146. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16147. if (this.attachedElement) {
  16148. return;
  16149. }
  16150. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16151. this.attachedElement = element;
  16152. this.noPreventDefault = noPreventDefault;
  16153. for (var cam in this.attached) {
  16154. var input = this.attached[cam];
  16155. this.attached[cam].attachControl(element, noPreventDefault);
  16156. }
  16157. };
  16158. CameraInputsManager.prototype.detachElement = function (element) {
  16159. if (this.attachedElement !== element) {
  16160. return;
  16161. }
  16162. for (var cam in this.attached) {
  16163. var input = this.attached[cam];
  16164. this.attached[cam].detachControl(element);
  16165. }
  16166. this.attachedElement = null;
  16167. };
  16168. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16169. this.checkInputs = function () { };
  16170. for (var cam in this.attached) {
  16171. var input = this.attached[cam];
  16172. if (input.checkInputs) {
  16173. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16174. }
  16175. }
  16176. };
  16177. CameraInputsManager.prototype.clear = function () {
  16178. if (this.attachedElement) {
  16179. this.detachElement(this.attachedElement);
  16180. }
  16181. this.attached = {};
  16182. this.attachedElement = null;
  16183. this.checkInputs = function () { };
  16184. };
  16185. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16186. var inputs = {};
  16187. for (var cam in this.attached) {
  16188. var input = this.attached[cam];
  16189. var res = BABYLON.SerializationHelper.Serialize(input);
  16190. inputs[input.getTypeName()] = res;
  16191. }
  16192. serializedCamera.inputsmgr = inputs;
  16193. };
  16194. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16195. var parsedInputs = parsedCamera.inputsmgr;
  16196. if (parsedInputs) {
  16197. this.clear();
  16198. for (var n in parsedInputs) {
  16199. var construct = BABYLON.CameraInputTypes[n];
  16200. if (construct) {
  16201. var parsedinput = parsedInputs[n];
  16202. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16203. this.add(input);
  16204. }
  16205. }
  16206. }
  16207. else {
  16208. //2016-03-08 this part is for managing backward compatibility
  16209. for (var n in this.attached) {
  16210. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16211. if (construct) {
  16212. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16213. this.remove(this.attached[n]);
  16214. this.add(input);
  16215. }
  16216. }
  16217. }
  16218. };
  16219. return CameraInputsManager;
  16220. }());
  16221. BABYLON.CameraInputsManager = CameraInputsManager;
  16222. })(BABYLON || (BABYLON = {}));
  16223. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16224. var BABYLON;
  16225. (function (BABYLON) {
  16226. var FreeCameraMouseInput = (function () {
  16227. function FreeCameraMouseInput(touchEnabled) {
  16228. if (touchEnabled === void 0) { touchEnabled = true; }
  16229. this.touchEnabled = touchEnabled;
  16230. this.buttons = [0, 1, 2];
  16231. this.angularSensibility = 2000.0;
  16232. }
  16233. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16234. var _this = this;
  16235. var engine = this.camera.getEngine();
  16236. if (!this._pointerInput) {
  16237. this._pointerInput = function (p, s) {
  16238. var evt = p.event;
  16239. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16240. return;
  16241. }
  16242. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16243. return;
  16244. }
  16245. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16246. try {
  16247. evt.srcElement.setPointerCapture(evt.pointerId);
  16248. }
  16249. catch (e) {
  16250. }
  16251. _this.previousPosition = {
  16252. x: evt.clientX,
  16253. y: evt.clientY
  16254. };
  16255. if (!noPreventDefault) {
  16256. evt.preventDefault();
  16257. element.focus();
  16258. }
  16259. }
  16260. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16261. try {
  16262. evt.srcElement.releasePointerCapture(evt.pointerId);
  16263. }
  16264. catch (e) {
  16265. }
  16266. _this.previousPosition = null;
  16267. if (!noPreventDefault) {
  16268. evt.preventDefault();
  16269. }
  16270. }
  16271. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16272. if (!_this.previousPosition || engine.isPointerLock) {
  16273. return;
  16274. }
  16275. var offsetX = evt.clientX - _this.previousPosition.x;
  16276. var offsetY = evt.clientY - _this.previousPosition.y;
  16277. if (_this.camera.getScene().useRightHandedSystem) {
  16278. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16279. }
  16280. else {
  16281. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16282. }
  16283. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16284. _this.previousPosition = {
  16285. x: evt.clientX,
  16286. y: evt.clientY
  16287. };
  16288. if (!noPreventDefault) {
  16289. evt.preventDefault();
  16290. }
  16291. }
  16292. };
  16293. }
  16294. this._onMouseMove = function (evt) {
  16295. if (!engine.isPointerLock) {
  16296. return;
  16297. }
  16298. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16299. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16300. if (_this.camera.getScene().useRightHandedSystem) {
  16301. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16302. }
  16303. else {
  16304. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16305. }
  16306. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16307. _this.previousPosition = null;
  16308. if (!noPreventDefault) {
  16309. evt.preventDefault();
  16310. }
  16311. };
  16312. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16313. element.addEventListener("mousemove", this._onMouseMove, false);
  16314. };
  16315. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16316. if (this._observer && element) {
  16317. this.camera.getScene().onPointerObservable.remove(this._observer);
  16318. element.removeEventListener("mousemove", this._onMouseMove);
  16319. this._observer = null;
  16320. this._onMouseMove = null;
  16321. this.previousPosition = null;
  16322. }
  16323. };
  16324. FreeCameraMouseInput.prototype.getTypeName = function () {
  16325. return "FreeCameraMouseInput";
  16326. };
  16327. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16328. return "mouse";
  16329. };
  16330. return FreeCameraMouseInput;
  16331. }());
  16332. __decorate([
  16333. BABYLON.serialize()
  16334. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16335. __decorate([
  16336. BABYLON.serialize()
  16337. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16338. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16339. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16340. })(BABYLON || (BABYLON = {}));
  16341. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16342. var BABYLON;
  16343. (function (BABYLON) {
  16344. var FreeCameraKeyboardMoveInput = (function () {
  16345. function FreeCameraKeyboardMoveInput() {
  16346. this._keys = [];
  16347. this.keysUp = [38];
  16348. this.keysDown = [40];
  16349. this.keysLeft = [37];
  16350. this.keysRight = [39];
  16351. }
  16352. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16353. var _this = this;
  16354. if (!this._onKeyDown) {
  16355. element.tabIndex = 1;
  16356. this._onKeyDown = function (evt) {
  16357. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16358. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16359. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16360. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16361. var index = _this._keys.indexOf(evt.keyCode);
  16362. if (index === -1) {
  16363. _this._keys.push(evt.keyCode);
  16364. }
  16365. if (!noPreventDefault) {
  16366. evt.preventDefault();
  16367. }
  16368. }
  16369. };
  16370. this._onKeyUp = function (evt) {
  16371. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16372. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16373. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16374. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16375. var index = _this._keys.indexOf(evt.keyCode);
  16376. if (index >= 0) {
  16377. _this._keys.splice(index, 1);
  16378. }
  16379. if (!noPreventDefault) {
  16380. evt.preventDefault();
  16381. }
  16382. }
  16383. };
  16384. element.addEventListener("keydown", this._onKeyDown, false);
  16385. element.addEventListener("keyup", this._onKeyUp, false);
  16386. BABYLON.Tools.RegisterTopRootEvents([
  16387. { name: "blur", handler: this._onLostFocus }
  16388. ]);
  16389. }
  16390. };
  16391. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16392. if (this._onKeyDown) {
  16393. element.removeEventListener("keydown", this._onKeyDown);
  16394. element.removeEventListener("keyup", this._onKeyUp);
  16395. BABYLON.Tools.UnregisterTopRootEvents([
  16396. { name: "blur", handler: this._onLostFocus }
  16397. ]);
  16398. this._keys = [];
  16399. this._onKeyDown = null;
  16400. this._onKeyUp = null;
  16401. }
  16402. };
  16403. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16404. if (this._onKeyDown) {
  16405. var camera = this.camera;
  16406. // Keyboard
  16407. for (var index = 0; index < this._keys.length; index++) {
  16408. var keyCode = this._keys[index];
  16409. var speed = camera._computeLocalCameraSpeed();
  16410. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16411. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16412. }
  16413. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16414. camera._localDirection.copyFromFloats(0, 0, speed);
  16415. }
  16416. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16417. camera._localDirection.copyFromFloats(speed, 0, 0);
  16418. }
  16419. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16420. camera._localDirection.copyFromFloats(0, 0, -speed);
  16421. }
  16422. if (camera.getScene().useRightHandedSystem) {
  16423. camera._localDirection.z *= -1;
  16424. }
  16425. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16426. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16427. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16428. }
  16429. }
  16430. };
  16431. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16432. return "FreeCameraKeyboardMoveInput";
  16433. };
  16434. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16435. this._keys = [];
  16436. };
  16437. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16438. return "keyboard";
  16439. };
  16440. return FreeCameraKeyboardMoveInput;
  16441. }());
  16442. __decorate([
  16443. BABYLON.serialize()
  16444. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16445. __decorate([
  16446. BABYLON.serialize()
  16447. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16448. __decorate([
  16449. BABYLON.serialize()
  16450. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16451. __decorate([
  16452. BABYLON.serialize()
  16453. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16454. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16455. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16456. })(BABYLON || (BABYLON = {}));
  16457. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16458. var BABYLON;
  16459. (function (BABYLON) {
  16460. var FreeCameraTouchInput = (function () {
  16461. function FreeCameraTouchInput() {
  16462. this._offsetX = null;
  16463. this._offsetY = null;
  16464. this._pointerCount = 0;
  16465. this._pointerPressed = [];
  16466. this.touchAngularSensibility = 200000.0;
  16467. this.touchMoveSensibility = 250.0;
  16468. }
  16469. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16470. var _this = this;
  16471. var previousPosition;
  16472. if (this._pointerInput === undefined) {
  16473. this._onLostFocus = function (evt) {
  16474. _this._offsetX = null;
  16475. _this._offsetY = null;
  16476. };
  16477. this._pointerInput = function (p, s) {
  16478. var evt = p.event;
  16479. if (evt.pointerType === "mouse") {
  16480. return;
  16481. }
  16482. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16483. if (!noPreventDefault) {
  16484. evt.preventDefault();
  16485. }
  16486. _this._pointerPressed.push(evt.pointerId);
  16487. if (_this._pointerPressed.length !== 1) {
  16488. return;
  16489. }
  16490. previousPosition = {
  16491. x: evt.clientX,
  16492. y: evt.clientY
  16493. };
  16494. }
  16495. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16496. if (!noPreventDefault) {
  16497. evt.preventDefault();
  16498. }
  16499. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16500. if (index === -1) {
  16501. return;
  16502. }
  16503. _this._pointerPressed.splice(index, 1);
  16504. if (index != 0) {
  16505. return;
  16506. }
  16507. previousPosition = null;
  16508. _this._offsetX = null;
  16509. _this._offsetY = null;
  16510. }
  16511. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16512. if (!noPreventDefault) {
  16513. evt.preventDefault();
  16514. }
  16515. if (!previousPosition) {
  16516. return;
  16517. }
  16518. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16519. if (index != 0) {
  16520. return;
  16521. }
  16522. _this._offsetX = evt.clientX - previousPosition.x;
  16523. _this._offsetY = -(evt.clientY - previousPosition.y);
  16524. }
  16525. };
  16526. }
  16527. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16528. element.addEventListener("blur", this._onLostFocus);
  16529. };
  16530. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16531. if (this._pointerInput && element) {
  16532. this.camera.getScene().onPointerObservable.remove(this._observer);
  16533. this._observer = null;
  16534. element.removeEventListener("blur", this._onLostFocus);
  16535. this._onLostFocus = null;
  16536. this._pointerPressed = [];
  16537. this._offsetX = null;
  16538. this._offsetY = null;
  16539. this._pointerCount = 0;
  16540. }
  16541. };
  16542. FreeCameraTouchInput.prototype.checkInputs = function () {
  16543. if (this._offsetX) {
  16544. var camera = this.camera;
  16545. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16546. if (this._pointerPressed.length > 1) {
  16547. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16548. }
  16549. else {
  16550. var speed = camera._computeLocalCameraSpeed();
  16551. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16552. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16553. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16554. }
  16555. }
  16556. };
  16557. FreeCameraTouchInput.prototype.getTypeName = function () {
  16558. return "FreeCameraTouchInput";
  16559. };
  16560. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16561. return "touch";
  16562. };
  16563. return FreeCameraTouchInput;
  16564. }());
  16565. __decorate([
  16566. BABYLON.serialize()
  16567. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16568. __decorate([
  16569. BABYLON.serialize()
  16570. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16571. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16572. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16573. })(BABYLON || (BABYLON = {}));
  16574. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16575. var BABYLON;
  16576. (function (BABYLON) {
  16577. var FreeCameraDeviceOrientationInput = (function () {
  16578. function FreeCameraDeviceOrientationInput() {
  16579. var _this = this;
  16580. this._screenOrientationAngle = 0;
  16581. this._screenQuaternion = new BABYLON.Quaternion();
  16582. this._alpha = 0;
  16583. this._beta = 0;
  16584. this._gamma = 0;
  16585. this._orientationChanged = function () {
  16586. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16587. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16588. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16589. };
  16590. this._deviceOrientation = function (evt) {
  16591. _this._alpha = evt.alpha;
  16592. _this._beta = evt.beta;
  16593. _this._gamma = evt.gamma;
  16594. };
  16595. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16596. this._orientationChanged();
  16597. }
  16598. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16599. get: function () {
  16600. return this._camera;
  16601. },
  16602. set: function (camera) {
  16603. this._camera = camera;
  16604. if (!this._camera.rotationQuaternion)
  16605. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16606. },
  16607. enumerable: true,
  16608. configurable: true
  16609. });
  16610. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16611. window.addEventListener("orientationchange", this._orientationChanged);
  16612. window.addEventListener("deviceorientation", this._deviceOrientation);
  16613. //In certain cases, the attach control is called AFTER orientation was changed,
  16614. //So this is needed.
  16615. this._orientationChanged();
  16616. };
  16617. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16618. window.removeEventListener("orientationchange", this._orientationChanged);
  16619. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16620. };
  16621. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16622. //if no device orientation provided, don't update the rotation.
  16623. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16624. if (!this._alpha)
  16625. return;
  16626. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16627. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16628. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16629. //Mirror on XY Plane
  16630. this._camera.rotationQuaternion.z *= -1;
  16631. this._camera.rotationQuaternion.w *= -1;
  16632. };
  16633. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16634. return "FreeCameraDeviceOrientationInput";
  16635. };
  16636. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16637. return "deviceOrientation";
  16638. };
  16639. return FreeCameraDeviceOrientationInput;
  16640. }());
  16641. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16642. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16643. })(BABYLON || (BABYLON = {}));
  16644. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16645. var BABYLON;
  16646. (function (BABYLON) {
  16647. var FreeCameraGamepadInput = (function () {
  16648. function FreeCameraGamepadInput() {
  16649. this.gamepadAngularSensibility = 200;
  16650. this.gamepadMoveSensibility = 40;
  16651. }
  16652. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16653. var _this = this;
  16654. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16655. };
  16656. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16657. if (this._gamepads) {
  16658. this._gamepads.dispose();
  16659. }
  16660. this.gamepad = null;
  16661. };
  16662. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16663. if (this.gamepad) {
  16664. var camera = this.camera;
  16665. var LSValues = this.gamepad.leftStick;
  16666. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16667. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16668. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16669. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16670. var RSValues = this.gamepad.rightStick;
  16671. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16672. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16673. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16674. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16675. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  16676. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16677. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  16678. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  16679. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  16680. }
  16681. };
  16682. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16683. // Only the first gamepad can control the camera
  16684. if (gamepad.index === 0) {
  16685. this.gamepad = gamepad;
  16686. }
  16687. };
  16688. FreeCameraGamepadInput.prototype.getTypeName = function () {
  16689. return "FreeCameraGamepadInput";
  16690. };
  16691. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  16692. return "gamepad";
  16693. };
  16694. return FreeCameraGamepadInput;
  16695. }());
  16696. __decorate([
  16697. BABYLON.serialize()
  16698. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  16699. __decorate([
  16700. BABYLON.serialize()
  16701. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  16702. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  16703. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  16704. })(BABYLON || (BABYLON = {}));
  16705. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  16706. var BABYLON;
  16707. (function (BABYLON) {
  16708. var ArcRotateCameraKeyboardMoveInput = (function () {
  16709. function ArcRotateCameraKeyboardMoveInput() {
  16710. this._keys = [];
  16711. this.keysUp = [38];
  16712. this.keysDown = [40];
  16713. this.keysLeft = [37];
  16714. this.keysRight = [39];
  16715. }
  16716. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16717. var _this = this;
  16718. element.tabIndex = 1;
  16719. this._onKeyDown = function (evt) {
  16720. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16721. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16722. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16723. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16724. var index = _this._keys.indexOf(evt.keyCode);
  16725. if (index === -1) {
  16726. _this._keys.push(evt.keyCode);
  16727. }
  16728. if (evt.preventDefault) {
  16729. if (!noPreventDefault) {
  16730. evt.preventDefault();
  16731. }
  16732. }
  16733. }
  16734. };
  16735. this._onKeyUp = function (evt) {
  16736. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16737. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16738. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16739. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16740. var index = _this._keys.indexOf(evt.keyCode);
  16741. if (index >= 0) {
  16742. _this._keys.splice(index, 1);
  16743. }
  16744. if (evt.preventDefault) {
  16745. if (!noPreventDefault) {
  16746. evt.preventDefault();
  16747. }
  16748. }
  16749. }
  16750. };
  16751. this._onLostFocus = function () {
  16752. _this._keys = [];
  16753. };
  16754. element.addEventListener("keydown", this._onKeyDown, false);
  16755. element.addEventListener("keyup", this._onKeyUp, false);
  16756. BABYLON.Tools.RegisterTopRootEvents([
  16757. { name: "blur", handler: this._onLostFocus }
  16758. ]);
  16759. };
  16760. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16761. if (element) {
  16762. element.removeEventListener("keydown", this._onKeyDown);
  16763. element.removeEventListener("keyup", this._onKeyUp);
  16764. }
  16765. BABYLON.Tools.UnregisterTopRootEvents([
  16766. { name: "blur", handler: this._onLostFocus }
  16767. ]);
  16768. this._keys = [];
  16769. this._onKeyDown = null;
  16770. this._onKeyUp = null;
  16771. this._onLostFocus = null;
  16772. };
  16773. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16774. if (this._onKeyDown) {
  16775. var camera = this.camera;
  16776. for (var index = 0; index < this._keys.length; index++) {
  16777. var keyCode = this._keys[index];
  16778. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16779. camera.inertialAlphaOffset -= 0.01;
  16780. }
  16781. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16782. camera.inertialBetaOffset -= 0.01;
  16783. }
  16784. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16785. camera.inertialAlphaOffset += 0.01;
  16786. }
  16787. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16788. camera.inertialBetaOffset += 0.01;
  16789. }
  16790. }
  16791. }
  16792. };
  16793. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16794. return "ArcRotateCameraKeyboardMoveInput";
  16795. };
  16796. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16797. return "keyboard";
  16798. };
  16799. return ArcRotateCameraKeyboardMoveInput;
  16800. }());
  16801. __decorate([
  16802. BABYLON.serialize()
  16803. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16804. __decorate([
  16805. BABYLON.serialize()
  16806. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16807. __decorate([
  16808. BABYLON.serialize()
  16809. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16810. __decorate([
  16811. BABYLON.serialize()
  16812. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16813. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  16814. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  16815. })(BABYLON || (BABYLON = {}));
  16816. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  16817. var BABYLON;
  16818. (function (BABYLON) {
  16819. var ArcRotateCameraMouseWheelInput = (function () {
  16820. function ArcRotateCameraMouseWheelInput() {
  16821. this.wheelPrecision = 3.0;
  16822. }
  16823. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  16824. var _this = this;
  16825. this._wheel = function (p, s) {
  16826. //sanity check - this should be a PointerWheel event.
  16827. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  16828. return;
  16829. var event = p.event;
  16830. var delta = 0;
  16831. if (event.wheelDelta) {
  16832. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  16833. }
  16834. else if (event.detail) {
  16835. delta = -event.detail / _this.wheelPrecision;
  16836. }
  16837. if (delta)
  16838. _this.camera.inertialRadiusOffset += delta;
  16839. if (event.preventDefault) {
  16840. if (!noPreventDefault) {
  16841. event.preventDefault();
  16842. }
  16843. }
  16844. };
  16845. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  16846. };
  16847. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  16848. if (this._observer && element) {
  16849. this.camera.getScene().onPointerObservable.remove(this._observer);
  16850. this._observer = null;
  16851. this._wheel = null;
  16852. }
  16853. };
  16854. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  16855. return "ArcRotateCameraMouseWheelInput";
  16856. };
  16857. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  16858. return "mousewheel";
  16859. };
  16860. return ArcRotateCameraMouseWheelInput;
  16861. }());
  16862. __decorate([
  16863. BABYLON.serialize()
  16864. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  16865. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  16866. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  16867. })(BABYLON || (BABYLON = {}));
  16868. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  16869. var BABYLON;
  16870. (function (BABYLON) {
  16871. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16872. var ArcRotateCameraPointersInput = (function () {
  16873. function ArcRotateCameraPointersInput() {
  16874. this.buttons = [0, 1, 2];
  16875. this.angularSensibilityX = 1000.0;
  16876. this.angularSensibilityY = 1000.0;
  16877. this.pinchPrecision = 6.0;
  16878. this.panningSensibility = 50.0;
  16879. this._isPanClick = false;
  16880. this.pinchInwards = true;
  16881. }
  16882. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  16883. var _this = this;
  16884. var engine = this.camera.getEngine();
  16885. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  16886. var pointA, pointB;
  16887. var previousPinchDistance = 0;
  16888. this._pointerInput = function (p, s) {
  16889. var evt = p.event;
  16890. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16891. return;
  16892. }
  16893. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16894. try {
  16895. evt.srcElement.setPointerCapture(evt.pointerId);
  16896. }
  16897. catch (e) {
  16898. }
  16899. // Manage panning with pan button click
  16900. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  16901. // manage pointers
  16902. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  16903. if (pointA === undefined) {
  16904. pointA = cacheSoloPointer;
  16905. }
  16906. else if (pointB === undefined) {
  16907. pointB = cacheSoloPointer;
  16908. }
  16909. if (!noPreventDefault) {
  16910. evt.preventDefault();
  16911. element.focus();
  16912. }
  16913. }
  16914. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16915. try {
  16916. evt.srcElement.releasePointerCapture(evt.pointerId);
  16917. }
  16918. catch (e) {
  16919. }
  16920. cacheSoloPointer = null;
  16921. previousPinchDistance = 0;
  16922. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  16923. //but emptying completly pointers collection is required to fix a bug on iPhone :
  16924. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  16925. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  16926. pointA = pointB = undefined;
  16927. if (!noPreventDefault) {
  16928. evt.preventDefault();
  16929. }
  16930. }
  16931. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16932. if (!noPreventDefault) {
  16933. evt.preventDefault();
  16934. }
  16935. // One button down
  16936. if (pointA && pointB === undefined) {
  16937. if (_this.panningSensibility !== 0 &&
  16938. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  16939. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  16940. _this.camera
  16941. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  16942. _this.camera
  16943. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  16944. }
  16945. else {
  16946. var offsetX = evt.clientX - cacheSoloPointer.x;
  16947. var offsetY = evt.clientY - cacheSoloPointer.y;
  16948. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  16949. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  16950. }
  16951. cacheSoloPointer.x = evt.clientX;
  16952. cacheSoloPointer.y = evt.clientY;
  16953. }
  16954. else if (pointA && pointB) {
  16955. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  16956. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  16957. ed.x = evt.clientX;
  16958. ed.y = evt.clientY;
  16959. var direction = _this.pinchInwards ? 1 : -1;
  16960. var distX = pointA.x - pointB.x;
  16961. var distY = pointA.y - pointB.y;
  16962. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  16963. if (previousPinchDistance === 0) {
  16964. previousPinchDistance = pinchSquaredDistance;
  16965. return;
  16966. }
  16967. if (pinchSquaredDistance !== previousPinchDistance) {
  16968. _this.camera
  16969. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  16970. (_this.pinchPrecision *
  16971. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  16972. direction);
  16973. previousPinchDistance = pinchSquaredDistance;
  16974. }
  16975. }
  16976. }
  16977. };
  16978. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16979. this._onContextMenu = function (evt) {
  16980. evt.preventDefault();
  16981. };
  16982. if (!this.camera._useCtrlForPanning) {
  16983. element.addEventListener("contextmenu", this._onContextMenu, false);
  16984. }
  16985. this._onLostFocus = function () {
  16986. //this._keys = [];
  16987. pointA = pointB = undefined;
  16988. previousPinchDistance = 0;
  16989. cacheSoloPointer = null;
  16990. };
  16991. this._onMouseMove = function (evt) {
  16992. if (!engine.isPointerLock) {
  16993. return;
  16994. }
  16995. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16996. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16997. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  16998. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  16999. if (!noPreventDefault) {
  17000. evt.preventDefault();
  17001. }
  17002. };
  17003. this._onGestureStart = function (e) {
  17004. if (window.MSGesture === undefined) {
  17005. return;
  17006. }
  17007. if (!_this._MSGestureHandler) {
  17008. _this._MSGestureHandler = new MSGesture();
  17009. _this._MSGestureHandler.target = element;
  17010. }
  17011. _this._MSGestureHandler.addPointer(e.pointerId);
  17012. };
  17013. this._onGesture = function (e) {
  17014. _this.camera.radius *= e.scale;
  17015. if (e.preventDefault) {
  17016. if (!noPreventDefault) {
  17017. e.stopPropagation();
  17018. e.preventDefault();
  17019. }
  17020. }
  17021. };
  17022. element.addEventListener("mousemove", this._onMouseMove, false);
  17023. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17024. element.addEventListener("MSGestureChange", this._onGesture, false);
  17025. element.addEventListener("keydown", this._onKeyDown, false);
  17026. element.addEventListener("keyup", this._onKeyUp, false);
  17027. BABYLON.Tools.RegisterTopRootEvents([
  17028. { name: "blur", handler: this._onLostFocus }
  17029. ]);
  17030. };
  17031. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17032. if (element && this._observer) {
  17033. this.camera.getScene().onPointerObservable.remove(this._observer);
  17034. this._observer = null;
  17035. element.removeEventListener("contextmenu", this._onContextMenu);
  17036. element.removeEventListener("mousemove", this._onMouseMove);
  17037. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17038. element.removeEventListener("MSGestureChange", this._onGesture);
  17039. element.removeEventListener("keydown", this._onKeyDown);
  17040. element.removeEventListener("keyup", this._onKeyUp);
  17041. this._isPanClick = false;
  17042. this.pinchInwards = true;
  17043. this._onKeyDown = null;
  17044. this._onKeyUp = null;
  17045. this._onMouseMove = null;
  17046. this._onGestureStart = null;
  17047. this._onGesture = null;
  17048. this._MSGestureHandler = null;
  17049. this._onLostFocus = null;
  17050. this._onContextMenu = null;
  17051. }
  17052. BABYLON.Tools.UnregisterTopRootEvents([
  17053. { name: "blur", handler: this._onLostFocus }
  17054. ]);
  17055. };
  17056. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17057. return "ArcRotateCameraPointersInput";
  17058. };
  17059. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17060. return "pointers";
  17061. };
  17062. return ArcRotateCameraPointersInput;
  17063. }());
  17064. __decorate([
  17065. BABYLON.serialize()
  17066. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17067. __decorate([
  17068. BABYLON.serialize()
  17069. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17070. __decorate([
  17071. BABYLON.serialize()
  17072. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17073. __decorate([
  17074. BABYLON.serialize()
  17075. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17076. __decorate([
  17077. BABYLON.serialize()
  17078. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17079. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17080. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17081. })(BABYLON || (BABYLON = {}));
  17082. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17083. var BABYLON;
  17084. (function (BABYLON) {
  17085. var ArcRotateCameraGamepadInput = (function () {
  17086. function ArcRotateCameraGamepadInput() {
  17087. this.gamepadRotationSensibility = 80;
  17088. this.gamepadMoveSensibility = 40;
  17089. }
  17090. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17091. var _this = this;
  17092. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17093. };
  17094. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17095. if (this._gamepads) {
  17096. this._gamepads.dispose();
  17097. }
  17098. this.gamepad = null;
  17099. };
  17100. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17101. if (this.gamepad) {
  17102. var camera = this.camera;
  17103. var RSValues = this.gamepad.rightStick;
  17104. if (RSValues.x != 0) {
  17105. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17106. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17107. camera.inertialAlphaOffset += normalizedRX;
  17108. }
  17109. }
  17110. if (RSValues.y != 0) {
  17111. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17112. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17113. camera.inertialBetaOffset += normalizedRY;
  17114. }
  17115. }
  17116. var LSValues = this.gamepad.leftStick;
  17117. if (LSValues.y != 0) {
  17118. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17119. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17120. this.camera.inertialRadiusOffset -= normalizedLY;
  17121. }
  17122. }
  17123. }
  17124. };
  17125. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17126. // Only the first gamepad can control the camera
  17127. if (gamepad.index === 0) {
  17128. this.gamepad = gamepad;
  17129. }
  17130. };
  17131. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17132. return "ArcRotateCameraGamepadInput";
  17133. };
  17134. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17135. return "gamepad";
  17136. };
  17137. return ArcRotateCameraGamepadInput;
  17138. }());
  17139. __decorate([
  17140. BABYLON.serialize()
  17141. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17142. __decorate([
  17143. BABYLON.serialize()
  17144. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17145. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17146. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17147. })(BABYLON || (BABYLON = {}));
  17148. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17149. var BABYLON;
  17150. (function (BABYLON) {
  17151. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17152. function ArcRotateCameraVRDeviceOrientationInput() {
  17153. this.alphaCorrection = 1;
  17154. this.betaCorrection = 1;
  17155. this.gammaCorrection = 1;
  17156. this._alpha = 0;
  17157. this._beta = 0;
  17158. this._gamma = 0;
  17159. this._dirty = false;
  17160. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17161. }
  17162. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17163. this.camera.attachControl(element, noPreventDefault);
  17164. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17165. };
  17166. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17167. var camera = this.camera;
  17168. this._alpha = +evt.alpha | 0;
  17169. this._beta = +evt.beta | 0;
  17170. this._gamma = +evt.gamma | 0;
  17171. this._dirty = true;
  17172. };
  17173. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17174. if (this._dirty) {
  17175. this._dirty = false;
  17176. if (this._gamma < 0) {
  17177. this._gamma = 180 + this._gamma;
  17178. }
  17179. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17180. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17181. }
  17182. };
  17183. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17184. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17185. };
  17186. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17187. return "ArcRotateCameraVRDeviceOrientationInput";
  17188. };
  17189. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17190. return "VRDeviceOrientation";
  17191. };
  17192. return ArcRotateCameraVRDeviceOrientationInput;
  17193. }());
  17194. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17195. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17196. })(BABYLON || (BABYLON = {}));
  17197. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17198. /// <reference path="babylon.camera.ts" />
  17199. var BABYLON;
  17200. (function (BABYLON) {
  17201. var TargetCamera = (function (_super) {
  17202. __extends(TargetCamera, _super);
  17203. function TargetCamera(name, position, scene) {
  17204. var _this = _super.call(this, name, position, scene) || this;
  17205. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17206. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17207. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17208. _this.speed = 2.0;
  17209. _this.noRotationConstraint = false;
  17210. _this.lockedTarget = null;
  17211. _this._currentTarget = BABYLON.Vector3.Zero();
  17212. _this._viewMatrix = BABYLON.Matrix.Zero();
  17213. _this._camMatrix = BABYLON.Matrix.Zero();
  17214. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17215. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17216. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17217. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17218. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17219. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17220. _this._tempMatrix = BABYLON.Matrix.Zero();
  17221. return _this;
  17222. }
  17223. TargetCamera.prototype.getFrontPosition = function (distance) {
  17224. var direction = this.getTarget().subtract(this.position);
  17225. direction.normalize();
  17226. direction.scaleInPlace(distance);
  17227. return this.globalPosition.add(direction);
  17228. };
  17229. TargetCamera.prototype._getLockedTargetPosition = function () {
  17230. if (!this.lockedTarget) {
  17231. return null;
  17232. }
  17233. if (this.lockedTarget.absolutePosition) {
  17234. this.lockedTarget.computeWorldMatrix();
  17235. }
  17236. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17237. };
  17238. // Cache
  17239. TargetCamera.prototype._initCache = function () {
  17240. _super.prototype._initCache.call(this);
  17241. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17242. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17243. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17244. };
  17245. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17246. if (!ignoreParentClass) {
  17247. _super.prototype._updateCache.call(this);
  17248. }
  17249. var lockedTargetPosition = this._getLockedTargetPosition();
  17250. if (!lockedTargetPosition) {
  17251. this._cache.lockedTarget = null;
  17252. }
  17253. else {
  17254. if (!this._cache.lockedTarget) {
  17255. this._cache.lockedTarget = lockedTargetPosition.clone();
  17256. }
  17257. else {
  17258. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17259. }
  17260. }
  17261. this._cache.rotation.copyFrom(this.rotation);
  17262. if (this.rotationQuaternion)
  17263. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17264. };
  17265. // Synchronized
  17266. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17267. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17268. return false;
  17269. }
  17270. var lockedTargetPosition = this._getLockedTargetPosition();
  17271. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17272. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17273. };
  17274. // Methods
  17275. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17276. var engine = this.getEngine();
  17277. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17278. };
  17279. // Target
  17280. TargetCamera.prototype.setTarget = function (target) {
  17281. this.upVector.normalize();
  17282. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17283. this._camMatrix.invert();
  17284. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17285. var vDir = target.subtract(this.position);
  17286. if (vDir.x >= 0.0) {
  17287. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17288. }
  17289. else {
  17290. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17291. }
  17292. this.rotation.z = 0;
  17293. if (isNaN(this.rotation.x)) {
  17294. this.rotation.x = 0;
  17295. }
  17296. if (isNaN(this.rotation.y)) {
  17297. this.rotation.y = 0;
  17298. }
  17299. if (isNaN(this.rotation.z)) {
  17300. this.rotation.z = 0;
  17301. }
  17302. if (this.rotationQuaternion) {
  17303. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17304. }
  17305. };
  17306. TargetCamera.prototype.getTarget = function () {
  17307. return this._currentTarget;
  17308. };
  17309. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17310. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17311. };
  17312. TargetCamera.prototype._updatePosition = function () {
  17313. this.position.addInPlace(this.cameraDirection);
  17314. };
  17315. TargetCamera.prototype._checkInputs = function () {
  17316. var needToMove = this._decideIfNeedsToMove();
  17317. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17318. // Move
  17319. if (needToMove) {
  17320. this._updatePosition();
  17321. }
  17322. // Rotate
  17323. if (needToRotate) {
  17324. this.rotation.x += this.cameraRotation.x;
  17325. this.rotation.y += this.cameraRotation.y;
  17326. if (!this.noRotationConstraint) {
  17327. var limit = (Math.PI / 2) * 0.95;
  17328. if (this.rotation.x > limit)
  17329. this.rotation.x = limit;
  17330. if (this.rotation.x < -limit)
  17331. this.rotation.x = -limit;
  17332. }
  17333. }
  17334. // Inertia
  17335. if (needToMove) {
  17336. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17337. this.cameraDirection.x = 0;
  17338. }
  17339. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17340. this.cameraDirection.y = 0;
  17341. }
  17342. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17343. this.cameraDirection.z = 0;
  17344. }
  17345. this.cameraDirection.scaleInPlace(this.inertia);
  17346. }
  17347. if (needToRotate) {
  17348. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17349. this.cameraRotation.x = 0;
  17350. }
  17351. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17352. this.cameraRotation.y = 0;
  17353. }
  17354. this.cameraRotation.scaleInPlace(this.inertia);
  17355. }
  17356. _super.prototype._checkInputs.call(this);
  17357. };
  17358. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17359. if (this.rotationQuaternion) {
  17360. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17361. //update the up vector!
  17362. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17363. }
  17364. else {
  17365. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17366. }
  17367. };
  17368. TargetCamera.prototype._getViewMatrix = function () {
  17369. if (!this.lockedTarget) {
  17370. // Compute
  17371. this._updateCameraRotationMatrix();
  17372. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17373. // Computing target and final matrix
  17374. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17375. }
  17376. else {
  17377. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17378. }
  17379. if (this.getScene().useRightHandedSystem) {
  17380. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17381. }
  17382. else {
  17383. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17384. }
  17385. return this._viewMatrix;
  17386. };
  17387. /**
  17388. * @override
  17389. * Override Camera.createRigCamera
  17390. */
  17391. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17392. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17393. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17394. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17395. if (!this.rotationQuaternion) {
  17396. this.rotationQuaternion = new BABYLON.Quaternion();
  17397. }
  17398. rigCamera._cameraRigParams = {};
  17399. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17400. }
  17401. return rigCamera;
  17402. }
  17403. return null;
  17404. };
  17405. /**
  17406. * @override
  17407. * Override Camera._updateRigCameras
  17408. */
  17409. TargetCamera.prototype._updateRigCameras = function () {
  17410. var camLeft = this._rigCameras[0];
  17411. var camRight = this._rigCameras[1];
  17412. switch (this.cameraRigMode) {
  17413. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17414. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17415. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17416. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17417. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17418. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17419. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17420. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17421. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17422. camLeft.setTarget(this.getTarget());
  17423. camRight.setTarget(this.getTarget());
  17424. break;
  17425. case BABYLON.Camera.RIG_MODE_VR:
  17426. case BABYLON.Camera.RIG_MODE_WEBVR:
  17427. if (camLeft.rotationQuaternion) {
  17428. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17429. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17430. }
  17431. else {
  17432. camLeft.rotation.copyFrom(this.rotation);
  17433. camRight.rotation.copyFrom(this.rotation);
  17434. }
  17435. camLeft.position.copyFrom(this.position);
  17436. camRight.position.copyFrom(this.position);
  17437. break;
  17438. }
  17439. _super.prototype._updateRigCameras.call(this);
  17440. };
  17441. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17442. if (!this._rigCamTransformMatrix) {
  17443. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17444. }
  17445. var target = this.getTarget();
  17446. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17447. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17448. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17449. };
  17450. TargetCamera.prototype.getClassName = function () {
  17451. return "TargetCamera";
  17452. };
  17453. return TargetCamera;
  17454. }(BABYLON.Camera));
  17455. __decorate([
  17456. BABYLON.serializeAsVector3()
  17457. ], TargetCamera.prototype, "rotation", void 0);
  17458. __decorate([
  17459. BABYLON.serialize()
  17460. ], TargetCamera.prototype, "speed", void 0);
  17461. __decorate([
  17462. BABYLON.serializeAsMeshReference("lockedTargetId")
  17463. ], TargetCamera.prototype, "lockedTarget", void 0);
  17464. BABYLON.TargetCamera = TargetCamera;
  17465. })(BABYLON || (BABYLON = {}));
  17466. //# sourceMappingURL=babylon.targetCamera.js.map
  17467. var BABYLON;
  17468. (function (BABYLON) {
  17469. var FreeCamera = (function (_super) {
  17470. __extends(FreeCamera, _super);
  17471. function FreeCamera(name, position, scene) {
  17472. var _this = _super.call(this, name, position, scene) || this;
  17473. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17474. _this.checkCollisions = false;
  17475. _this.applyGravity = false;
  17476. _this._collider = new BABYLON.Collider();
  17477. _this._needMoveForGravity = false;
  17478. _this._oldPosition = BABYLON.Vector3.Zero();
  17479. _this._diffPosition = BABYLON.Vector3.Zero();
  17480. _this._newPosition = BABYLON.Vector3.Zero();
  17481. // Collisions
  17482. _this._collisionMask = -1;
  17483. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17484. if (collidedMesh === void 0) { collidedMesh = null; }
  17485. //TODO move this to the collision coordinator!
  17486. if (_this.getScene().workerCollisions)
  17487. newPosition.multiplyInPlace(_this._collider.radius);
  17488. var updatePosition = function (newPos) {
  17489. _this._newPosition.copyFrom(newPos);
  17490. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17491. var oldPosition = _this.position.clone();
  17492. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17493. _this.position.addInPlace(_this._diffPosition);
  17494. if (_this.onCollide && collidedMesh) {
  17495. _this.onCollide(collidedMesh);
  17496. }
  17497. }
  17498. };
  17499. updatePosition(newPosition);
  17500. };
  17501. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17502. _this.inputs.addKeyboard().addMouse();
  17503. return _this;
  17504. }
  17505. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17506. //-- begin properties for backward compatibility for inputs
  17507. get: function () {
  17508. var mouse = this.inputs.attached["mouse"];
  17509. if (mouse)
  17510. return mouse.angularSensibility;
  17511. },
  17512. set: function (value) {
  17513. var mouse = this.inputs.attached["mouse"];
  17514. if (mouse)
  17515. mouse.angularSensibility = value;
  17516. },
  17517. enumerable: true,
  17518. configurable: true
  17519. });
  17520. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17521. get: function () {
  17522. var keyboard = this.inputs.attached["keyboard"];
  17523. if (keyboard)
  17524. return keyboard.keysUp;
  17525. },
  17526. set: function (value) {
  17527. var keyboard = this.inputs.attached["keyboard"];
  17528. if (keyboard)
  17529. keyboard.keysUp = value;
  17530. },
  17531. enumerable: true,
  17532. configurable: true
  17533. });
  17534. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17535. get: function () {
  17536. var keyboard = this.inputs.attached["keyboard"];
  17537. if (keyboard)
  17538. return keyboard.keysDown;
  17539. },
  17540. set: function (value) {
  17541. var keyboard = this.inputs.attached["keyboard"];
  17542. if (keyboard)
  17543. keyboard.keysDown = value;
  17544. },
  17545. enumerable: true,
  17546. configurable: true
  17547. });
  17548. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17549. get: function () {
  17550. var keyboard = this.inputs.attached["keyboard"];
  17551. if (keyboard)
  17552. return keyboard.keysLeft;
  17553. },
  17554. set: function (value) {
  17555. var keyboard = this.inputs.attached["keyboard"];
  17556. if (keyboard)
  17557. keyboard.keysLeft = value;
  17558. },
  17559. enumerable: true,
  17560. configurable: true
  17561. });
  17562. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17563. get: function () {
  17564. var keyboard = this.inputs.attached["keyboard"];
  17565. if (keyboard)
  17566. return keyboard.keysRight;
  17567. },
  17568. set: function (value) {
  17569. var keyboard = this.inputs.attached["keyboard"];
  17570. if (keyboard)
  17571. keyboard.keysRight = value;
  17572. },
  17573. enumerable: true,
  17574. configurable: true
  17575. });
  17576. // Controls
  17577. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17578. this.inputs.attachElement(element, noPreventDefault);
  17579. };
  17580. FreeCamera.prototype.detachControl = function (element) {
  17581. this.inputs.detachElement(element);
  17582. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17583. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17584. };
  17585. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17586. get: function () {
  17587. return this._collisionMask;
  17588. },
  17589. set: function (mask) {
  17590. this._collisionMask = !isNaN(mask) ? mask : -1;
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17596. var globalPosition;
  17597. if (this.parent) {
  17598. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17599. }
  17600. else {
  17601. globalPosition = this.position;
  17602. }
  17603. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17604. this._collider.radius = this.ellipsoid;
  17605. this._collider.collisionMask = this._collisionMask;
  17606. //no need for clone, as long as gravity is not on.
  17607. var actualVelocity = velocity;
  17608. //add gravity to the velocity to prevent the dual-collision checking
  17609. if (this.applyGravity) {
  17610. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17611. actualVelocity = velocity.add(this.getScene().gravity);
  17612. }
  17613. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17614. };
  17615. FreeCamera.prototype._checkInputs = function () {
  17616. if (!this._localDirection) {
  17617. this._localDirection = BABYLON.Vector3.Zero();
  17618. this._transformedDirection = BABYLON.Vector3.Zero();
  17619. }
  17620. this.inputs.checkInputs();
  17621. _super.prototype._checkInputs.call(this);
  17622. };
  17623. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17624. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17625. };
  17626. FreeCamera.prototype._updatePosition = function () {
  17627. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17628. this._collideWithWorld(this.cameraDirection);
  17629. }
  17630. else {
  17631. this.position.addInPlace(this.cameraDirection);
  17632. }
  17633. };
  17634. FreeCamera.prototype.dispose = function () {
  17635. this.inputs.clear();
  17636. _super.prototype.dispose.call(this);
  17637. };
  17638. FreeCamera.prototype.getClassName = function () {
  17639. return "FreeCamera";
  17640. };
  17641. return FreeCamera;
  17642. }(BABYLON.TargetCamera));
  17643. __decorate([
  17644. BABYLON.serializeAsVector3()
  17645. ], FreeCamera.prototype, "ellipsoid", void 0);
  17646. __decorate([
  17647. BABYLON.serialize()
  17648. ], FreeCamera.prototype, "checkCollisions", void 0);
  17649. __decorate([
  17650. BABYLON.serialize()
  17651. ], FreeCamera.prototype, "applyGravity", void 0);
  17652. BABYLON.FreeCamera = FreeCamera;
  17653. })(BABYLON || (BABYLON = {}));
  17654. //# sourceMappingURL=babylon.freeCamera.js.map
  17655. var BABYLON;
  17656. (function (BABYLON) {
  17657. var FreeCameraInputsManager = (function (_super) {
  17658. __extends(FreeCameraInputsManager, _super);
  17659. function FreeCameraInputsManager(camera) {
  17660. return _super.call(this, camera) || this;
  17661. }
  17662. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17663. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  17664. return this;
  17665. };
  17666. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  17667. if (touchEnabled === void 0) { touchEnabled = true; }
  17668. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  17669. return this;
  17670. };
  17671. FreeCameraInputsManager.prototype.addGamepad = function () {
  17672. this.add(new BABYLON.FreeCameraGamepadInput());
  17673. return this;
  17674. };
  17675. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  17676. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  17677. return this;
  17678. };
  17679. FreeCameraInputsManager.prototype.addTouch = function () {
  17680. this.add(new BABYLON.FreeCameraTouchInput());
  17681. return this;
  17682. };
  17683. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  17684. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  17685. return this;
  17686. };
  17687. return FreeCameraInputsManager;
  17688. }(BABYLON.CameraInputsManager));
  17689. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  17690. })(BABYLON || (BABYLON = {}));
  17691. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  17692. /// <reference path="babylon.targetCamera.ts" />
  17693. var BABYLON;
  17694. (function (BABYLON) {
  17695. var FollowCamera = (function (_super) {
  17696. __extends(FollowCamera, _super);
  17697. function FollowCamera(name, position, scene, lockedTarget) {
  17698. var _this = _super.call(this, name, position, scene) || this;
  17699. _this.radius = 12;
  17700. _this.rotationOffset = 0;
  17701. _this.heightOffset = 4;
  17702. _this.cameraAcceleration = 0.05;
  17703. _this.maxCameraSpeed = 20;
  17704. _this.lockedTarget = lockedTarget;
  17705. return _this;
  17706. }
  17707. FollowCamera.prototype.getRadians = function (degrees) {
  17708. return degrees * Math.PI / 180;
  17709. };
  17710. FollowCamera.prototype.follow = function (cameraTarget) {
  17711. if (!cameraTarget)
  17712. return;
  17713. var yRotation;
  17714. if (cameraTarget.rotationQuaternion) {
  17715. var rotMatrix = new BABYLON.Matrix();
  17716. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  17717. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  17718. }
  17719. else {
  17720. yRotation = cameraTarget.rotation.y;
  17721. }
  17722. var radians = this.getRadians(this.rotationOffset) + yRotation;
  17723. var targetPosition = cameraTarget.getAbsolutePosition();
  17724. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  17725. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  17726. var dx = targetX - this.position.x;
  17727. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  17728. var dz = (targetZ) - this.position.z;
  17729. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  17730. var vy = dy * this.cameraAcceleration;
  17731. var vz = dz * this.cameraAcceleration * 2;
  17732. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  17733. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17734. }
  17735. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  17736. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17737. }
  17738. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  17739. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17740. }
  17741. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  17742. this.setTarget(targetPosition);
  17743. };
  17744. FollowCamera.prototype._checkInputs = function () {
  17745. _super.prototype._checkInputs.call(this);
  17746. this.follow(this.lockedTarget);
  17747. };
  17748. FollowCamera.prototype.getClassName = function () {
  17749. return "FollowCamera";
  17750. };
  17751. return FollowCamera;
  17752. }(BABYLON.TargetCamera));
  17753. __decorate([
  17754. BABYLON.serialize()
  17755. ], FollowCamera.prototype, "radius", void 0);
  17756. __decorate([
  17757. BABYLON.serialize()
  17758. ], FollowCamera.prototype, "rotationOffset", void 0);
  17759. __decorate([
  17760. BABYLON.serialize()
  17761. ], FollowCamera.prototype, "heightOffset", void 0);
  17762. __decorate([
  17763. BABYLON.serialize()
  17764. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  17765. __decorate([
  17766. BABYLON.serialize()
  17767. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  17768. __decorate([
  17769. BABYLON.serializeAsMeshReference("lockedTargetId")
  17770. ], FollowCamera.prototype, "lockedTarget", void 0);
  17771. BABYLON.FollowCamera = FollowCamera;
  17772. var ArcFollowCamera = (function (_super) {
  17773. __extends(ArcFollowCamera, _super);
  17774. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  17775. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17776. _this.alpha = alpha;
  17777. _this.beta = beta;
  17778. _this.radius = radius;
  17779. _this.target = target;
  17780. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  17781. _this.follow();
  17782. return _this;
  17783. }
  17784. ArcFollowCamera.prototype.follow = function () {
  17785. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  17786. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  17787. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  17788. var targetPosition = this.target.getAbsolutePosition();
  17789. this.position = targetPosition.add(this._cartesianCoordinates);
  17790. this.setTarget(targetPosition);
  17791. };
  17792. ArcFollowCamera.prototype._checkInputs = function () {
  17793. _super.prototype._checkInputs.call(this);
  17794. this.follow();
  17795. };
  17796. ArcFollowCamera.prototype.getClassName = function () {
  17797. return "ArcFollowCamera";
  17798. };
  17799. return ArcFollowCamera;
  17800. }(BABYLON.TargetCamera));
  17801. BABYLON.ArcFollowCamera = ArcFollowCamera;
  17802. })(BABYLON || (BABYLON = {}));
  17803. //# sourceMappingURL=babylon.followCamera.js.map
  17804. /// <reference path="babylon.freeCamera.ts" />
  17805. var BABYLON;
  17806. (function (BABYLON) {
  17807. // We're mainly based on the logic defined into the FreeCamera code
  17808. var TouchCamera = (function (_super) {
  17809. __extends(TouchCamera, _super);
  17810. //-- end properties for backward compatibility for inputs
  17811. function TouchCamera(name, position, scene) {
  17812. var _this = _super.call(this, name, position, scene) || this;
  17813. _this.inputs.addTouch();
  17814. _this._setupInputs();
  17815. return _this;
  17816. }
  17817. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  17818. //-- Begin properties for backward compatibility for inputs
  17819. get: function () {
  17820. var touch = this.inputs.attached["touch"];
  17821. if (touch)
  17822. return touch.touchAngularSensibility;
  17823. },
  17824. set: function (value) {
  17825. var touch = this.inputs.attached["touch"];
  17826. if (touch)
  17827. touch.touchAngularSensibility = value;
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  17833. get: function () {
  17834. var touch = this.inputs.attached["touch"];
  17835. if (touch)
  17836. return touch.touchMoveSensibility;
  17837. },
  17838. set: function (value) {
  17839. var touch = this.inputs.attached["touch"];
  17840. if (touch)
  17841. touch.touchMoveSensibility = value;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. TouchCamera.prototype.getClassName = function () {
  17847. return "TouchCamera";
  17848. };
  17849. TouchCamera.prototype._setupInputs = function () {
  17850. var mouse = this.inputs.attached["mouse"];
  17851. if (mouse) {
  17852. mouse.touchEnabled = false;
  17853. }
  17854. };
  17855. return TouchCamera;
  17856. }(BABYLON.FreeCamera));
  17857. BABYLON.TouchCamera = TouchCamera;
  17858. })(BABYLON || (BABYLON = {}));
  17859. //# sourceMappingURL=babylon.touchCamera.js.map
  17860. /// <reference path="babylon.targetCamera.ts" />
  17861. /// <reference path="..\Tools\babylon.tools.ts" />
  17862. var BABYLON;
  17863. (function (BABYLON) {
  17864. var ArcRotateCamera = (function (_super) {
  17865. __extends(ArcRotateCamera, _super);
  17866. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  17867. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17868. _this.inertialAlphaOffset = 0;
  17869. _this.inertialBetaOffset = 0;
  17870. _this.inertialRadiusOffset = 0;
  17871. _this.lowerAlphaLimit = null;
  17872. _this.upperAlphaLimit = null;
  17873. _this.lowerBetaLimit = 0.01;
  17874. _this.upperBetaLimit = Math.PI;
  17875. _this.lowerRadiusLimit = null;
  17876. _this.upperRadiusLimit = null;
  17877. _this.inertialPanningX = 0;
  17878. _this.inertialPanningY = 0;
  17879. //-- end properties for backward compatibility for inputs
  17880. _this.zoomOnFactor = 1;
  17881. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  17882. _this.allowUpsideDown = true;
  17883. _this._viewMatrix = new BABYLON.Matrix();
  17884. // Panning
  17885. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  17886. _this.checkCollisions = false;
  17887. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  17888. _this._collider = new BABYLON.Collider();
  17889. _this._previousPosition = BABYLON.Vector3.Zero();
  17890. _this._collisionVelocity = BABYLON.Vector3.Zero();
  17891. _this._newPosition = BABYLON.Vector3.Zero();
  17892. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17893. if (collidedMesh === void 0) { collidedMesh = null; }
  17894. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  17895. newPosition.multiplyInPlace(_this._collider.radius);
  17896. }
  17897. if (!collidedMesh) {
  17898. _this._previousPosition.copyFrom(_this.position);
  17899. }
  17900. else {
  17901. _this.setPosition(newPosition);
  17902. if (_this.onCollide) {
  17903. _this.onCollide(collidedMesh);
  17904. }
  17905. }
  17906. // Recompute because of constraints
  17907. var cosa = Math.cos(_this.alpha);
  17908. var sina = Math.sin(_this.alpha);
  17909. var cosb = Math.cos(_this.beta);
  17910. var sinb = Math.sin(_this.beta);
  17911. if (sinb === 0) {
  17912. sinb = 0.0001;
  17913. }
  17914. var target = _this._getTargetPosition();
  17915. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  17916. _this.position.copyFrom(_this._newPosition);
  17917. var up = _this.upVector;
  17918. if (_this.allowUpsideDown && _this.beta < 0) {
  17919. up = up.clone();
  17920. up = up.negate();
  17921. }
  17922. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  17923. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  17924. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  17925. _this._collisionTriggered = false;
  17926. };
  17927. if (!target) {
  17928. _this.target = BABYLON.Vector3.Zero();
  17929. }
  17930. else {
  17931. _this.target = target;
  17932. }
  17933. _this.alpha = alpha;
  17934. _this.beta = beta;
  17935. _this.radius = radius;
  17936. _this.getViewMatrix();
  17937. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  17938. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  17939. return _this;
  17940. }
  17941. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  17942. //-- begin properties for backward compatibility for inputs
  17943. get: function () {
  17944. var pointers = this.inputs.attached["pointers"];
  17945. if (pointers)
  17946. return pointers.angularSensibilityX;
  17947. },
  17948. set: function (value) {
  17949. var pointers = this.inputs.attached["pointers"];
  17950. if (pointers) {
  17951. pointers.angularSensibilityX = value;
  17952. }
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  17958. get: function () {
  17959. var pointers = this.inputs.attached["pointers"];
  17960. if (pointers)
  17961. return pointers.angularSensibilityY;
  17962. },
  17963. set: function (value) {
  17964. var pointers = this.inputs.attached["pointers"];
  17965. if (pointers) {
  17966. pointers.angularSensibilityY = value;
  17967. }
  17968. },
  17969. enumerable: true,
  17970. configurable: true
  17971. });
  17972. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  17973. get: function () {
  17974. var pointers = this.inputs.attached["pointers"];
  17975. if (pointers)
  17976. return pointers.pinchPrecision;
  17977. },
  17978. set: function (value) {
  17979. var pointers = this.inputs.attached["pointers"];
  17980. if (pointers) {
  17981. pointers.pinchPrecision = value;
  17982. }
  17983. },
  17984. enumerable: true,
  17985. configurable: true
  17986. });
  17987. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  17988. get: function () {
  17989. var pointers = this.inputs.attached["pointers"];
  17990. if (pointers)
  17991. return pointers.panningSensibility;
  17992. },
  17993. set: function (value) {
  17994. var pointers = this.inputs.attached["pointers"];
  17995. if (pointers) {
  17996. pointers.panningSensibility = value;
  17997. }
  17998. },
  17999. enumerable: true,
  18000. configurable: true
  18001. });
  18002. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18003. get: function () {
  18004. var keyboard = this.inputs.attached["keyboard"];
  18005. if (keyboard)
  18006. return keyboard.keysUp;
  18007. },
  18008. set: function (value) {
  18009. var keyboard = this.inputs.attached["keyboard"];
  18010. if (keyboard)
  18011. keyboard.keysUp = value;
  18012. },
  18013. enumerable: true,
  18014. configurable: true
  18015. });
  18016. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18017. get: function () {
  18018. var keyboard = this.inputs.attached["keyboard"];
  18019. if (keyboard)
  18020. return keyboard.keysDown;
  18021. },
  18022. set: function (value) {
  18023. var keyboard = this.inputs.attached["keyboard"];
  18024. if (keyboard)
  18025. keyboard.keysDown = value;
  18026. },
  18027. enumerable: true,
  18028. configurable: true
  18029. });
  18030. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18031. get: function () {
  18032. var keyboard = this.inputs.attached["keyboard"];
  18033. if (keyboard)
  18034. return keyboard.keysLeft;
  18035. },
  18036. set: function (value) {
  18037. var keyboard = this.inputs.attached["keyboard"];
  18038. if (keyboard)
  18039. keyboard.keysLeft = value;
  18040. },
  18041. enumerable: true,
  18042. configurable: true
  18043. });
  18044. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18045. get: function () {
  18046. var keyboard = this.inputs.attached["keyboard"];
  18047. if (keyboard)
  18048. return keyboard.keysRight;
  18049. },
  18050. set: function (value) {
  18051. var keyboard = this.inputs.attached["keyboard"];
  18052. if (keyboard)
  18053. keyboard.keysRight = value;
  18054. },
  18055. enumerable: true,
  18056. configurable: true
  18057. });
  18058. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18059. get: function () {
  18060. var mousewheel = this.inputs.attached["mousewheel"];
  18061. if (mousewheel)
  18062. return mousewheel.wheelPrecision;
  18063. },
  18064. set: function (value) {
  18065. var mousewheel = this.inputs.attached["mousewheel"];
  18066. if (mousewheel)
  18067. mousewheel.wheelPrecision = value;
  18068. },
  18069. enumerable: true,
  18070. configurable: true
  18071. });
  18072. // Cache
  18073. ArcRotateCamera.prototype._initCache = function () {
  18074. _super.prototype._initCache.call(this);
  18075. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18076. this._cache.alpha = undefined;
  18077. this._cache.beta = undefined;
  18078. this._cache.radius = undefined;
  18079. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18080. };
  18081. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18082. if (!ignoreParentClass) {
  18083. _super.prototype._updateCache.call(this);
  18084. }
  18085. this._cache.target.copyFrom(this._getTargetPosition());
  18086. this._cache.alpha = this.alpha;
  18087. this._cache.beta = this.beta;
  18088. this._cache.radius = this.radius;
  18089. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18090. };
  18091. ArcRotateCamera.prototype._getTargetPosition = function () {
  18092. if (this.target.getAbsolutePosition) {
  18093. var pos = this.target.getAbsolutePosition();
  18094. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18095. }
  18096. return this.target;
  18097. };
  18098. // Synchronized
  18099. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18100. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18101. return false;
  18102. return this._cache.target.equals(this.target)
  18103. && this._cache.alpha === this.alpha
  18104. && this._cache.beta === this.beta
  18105. && this._cache.radius === this.radius
  18106. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18107. };
  18108. // Methods
  18109. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18110. var _this = this;
  18111. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18112. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18113. this._useCtrlForPanning = useCtrlForPanning;
  18114. this._panningMouseButton = panningMouseButton;
  18115. this.inputs.attachElement(element, noPreventDefault);
  18116. this._reset = function () {
  18117. _this.inertialAlphaOffset = 0;
  18118. _this.inertialBetaOffset = 0;
  18119. _this.inertialRadiusOffset = 0;
  18120. };
  18121. };
  18122. ArcRotateCamera.prototype.detachControl = function (element) {
  18123. this.inputs.detachElement(element);
  18124. if (this._reset) {
  18125. this._reset();
  18126. }
  18127. };
  18128. ArcRotateCamera.prototype._checkInputs = function () {
  18129. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18130. if (this._collisionTriggered) {
  18131. return;
  18132. }
  18133. this.inputs.checkInputs();
  18134. // Inertia
  18135. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18136. if (this.getScene().useRightHandedSystem) {
  18137. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18138. }
  18139. else {
  18140. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18141. }
  18142. this.beta += this.inertialBetaOffset;
  18143. this.radius -= this.inertialRadiusOffset;
  18144. this.inertialAlphaOffset *= this.inertia;
  18145. this.inertialBetaOffset *= this.inertia;
  18146. this.inertialRadiusOffset *= this.inertia;
  18147. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18148. this.inertialAlphaOffset = 0;
  18149. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18150. this.inertialBetaOffset = 0;
  18151. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18152. this.inertialRadiusOffset = 0;
  18153. }
  18154. // Panning inertia
  18155. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18156. if (!this._localDirection) {
  18157. this._localDirection = BABYLON.Vector3.Zero();
  18158. this._transformedDirection = BABYLON.Vector3.Zero();
  18159. }
  18160. this.inertialPanningX *= this.inertia;
  18161. this.inertialPanningY *= this.inertia;
  18162. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18163. this.inertialPanningX = 0;
  18164. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18165. this.inertialPanningY = 0;
  18166. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18167. this._localDirection.multiplyInPlace(this.panningAxis);
  18168. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18169. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18170. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18171. if (!this.panningAxis.y) {
  18172. this._transformedDirection.y = 0;
  18173. }
  18174. if (!this.target.getAbsolutePosition) {
  18175. this.target.addInPlace(this._transformedDirection);
  18176. }
  18177. }
  18178. // Limits
  18179. this._checkLimits();
  18180. _super.prototype._checkInputs.call(this);
  18181. };
  18182. ArcRotateCamera.prototype._checkLimits = function () {
  18183. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18184. if (this.allowUpsideDown && this.beta > Math.PI) {
  18185. this.beta = this.beta - (2 * Math.PI);
  18186. }
  18187. }
  18188. else {
  18189. if (this.beta < this.lowerBetaLimit) {
  18190. this.beta = this.lowerBetaLimit;
  18191. }
  18192. }
  18193. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18194. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18195. this.beta = this.beta + (2 * Math.PI);
  18196. }
  18197. }
  18198. else {
  18199. if (this.beta > this.upperBetaLimit) {
  18200. this.beta = this.upperBetaLimit;
  18201. }
  18202. }
  18203. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18204. this.alpha = this.lowerAlphaLimit;
  18205. }
  18206. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18207. this.alpha = this.upperAlphaLimit;
  18208. }
  18209. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18210. this.radius = this.lowerRadiusLimit;
  18211. }
  18212. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18213. this.radius = this.upperRadiusLimit;
  18214. }
  18215. };
  18216. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18217. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18218. this.radius = radiusv3.length();
  18219. // Alpha
  18220. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18221. if (radiusv3.z < 0) {
  18222. this.alpha = 2 * Math.PI - this.alpha;
  18223. }
  18224. // Beta
  18225. this.beta = Math.acos(radiusv3.y / this.radius);
  18226. this._checkLimits();
  18227. };
  18228. ArcRotateCamera.prototype.setPosition = function (position) {
  18229. if (this.position.equals(position)) {
  18230. return;
  18231. }
  18232. this.position.copyFrom(position);
  18233. this.rebuildAnglesAndRadius();
  18234. };
  18235. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18236. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18237. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18238. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18239. return;
  18240. }
  18241. if (toBoundingCenter && target.getBoundingInfo) {
  18242. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  18243. }
  18244. else {
  18245. this._targetBoundingCenter = null;
  18246. }
  18247. this.target = target;
  18248. this.rebuildAnglesAndRadius();
  18249. };
  18250. ArcRotateCamera.prototype._getViewMatrix = function () {
  18251. // Compute
  18252. var cosa = Math.cos(this.alpha);
  18253. var sina = Math.sin(this.alpha);
  18254. var cosb = Math.cos(this.beta);
  18255. var sinb = Math.sin(this.beta);
  18256. if (sinb === 0) {
  18257. sinb = 0.0001;
  18258. }
  18259. var target = this._getTargetPosition();
  18260. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18261. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18262. this._collider.radius = this.collisionRadius;
  18263. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18264. this._collisionTriggered = true;
  18265. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18266. }
  18267. else {
  18268. this.position.copyFrom(this._newPosition);
  18269. var up = this.upVector;
  18270. if (this.allowUpsideDown && this.beta < 0) {
  18271. up = up.clone();
  18272. up = up.negate();
  18273. }
  18274. if (this.getScene().useRightHandedSystem) {
  18275. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18276. }
  18277. else {
  18278. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18279. }
  18280. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18281. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18282. }
  18283. this._currentTarget = target;
  18284. return this._viewMatrix;
  18285. };
  18286. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18287. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18288. meshes = meshes || this.getScene().meshes;
  18289. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18290. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18291. this.radius = distance * this.zoomOnFactor;
  18292. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18293. };
  18294. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18295. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18296. var meshesOrMinMaxVector;
  18297. var distance;
  18298. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18299. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18300. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18301. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18302. }
  18303. else {
  18304. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18305. distance = meshesOrMinMaxVectorAndDistance.distance;
  18306. }
  18307. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18308. if (!doNotUpdateMaxZ) {
  18309. this.maxZ = distance * 2;
  18310. }
  18311. };
  18312. /**
  18313. * @override
  18314. * Override Camera.createRigCamera
  18315. */
  18316. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18317. var alphaShift;
  18318. switch (this.cameraRigMode) {
  18319. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18320. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18321. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18322. case BABYLON.Camera.RIG_MODE_VR:
  18323. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18324. break;
  18325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18326. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18327. break;
  18328. }
  18329. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18330. rigCam._cameraRigParams = {};
  18331. return rigCam;
  18332. };
  18333. /**
  18334. * @override
  18335. * Override Camera._updateRigCameras
  18336. */
  18337. ArcRotateCamera.prototype._updateRigCameras = function () {
  18338. var camLeft = this._rigCameras[0];
  18339. var camRight = this._rigCameras[1];
  18340. camLeft.beta = camRight.beta = this.beta;
  18341. camLeft.radius = camRight.radius = this.radius;
  18342. switch (this.cameraRigMode) {
  18343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18346. case BABYLON.Camera.RIG_MODE_VR:
  18347. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18348. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18349. break;
  18350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18351. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18352. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18353. break;
  18354. }
  18355. _super.prototype._updateRigCameras.call(this);
  18356. };
  18357. ArcRotateCamera.prototype.dispose = function () {
  18358. this.inputs.clear();
  18359. _super.prototype.dispose.call(this);
  18360. };
  18361. ArcRotateCamera.prototype.getClassName = function () {
  18362. return "ArcRotateCamera";
  18363. };
  18364. return ArcRotateCamera;
  18365. }(BABYLON.TargetCamera));
  18366. __decorate([
  18367. BABYLON.serialize()
  18368. ], ArcRotateCamera.prototype, "alpha", void 0);
  18369. __decorate([
  18370. BABYLON.serialize()
  18371. ], ArcRotateCamera.prototype, "beta", void 0);
  18372. __decorate([
  18373. BABYLON.serialize()
  18374. ], ArcRotateCamera.prototype, "radius", void 0);
  18375. __decorate([
  18376. BABYLON.serializeAsVector3()
  18377. ], ArcRotateCamera.prototype, "target", void 0);
  18378. __decorate([
  18379. BABYLON.serialize()
  18380. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18381. __decorate([
  18382. BABYLON.serialize()
  18383. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18384. __decorate([
  18385. BABYLON.serialize()
  18386. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18387. __decorate([
  18388. BABYLON.serialize()
  18389. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18390. __decorate([
  18391. BABYLON.serialize()
  18392. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18393. __decorate([
  18394. BABYLON.serialize()
  18395. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18396. __decorate([
  18397. BABYLON.serialize()
  18398. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18399. __decorate([
  18400. BABYLON.serialize()
  18401. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18402. __decorate([
  18403. BABYLON.serialize()
  18404. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18405. __decorate([
  18406. BABYLON.serialize()
  18407. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18408. __decorate([
  18409. BABYLON.serialize()
  18410. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18411. __decorate([
  18412. BABYLON.serialize()
  18413. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18414. __decorate([
  18415. BABYLON.serialize()
  18416. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18417. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18418. })(BABYLON || (BABYLON = {}));
  18419. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18420. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18421. var BABYLON;
  18422. (function (BABYLON) {
  18423. var ArcRotateCameraInputsManager = (function (_super) {
  18424. __extends(ArcRotateCameraInputsManager, _super);
  18425. function ArcRotateCameraInputsManager(camera) {
  18426. return _super.call(this, camera) || this;
  18427. }
  18428. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18429. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18430. return this;
  18431. };
  18432. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18433. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18434. return this;
  18435. };
  18436. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18437. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18438. return this;
  18439. };
  18440. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18441. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18442. return this;
  18443. };
  18444. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18445. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18446. return this;
  18447. };
  18448. return ArcRotateCameraInputsManager;
  18449. }(BABYLON.CameraInputsManager));
  18450. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18451. })(BABYLON || (BABYLON = {}));
  18452. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18453. var BABYLON;
  18454. (function (BABYLON) {
  18455. var RenderingManager = (function () {
  18456. function RenderingManager(scene) {
  18457. this._renderingGroups = new Array();
  18458. this._autoClearDepthStencil = {};
  18459. this._customOpaqueSortCompareFn = {};
  18460. this._customAlphaTestSortCompareFn = {};
  18461. this._customTransparentSortCompareFn = {};
  18462. this._renderinGroupInfo = null;
  18463. this._scene = scene;
  18464. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18465. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18466. }
  18467. }
  18468. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18469. if (depth === void 0) { depth = true; }
  18470. if (stencil === void 0) { stencil = true; }
  18471. if (this._depthStencilBufferAlreadyCleaned) {
  18472. return;
  18473. }
  18474. this._scene.getEngine().clear(null, false, depth, stencil);
  18475. this._depthStencilBufferAlreadyCleaned = true;
  18476. };
  18477. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18478. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18479. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18480. var info = null;
  18481. if (observable) {
  18482. if (!this._renderinGroupInfo) {
  18483. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18484. }
  18485. info = this._renderinGroupInfo;
  18486. info.scene = this._scene;
  18487. info.camera = this._scene.activeCamera;
  18488. }
  18489. // Dispatch sprites
  18490. if (renderSprites) {
  18491. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18492. var manager = this._scene.spriteManagers[index];
  18493. this.dispatchSprites(manager);
  18494. }
  18495. }
  18496. // Render
  18497. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18498. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18499. var renderingGroup = this._renderingGroups[index];
  18500. if (!renderingGroup && !observable)
  18501. continue;
  18502. this._currentIndex = index;
  18503. var renderingGroupMask = 0;
  18504. // Fire PRECLEAR stage
  18505. if (observable) {
  18506. renderingGroupMask = Math.pow(2, index);
  18507. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18508. info.renderingGroupId = index;
  18509. observable.notifyObservers(info, renderingGroupMask);
  18510. }
  18511. // Clear depth/stencil if needed
  18512. var autoClear = this._autoClearDepthStencil[index];
  18513. if (autoClear && autoClear.autoClear) {
  18514. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18515. }
  18516. if (observable) {
  18517. // Fire PREOPAQUE stage
  18518. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18519. observable.notifyObservers(info, renderingGroupMask);
  18520. // Fire PRETRANSPARENT stage
  18521. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18522. observable.notifyObservers(info, renderingGroupMask);
  18523. }
  18524. if (renderingGroup)
  18525. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18526. // Fire POSTTRANSPARENT stage
  18527. if (observable) {
  18528. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18529. observable.notifyObservers(info, renderingGroupMask);
  18530. }
  18531. }
  18532. };
  18533. RenderingManager.prototype.reset = function () {
  18534. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18535. var renderingGroup = this._renderingGroups[index];
  18536. if (renderingGroup) {
  18537. renderingGroup.prepare();
  18538. }
  18539. }
  18540. };
  18541. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18542. if (!this._renderingGroups[renderingGroupId]) {
  18543. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18544. }
  18545. };
  18546. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18547. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18548. this._prepareRenderingGroup(renderingGroupId);
  18549. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18550. };
  18551. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18552. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18553. this._prepareRenderingGroup(renderingGroupId);
  18554. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18555. };
  18556. RenderingManager.prototype.dispatch = function (subMesh) {
  18557. var mesh = subMesh.getMesh();
  18558. var renderingGroupId = mesh.renderingGroupId || 0;
  18559. this._prepareRenderingGroup(renderingGroupId);
  18560. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18561. };
  18562. /**
  18563. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18564. * This allowed control for front to back rendering or reversly depending of the special needs.
  18565. *
  18566. * @param renderingGroupId The rendering group id corresponding to its index
  18567. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18568. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18569. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18570. */
  18571. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18572. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18573. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18574. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18575. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18576. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18577. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18578. if (this._renderingGroups[renderingGroupId]) {
  18579. var group = this._renderingGroups[renderingGroupId];
  18580. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18581. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18582. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18583. }
  18584. };
  18585. /**
  18586. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18587. *
  18588. * @param renderingGroupId The rendering group id corresponding to its index
  18589. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18590. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18591. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18592. */
  18593. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18594. if (depth === void 0) { depth = true; }
  18595. if (stencil === void 0) { stencil = true; }
  18596. this._autoClearDepthStencil[renderingGroupId] = {
  18597. autoClear: autoClearDepthStencil,
  18598. depth: depth,
  18599. stencil: stencil
  18600. };
  18601. };
  18602. return RenderingManager;
  18603. }());
  18604. /**
  18605. * The max id used for rendering groups (not included)
  18606. */
  18607. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18608. /**
  18609. * The min id used for rendering groups (included)
  18610. */
  18611. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18612. BABYLON.RenderingManager = RenderingManager;
  18613. })(BABYLON || (BABYLON = {}));
  18614. //# sourceMappingURL=babylon.renderingManager.js.map
  18615. var BABYLON;
  18616. (function (BABYLON) {
  18617. var RenderingGroup = (function () {
  18618. /**
  18619. * Creates a new rendering group.
  18620. * @param index The rendering group index
  18621. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18622. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18623. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18624. */
  18625. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18626. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18627. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18628. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18629. this.index = index;
  18630. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18631. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18632. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18633. this._particleSystems = new BABYLON.SmartArray(256);
  18634. this._spriteManagers = new BABYLON.SmartArray(256);
  18635. this._scene = scene;
  18636. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18637. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18638. this.transparentSortCompareFn = transparentSortCompareFn;
  18639. }
  18640. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18641. /**
  18642. * Set the opaque sort comparison function.
  18643. * If null the sub meshes will be render in the order they were created
  18644. */
  18645. set: function (value) {
  18646. this._opaqueSortCompareFn = value;
  18647. if (value) {
  18648. this._renderOpaque = this.renderOpaqueSorted;
  18649. }
  18650. else {
  18651. this._renderOpaque = RenderingGroup.renderUnsorted;
  18652. }
  18653. },
  18654. enumerable: true,
  18655. configurable: true
  18656. });
  18657. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18658. /**
  18659. * Set the alpha test sort comparison function.
  18660. * If null the sub meshes will be render in the order they were created
  18661. */
  18662. set: function (value) {
  18663. this._alphaTestSortCompareFn = value;
  18664. if (value) {
  18665. this._renderAlphaTest = this.renderAlphaTestSorted;
  18666. }
  18667. else {
  18668. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18669. }
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18675. /**
  18676. * Set the transparent sort comparison function.
  18677. * If null the sub meshes will be render in the order they were created
  18678. */
  18679. set: function (value) {
  18680. if (value) {
  18681. this._transparentSortCompareFn = value;
  18682. }
  18683. else {
  18684. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18685. }
  18686. this._renderTransparent = this.renderTransparentSorted;
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. /**
  18692. * Render all the sub meshes contained in the group.
  18693. * @param customRenderFunction Used to override the default render behaviour of the group.
  18694. * @returns true if rendered some submeshes.
  18695. */
  18696. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18697. if (customRenderFunction) {
  18698. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  18699. return;
  18700. }
  18701. var engine = this._scene.getEngine();
  18702. // Opaque
  18703. if (this._opaqueSubMeshes.length !== 0) {
  18704. this._renderOpaque(this._opaqueSubMeshes);
  18705. }
  18706. // Alpha test
  18707. if (this._alphaTestSubMeshes.length !== 0) {
  18708. engine.setAlphaTesting(true);
  18709. this._renderAlphaTest(this._alphaTestSubMeshes);
  18710. engine.setAlphaTesting(false);
  18711. }
  18712. // Sprites
  18713. if (renderSprites) {
  18714. this._renderSprites();
  18715. }
  18716. // Particles
  18717. if (renderParticles) {
  18718. this._renderParticles(activeMeshes);
  18719. }
  18720. if (this.onBeforeTransparentRendering) {
  18721. this.onBeforeTransparentRendering();
  18722. }
  18723. // Transparent
  18724. if (this._transparentSubMeshes.length !== 0) {
  18725. this._renderTransparent(this._transparentSubMeshes);
  18726. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18727. }
  18728. };
  18729. /**
  18730. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18731. * @param subMeshes The submeshes to render
  18732. */
  18733. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18734. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18735. };
  18736. /**
  18737. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18738. * @param subMeshes The submeshes to render
  18739. */
  18740. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18741. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18742. };
  18743. /**
  18744. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18745. * @param subMeshes The submeshes to render
  18746. */
  18747. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18748. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  18749. };
  18750. /**
  18751. * Renders the submeshes in a specified order.
  18752. * @param subMeshes The submeshes to sort before render
  18753. * @param sortCompareFn The comparison function use to sort
  18754. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18755. * @param transparent Specifies to activate blending if true
  18756. */
  18757. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  18758. var subIndex = 0;
  18759. var subMesh;
  18760. for (; subIndex < subMeshes.length; subIndex++) {
  18761. subMesh = subMeshes.data[subIndex];
  18762. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18763. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18764. }
  18765. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18766. sortedArray.sort(sortCompareFn);
  18767. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18768. subMesh = sortedArray[subIndex];
  18769. subMesh.render(transparent);
  18770. }
  18771. };
  18772. /**
  18773. * Renders the submeshes in the order they were dispatched (no sort applied).
  18774. * @param subMeshes The submeshes to render
  18775. */
  18776. RenderingGroup.renderUnsorted = function (subMeshes) {
  18777. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18778. var submesh = subMeshes.data[subIndex];
  18779. submesh.render(false);
  18780. }
  18781. };
  18782. /**
  18783. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18784. * are rendered back to front if in the same alpha index.
  18785. *
  18786. * @param a The first submesh
  18787. * @param b The second submesh
  18788. * @returns The result of the comparison
  18789. */
  18790. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18791. // Alpha index first
  18792. if (a._alphaIndex > b._alphaIndex) {
  18793. return 1;
  18794. }
  18795. if (a._alphaIndex < b._alphaIndex) {
  18796. return -1;
  18797. }
  18798. // Then distance to camera
  18799. return RenderingGroup.backToFrontSortCompare(a, b);
  18800. };
  18801. /**
  18802. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18803. * are rendered back to front.
  18804. *
  18805. * @param a The first submesh
  18806. * @param b The second submesh
  18807. * @returns The result of the comparison
  18808. */
  18809. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18810. // Then distance to camera
  18811. if (a._distanceToCamera < b._distanceToCamera) {
  18812. return 1;
  18813. }
  18814. if (a._distanceToCamera > b._distanceToCamera) {
  18815. return -1;
  18816. }
  18817. return 0;
  18818. };
  18819. /**
  18820. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18821. * are rendered front to back (prevent overdraw).
  18822. *
  18823. * @param a The first submesh
  18824. * @param b The second submesh
  18825. * @returns The result of the comparison
  18826. */
  18827. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18828. // Then distance to camera
  18829. if (a._distanceToCamera < b._distanceToCamera) {
  18830. return -1;
  18831. }
  18832. if (a._distanceToCamera > b._distanceToCamera) {
  18833. return 1;
  18834. }
  18835. return 0;
  18836. };
  18837. /**
  18838. * Resets the different lists of submeshes to prepare a new frame.
  18839. */
  18840. RenderingGroup.prototype.prepare = function () {
  18841. this._opaqueSubMeshes.reset();
  18842. this._transparentSubMeshes.reset();
  18843. this._alphaTestSubMeshes.reset();
  18844. this._particleSystems.reset();
  18845. this._spriteManagers.reset();
  18846. };
  18847. /**
  18848. * Inserts the submesh in its correct queue depending on its material.
  18849. * @param subMesh The submesh to dispatch
  18850. */
  18851. RenderingGroup.prototype.dispatch = function (subMesh) {
  18852. var material = subMesh.getMaterial();
  18853. var mesh = subMesh.getMesh();
  18854. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  18855. this._transparentSubMeshes.push(subMesh);
  18856. }
  18857. else if (material.needAlphaTesting()) {
  18858. this._alphaTestSubMeshes.push(subMesh);
  18859. }
  18860. else {
  18861. this._opaqueSubMeshes.push(subMesh); // Opaque
  18862. }
  18863. };
  18864. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18865. this._spriteManagers.push(spriteManager);
  18866. };
  18867. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18868. this._particleSystems.push(particleSystem);
  18869. };
  18870. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18871. if (this._particleSystems.length === 0) {
  18872. return;
  18873. }
  18874. // Particles
  18875. var activeCamera = this._scene.activeCamera;
  18876. this._scene._particlesDuration.beginMonitoring();
  18877. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18878. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18879. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18880. continue;
  18881. }
  18882. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  18883. this._scene._activeParticles.addCount(particleSystem.render(), false);
  18884. }
  18885. }
  18886. this._scene._particlesDuration.endMonitoring(false);
  18887. };
  18888. RenderingGroup.prototype._renderSprites = function () {
  18889. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  18890. return;
  18891. }
  18892. // Sprites
  18893. var activeCamera = this._scene.activeCamera;
  18894. this._scene._spritesDuration.beginMonitoring();
  18895. for (var id = 0; id < this._spriteManagers.length; id++) {
  18896. var spriteManager = this._spriteManagers.data[id];
  18897. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  18898. spriteManager.render();
  18899. }
  18900. }
  18901. this._scene._spritesDuration.endMonitoring(false);
  18902. };
  18903. return RenderingGroup;
  18904. }());
  18905. BABYLON.RenderingGroup = RenderingGroup;
  18906. })(BABYLON || (BABYLON = {}));
  18907. //# sourceMappingURL=babylon.renderingGroup.js.map
  18908. var BABYLON;
  18909. (function (BABYLON) {
  18910. var PointerEventTypes = (function () {
  18911. function PointerEventTypes() {
  18912. }
  18913. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  18914. get: function () {
  18915. return PointerEventTypes._POINTERDOWN;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  18921. get: function () {
  18922. return PointerEventTypes._POINTERUP;
  18923. },
  18924. enumerable: true,
  18925. configurable: true
  18926. });
  18927. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  18928. get: function () {
  18929. return PointerEventTypes._POINTERMOVE;
  18930. },
  18931. enumerable: true,
  18932. configurable: true
  18933. });
  18934. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  18935. get: function () {
  18936. return PointerEventTypes._POINTERWHEEL;
  18937. },
  18938. enumerable: true,
  18939. configurable: true
  18940. });
  18941. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  18942. get: function () {
  18943. return PointerEventTypes._POINTERPICK;
  18944. },
  18945. enumerable: true,
  18946. configurable: true
  18947. });
  18948. return PointerEventTypes;
  18949. }());
  18950. PointerEventTypes._POINTERDOWN = 0x01;
  18951. PointerEventTypes._POINTERUP = 0x02;
  18952. PointerEventTypes._POINTERMOVE = 0x04;
  18953. PointerEventTypes._POINTERWHEEL = 0x08;
  18954. PointerEventTypes._POINTERPICK = 0x10;
  18955. BABYLON.PointerEventTypes = PointerEventTypes;
  18956. var PointerInfoBase = (function () {
  18957. function PointerInfoBase(type, event) {
  18958. this.type = type;
  18959. this.event = event;
  18960. }
  18961. return PointerInfoBase;
  18962. }());
  18963. BABYLON.PointerInfoBase = PointerInfoBase;
  18964. /**
  18965. * This class is used to store pointer related info for the onPrePointerObservable event.
  18966. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  18967. */
  18968. var PointerInfoPre = (function (_super) {
  18969. __extends(PointerInfoPre, _super);
  18970. function PointerInfoPre(type, event, localX, localY) {
  18971. var _this = _super.call(this, type, event) || this;
  18972. _this.skipOnPointerObservable = false;
  18973. _this.localPosition = new BABYLON.Vector2(localX, localY);
  18974. return _this;
  18975. }
  18976. return PointerInfoPre;
  18977. }(PointerInfoBase));
  18978. BABYLON.PointerInfoPre = PointerInfoPre;
  18979. /**
  18980. * This type contains all the data related to a pointer event in Babylon.js.
  18981. * 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.
  18982. */
  18983. var PointerInfo = (function (_super) {
  18984. __extends(PointerInfo, _super);
  18985. function PointerInfo(type, event, pickInfo) {
  18986. var _this = _super.call(this, type, event) || this;
  18987. _this.pickInfo = pickInfo;
  18988. return _this;
  18989. }
  18990. return PointerInfo;
  18991. }(PointerInfoBase));
  18992. BABYLON.PointerInfo = PointerInfo;
  18993. /**
  18994. * This class is used by the onRenderingGroupObservable
  18995. */
  18996. var RenderingGroupInfo = (function () {
  18997. function RenderingGroupInfo() {
  18998. }
  18999. return RenderingGroupInfo;
  19000. }());
  19001. /**
  19002. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19003. * This stage will be fired no matter what
  19004. */
  19005. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19006. /**
  19007. * Called before opaque object are rendered.
  19008. * This stage will be fired only if there's 3D Opaque content to render
  19009. */
  19010. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19011. /**
  19012. * Called after the opaque objects are rendered and before the transparent ones
  19013. * This stage will be fired only if there's 3D transparent content to render
  19014. */
  19015. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19016. /**
  19017. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19018. * This stage will be fired no matter what
  19019. */
  19020. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19021. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19022. /**
  19023. * Represents a scene to be rendered by the engine.
  19024. * @see http://doc.babylonjs.com/page.php?p=21911
  19025. */
  19026. var Scene = (function () {
  19027. /**
  19028. * @constructor
  19029. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19030. */
  19031. function Scene(engine) {
  19032. // Members
  19033. this.autoClear = true;
  19034. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19035. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19036. this.forceWireframe = false;
  19037. this.forcePointsCloud = false;
  19038. this.forceShowBoundingBoxes = false;
  19039. this.animationsEnabled = true;
  19040. this.constantlyUpdateMeshUnderPointer = false;
  19041. this.useRightHandedSystem = false;
  19042. this.hoverCursor = "pointer";
  19043. // Metadata
  19044. this.metadata = null;
  19045. // Events
  19046. /**
  19047. * An event triggered when the scene is disposed.
  19048. * @type {BABYLON.Observable}
  19049. */
  19050. this.onDisposeObservable = new BABYLON.Observable();
  19051. /**
  19052. * An event triggered before rendering the scene
  19053. * @type {BABYLON.Observable}
  19054. */
  19055. this.onBeforeRenderObservable = new BABYLON.Observable();
  19056. /**
  19057. * An event triggered after rendering the scene
  19058. * @type {BABYLON.Observable}
  19059. */
  19060. this.onAfterRenderObservable = new BABYLON.Observable();
  19061. /**
  19062. * An event triggered when the scene is ready
  19063. * @type {BABYLON.Observable}
  19064. */
  19065. this.onReadyObservable = new BABYLON.Observable();
  19066. /**
  19067. * An event triggered before rendering a camera
  19068. * @type {BABYLON.Observable}
  19069. */
  19070. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19071. /**
  19072. * An event triggered after rendering a camera
  19073. * @type {BABYLON.Observable}
  19074. */
  19075. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19076. /**
  19077. * An event triggered when a camera is created
  19078. * @type {BABYLON.Observable}
  19079. */
  19080. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19081. /**
  19082. * An event triggered when a camera is removed
  19083. * @type {BABYLON.Observable}
  19084. */
  19085. this.onCameraRemovedObservable = new BABYLON.Observable();
  19086. /**
  19087. * An event triggered when a light is created
  19088. * @type {BABYLON.Observable}
  19089. */
  19090. this.onNewLightAddedObservable = new BABYLON.Observable();
  19091. /**
  19092. * An event triggered when a light is removed
  19093. * @type {BABYLON.Observable}
  19094. */
  19095. this.onLightRemovedObservable = new BABYLON.Observable();
  19096. /**
  19097. * An event triggered when a geometry is created
  19098. * @type {BABYLON.Observable}
  19099. */
  19100. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19101. /**
  19102. * An event triggered when a geometry is removed
  19103. * @type {BABYLON.Observable}
  19104. */
  19105. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19106. /**
  19107. * An event triggered when a mesh is created
  19108. * @type {BABYLON.Observable}
  19109. */
  19110. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19111. /**
  19112. * An event triggered when a mesh is removed
  19113. * @type {BABYLON.Observable}
  19114. */
  19115. this.onMeshRemovedObservable = new BABYLON.Observable();
  19116. /**
  19117. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19118. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19119. * 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)
  19120. */
  19121. this.onRenderingGroupObservable = new BABYLON.Observable();
  19122. // Animations
  19123. this.animations = [];
  19124. /**
  19125. * 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).
  19126. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19127. */
  19128. this.onPrePointerObservable = new BABYLON.Observable();
  19129. /**
  19130. * Observable event triggered each time an input event is received from the rendering canvas
  19131. */
  19132. this.onPointerObservable = new BABYLON.Observable();
  19133. 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
  19134. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19135. this._startingPointerTime = 0;
  19136. // Fog
  19137. /**
  19138. * is fog enabled on this scene.
  19139. * @type {boolean}
  19140. */
  19141. this.fogEnabled = true;
  19142. this.fogMode = Scene.FOGMODE_NONE;
  19143. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19144. this.fogDensity = 0.1;
  19145. this.fogStart = 0;
  19146. this.fogEnd = 1000.0;
  19147. // Lights
  19148. /**
  19149. * is shadow enabled on this scene.
  19150. * @type {boolean}
  19151. */
  19152. this.shadowsEnabled = true;
  19153. /**
  19154. * is light enabled on this scene.
  19155. * @type {boolean}
  19156. */
  19157. this.lightsEnabled = true;
  19158. /**
  19159. * All of the lights added to this scene.
  19160. * @see BABYLON.Light
  19161. * @type {BABYLON.Light[]}
  19162. */
  19163. this.lights = new Array();
  19164. // Cameras
  19165. /**
  19166. * All of the cameras added to this scene.
  19167. * @see BABYLON.Camera
  19168. * @type {BABYLON.Camera[]}
  19169. */
  19170. this.cameras = new Array();
  19171. this.activeCameras = new Array();
  19172. // Meshes
  19173. /**
  19174. * All of the (abstract) meshes added to this scene.
  19175. * @see BABYLON.AbstractMesh
  19176. * @type {BABYLON.AbstractMesh[]}
  19177. */
  19178. this.meshes = new Array();
  19179. // Geometries
  19180. this._geometries = new Array();
  19181. this.materials = new Array();
  19182. this.multiMaterials = new Array();
  19183. // Textures
  19184. this.texturesEnabled = true;
  19185. this.textures = new Array();
  19186. // Particles
  19187. this.particlesEnabled = true;
  19188. this.particleSystems = new Array();
  19189. // Sprites
  19190. this.spritesEnabled = true;
  19191. this.spriteManagers = new Array();
  19192. // Layers
  19193. this.layers = new Array();
  19194. this.highlightLayers = new Array();
  19195. // Skeletons
  19196. this.skeletonsEnabled = true;
  19197. this.skeletons = new Array();
  19198. // Lens flares
  19199. this.lensFlaresEnabled = true;
  19200. this.lensFlareSystems = new Array();
  19201. // Collisions
  19202. this.collisionsEnabled = true;
  19203. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19204. // Postprocesses
  19205. this.postProcessesEnabled = true;
  19206. // Customs render targets
  19207. this.renderTargetsEnabled = true;
  19208. this.dumpNextRenderTargets = false;
  19209. this.customRenderTargets = new Array();
  19210. // Imported meshes
  19211. this.importedMeshesFiles = new Array();
  19212. // Probes
  19213. this.probesEnabled = true;
  19214. this.reflectionProbes = new Array();
  19215. this._actionManagers = new Array();
  19216. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19217. // Procedural textures
  19218. this.proceduralTexturesEnabled = true;
  19219. this._proceduralTextures = new Array();
  19220. this.soundTracks = new Array();
  19221. this._audioEnabled = true;
  19222. this._headphone = false;
  19223. // Performance counters
  19224. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19225. this._totalLightsCounter = new BABYLON.PerfCounter();
  19226. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19227. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19228. this._totalVertices = new BABYLON.PerfCounter();
  19229. this._activeIndices = new BABYLON.PerfCounter();
  19230. this._activeParticles = new BABYLON.PerfCounter();
  19231. this._lastFrameDuration = new BABYLON.PerfCounter();
  19232. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19233. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19234. this._particlesDuration = new BABYLON.PerfCounter();
  19235. this._renderDuration = new BABYLON.PerfCounter();
  19236. this._spritesDuration = new BABYLON.PerfCounter();
  19237. this._activeBones = new BABYLON.PerfCounter();
  19238. this._animationTime = 0;
  19239. this.animationTimeScale = 1;
  19240. this._renderId = 0;
  19241. this._executeWhenReadyTimeoutId = -1;
  19242. this._intermediateRendering = false;
  19243. this._toBeDisposed = new BABYLON.SmartArray(256);
  19244. this._pendingData = []; //ANY
  19245. this._activeMeshes = new BABYLON.SmartArray(256);
  19246. this._processedMaterials = new BABYLON.SmartArray(256);
  19247. this._renderTargets = new BABYLON.SmartArray(256);
  19248. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19249. this._activeSkeletons = new BABYLON.SmartArray(32);
  19250. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19251. this._activeAnimatables = new Array();
  19252. this._transformMatrix = BABYLON.Matrix.Zero();
  19253. this._edgesRenderers = new BABYLON.SmartArray(16);
  19254. this._uniqueIdCounter = 0;
  19255. this._engine = engine;
  19256. engine.scenes.push(this);
  19257. this._externalData = new BABYLON.StringDictionary();
  19258. this._uid = null;
  19259. this._renderingManager = new BABYLON.RenderingManager(this);
  19260. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19261. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19262. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19263. if (BABYLON.OutlineRenderer) {
  19264. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19265. }
  19266. this.attachControl();
  19267. if (BABYLON.SoundTrack) {
  19268. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19269. }
  19270. //simplification queue
  19271. if (BABYLON.SimplificationQueue) {
  19272. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19273. }
  19274. //collision coordinator initialization. For now legacy per default.
  19275. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19276. }
  19277. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19278. get: function () {
  19279. return Scene._FOGMODE_NONE;
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19285. get: function () {
  19286. return Scene._FOGMODE_EXP;
  19287. },
  19288. enumerable: true,
  19289. configurable: true
  19290. });
  19291. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19292. get: function () {
  19293. return Scene._FOGMODE_EXP2;
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19299. get: function () {
  19300. return Scene._FOGMODE_LINEAR;
  19301. },
  19302. enumerable: true,
  19303. configurable: true
  19304. });
  19305. Object.defineProperty(Scene.prototype, "onDispose", {
  19306. set: function (callback) {
  19307. if (this._onDisposeObserver) {
  19308. this.onDisposeObservable.remove(this._onDisposeObserver);
  19309. }
  19310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Scene.prototype, "beforeRender", {
  19316. set: function (callback) {
  19317. if (this._onBeforeRenderObserver) {
  19318. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19319. }
  19320. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(Scene.prototype, "afterRender", {
  19326. set: function (callback) {
  19327. if (this._onAfterRenderObserver) {
  19328. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19329. }
  19330. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19336. set: function (callback) {
  19337. if (this._onBeforeCameraRenderObserver) {
  19338. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19339. }
  19340. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19346. set: function (callback) {
  19347. if (this._onAfterCameraRenderObserver) {
  19348. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19349. }
  19350. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19356. get: function () {
  19357. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19358. },
  19359. enumerable: true,
  19360. configurable: true
  19361. });
  19362. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19363. get: function () {
  19364. if (!this._defaultMaterial) {
  19365. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19366. }
  19367. return this._defaultMaterial;
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19373. get: function () {
  19374. return this._frustumPlanes;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Scene.prototype, "debugLayer", {
  19380. // Properties
  19381. get: function () {
  19382. if (!this._debugLayer) {
  19383. this._debugLayer = new BABYLON.DebugLayer(this);
  19384. }
  19385. return this._debugLayer;
  19386. },
  19387. enumerable: true,
  19388. configurable: true
  19389. });
  19390. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19391. get: function () {
  19392. return this._workerCollisions;
  19393. },
  19394. set: function (enabled) {
  19395. enabled = (enabled && !!Worker);
  19396. this._workerCollisions = enabled;
  19397. if (this.collisionCoordinator) {
  19398. this.collisionCoordinator.destroy();
  19399. }
  19400. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19401. this.collisionCoordinator.init(this);
  19402. },
  19403. enumerable: true,
  19404. configurable: true
  19405. });
  19406. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19407. get: function () {
  19408. return this._selectionOctree;
  19409. },
  19410. enumerable: true,
  19411. configurable: true
  19412. });
  19413. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19414. /**
  19415. * The mesh that is currently under the pointer.
  19416. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19417. */
  19418. get: function () {
  19419. return this._pointerOverMesh;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(Scene.prototype, "pointerX", {
  19425. /**
  19426. * Current on-screen X position of the pointer
  19427. * @return {number} X position of the pointer
  19428. */
  19429. get: function () {
  19430. return this._pointerX;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. Object.defineProperty(Scene.prototype, "pointerY", {
  19436. /**
  19437. * Current on-screen Y position of the pointer
  19438. * @return {number} Y position of the pointer
  19439. */
  19440. get: function () {
  19441. return this._pointerY;
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Scene.prototype.getCachedMaterial = function () {
  19447. return this._cachedMaterial;
  19448. };
  19449. Scene.prototype.getBoundingBoxRenderer = function () {
  19450. return this._boundingBoxRenderer;
  19451. };
  19452. Scene.prototype.getOutlineRenderer = function () {
  19453. return this._outlineRenderer;
  19454. };
  19455. Scene.prototype.getEngine = function () {
  19456. return this._engine;
  19457. };
  19458. Scene.prototype.getTotalVertices = function () {
  19459. return this._totalVertices.current;
  19460. };
  19461. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19462. get: function () {
  19463. return this._totalVertices;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Scene.prototype.getActiveIndices = function () {
  19469. return this._activeIndices.current;
  19470. };
  19471. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19472. get: function () {
  19473. return this._activeIndices;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Scene.prototype.getActiveParticles = function () {
  19479. return this._activeParticles.current;
  19480. };
  19481. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19482. get: function () {
  19483. return this._activeParticles;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Scene.prototype.getActiveBones = function () {
  19489. return this._activeBones.current;
  19490. };
  19491. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19492. get: function () {
  19493. return this._activeBones;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. // Stats
  19499. Scene.prototype.getLastFrameDuration = function () {
  19500. return this._lastFrameDuration.current;
  19501. };
  19502. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19503. get: function () {
  19504. return this._lastFrameDuration;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19510. return this._evaluateActiveMeshesDuration.current;
  19511. };
  19512. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19513. get: function () {
  19514. return this._evaluateActiveMeshesDuration;
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Scene.prototype.getActiveMeshes = function () {
  19520. return this._activeMeshes;
  19521. };
  19522. Scene.prototype.getRenderTargetsDuration = function () {
  19523. return this._renderTargetsDuration.current;
  19524. };
  19525. Scene.prototype.getRenderDuration = function () {
  19526. return this._renderDuration.current;
  19527. };
  19528. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19529. get: function () {
  19530. return this._renderDuration;
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Scene.prototype.getParticlesDuration = function () {
  19536. return this._particlesDuration.current;
  19537. };
  19538. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19539. get: function () {
  19540. return this._particlesDuration;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Scene.prototype.getSpritesDuration = function () {
  19546. return this._spritesDuration.current;
  19547. };
  19548. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19549. get: function () {
  19550. return this._spritesDuration;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Scene.prototype.getAnimationRatio = function () {
  19556. return this._animationRatio;
  19557. };
  19558. Scene.prototype.getRenderId = function () {
  19559. return this._renderId;
  19560. };
  19561. Scene.prototype.incrementRenderId = function () {
  19562. this._renderId++;
  19563. };
  19564. Scene.prototype._updatePointerPosition = function (evt) {
  19565. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19566. this._pointerX = evt.clientX - canvasRect.left;
  19567. this._pointerY = evt.clientY - canvasRect.top;
  19568. this._unTranslatedPointerX = this._pointerX;
  19569. this._unTranslatedPointerY = this._pointerY;
  19570. if (this.cameraToUseForPointers) {
  19571. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19572. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19573. }
  19574. };
  19575. // Pointers handling
  19576. /**
  19577. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19578. * @param attachUp defines if you want to attach events to pointerup
  19579. * @param attachDown defines if you want to attach events to pointerdown
  19580. * @param attachMove defines if you want to attach events to pointermove
  19581. */
  19582. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19583. var _this = this;
  19584. if (attachUp === void 0) { attachUp = true; }
  19585. if (attachDown === void 0) { attachDown = true; }
  19586. if (attachMove === void 0) { attachMove = true; }
  19587. var spritePredicate = function (sprite) {
  19588. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19589. };
  19590. this._onPointerMove = function (evt) {
  19591. _this._updatePointerPosition(evt);
  19592. // PreObservable support
  19593. if (_this.onPrePointerObservable.hasObservers()) {
  19594. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19595. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19596. _this.onPrePointerObservable.notifyObservers(pi, type);
  19597. if (pi.skipOnPointerObservable) {
  19598. return;
  19599. }
  19600. }
  19601. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19602. return;
  19603. }
  19604. var canvas = _this._engine.getRenderingCanvas();
  19605. if (!_this.pointerMovePredicate) {
  19606. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19607. }
  19608. // Meshes
  19609. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19610. if (pickResult.hit && pickResult.pickedMesh) {
  19611. _this.setPointerOverSprite(null);
  19612. _this.setPointerOverMesh(pickResult.pickedMesh);
  19613. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19614. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  19615. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  19616. }
  19617. else {
  19618. canvas.style.cursor = _this.hoverCursor;
  19619. }
  19620. }
  19621. else {
  19622. canvas.style.cursor = "";
  19623. }
  19624. }
  19625. else {
  19626. _this.setPointerOverMesh(null);
  19627. // Sprites
  19628. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19629. if (pickResult.hit && pickResult.pickedSprite) {
  19630. _this.setPointerOverSprite(pickResult.pickedSprite);
  19631. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  19632. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  19633. }
  19634. else {
  19635. canvas.style.cursor = _this.hoverCursor;
  19636. }
  19637. }
  19638. else {
  19639. _this.setPointerOverSprite(null);
  19640. // Restore pointer
  19641. canvas.style.cursor = "";
  19642. }
  19643. }
  19644. if (_this.onPointerMove) {
  19645. _this.onPointerMove(evt, pickResult);
  19646. }
  19647. if (_this.onPointerObservable.hasObservers()) {
  19648. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19649. var pi = new PointerInfo(type, evt, pickResult);
  19650. _this.onPointerObservable.notifyObservers(pi, type);
  19651. }
  19652. };
  19653. this._onPointerDown = function (evt) {
  19654. _this._updatePointerPosition(evt);
  19655. // PreObservable support
  19656. if (_this.onPrePointerObservable.hasObservers()) {
  19657. var type = PointerEventTypes.POINTERDOWN;
  19658. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19659. _this.onPrePointerObservable.notifyObservers(pi, type);
  19660. if (pi.skipOnPointerObservable) {
  19661. return;
  19662. }
  19663. }
  19664. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19665. return;
  19666. }
  19667. _this._startingPointerPosition.x = _this._pointerX;
  19668. _this._startingPointerPosition.y = _this._pointerY;
  19669. _this._startingPointerTime = new Date().getTime();
  19670. if (!_this.pointerDownPredicate) {
  19671. _this.pointerDownPredicate = function (mesh) {
  19672. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19673. };
  19674. }
  19675. // Meshes
  19676. _this._pickedDownMesh = null;
  19677. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19678. if (pickResult.hit && pickResult.pickedMesh) {
  19679. _this._pickedDownMesh = pickResult.pickedMesh;
  19680. if (pickResult.pickedMesh.actionManager) {
  19681. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  19682. switch (evt.button) {
  19683. case 0:
  19684. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19685. break;
  19686. case 1:
  19687. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19688. break;
  19689. case 2:
  19690. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19691. break;
  19692. }
  19693. if (pickResult.pickedMesh.actionManager) {
  19694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19695. }
  19696. }
  19697. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19698. var that = _this;
  19699. window.setTimeout(function () {
  19700. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  19701. if (pickResult.hit && pickResult.pickedMesh) {
  19702. if (pickResult.pickedMesh.actionManager) {
  19703. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  19704. that._startingPointerTime = 0;
  19705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19706. }
  19707. }
  19708. }
  19709. }, BABYLON.ActionManager.LongPressDelay);
  19710. }
  19711. }
  19712. }
  19713. if (_this.onPointerDown) {
  19714. _this.onPointerDown(evt, pickResult);
  19715. }
  19716. if (_this.onPointerObservable.hasObservers()) {
  19717. var type = PointerEventTypes.POINTERDOWN;
  19718. var pi = new PointerInfo(type, evt, pickResult);
  19719. _this.onPointerObservable.notifyObservers(pi, type);
  19720. }
  19721. // Sprites
  19722. _this._pickedDownSprite = null;
  19723. if (_this.spriteManagers.length > 0) {
  19724. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19725. if (pickResult.hit && pickResult.pickedSprite) {
  19726. if (pickResult.pickedSprite.actionManager) {
  19727. _this._pickedDownSprite = pickResult.pickedSprite;
  19728. switch (evt.button) {
  19729. case 0:
  19730. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19731. break;
  19732. case 1:
  19733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19734. break;
  19735. case 2:
  19736. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19737. break;
  19738. }
  19739. if (pickResult.pickedSprite.actionManager) {
  19740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19741. }
  19742. }
  19743. }
  19744. }
  19745. };
  19746. this._onPointerUp = function (evt) {
  19747. _this._updatePointerPosition(evt);
  19748. // PreObservable support
  19749. if (_this.onPrePointerObservable.hasObservers()) {
  19750. var type = PointerEventTypes.POINTERUP;
  19751. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19752. _this.onPrePointerObservable.notifyObservers(pi, type);
  19753. if (pi.skipOnPointerObservable) {
  19754. return;
  19755. }
  19756. }
  19757. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19758. return;
  19759. }
  19760. if (!_this.pointerUpPredicate) {
  19761. _this.pointerUpPredicate = function (mesh) {
  19762. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19763. };
  19764. }
  19765. // Meshes
  19766. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  19767. if (pickResult.hit && pickResult.pickedMesh) {
  19768. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  19769. if (_this.onPointerPick) {
  19770. _this.onPointerPick(evt, pickResult);
  19771. }
  19772. if (_this.onPointerObservable.hasObservers()) {
  19773. var type = PointerEventTypes.POINTERPICK;
  19774. var pi = new PointerInfo(type, evt, pickResult);
  19775. _this.onPointerObservable.notifyObservers(pi, type);
  19776. }
  19777. }
  19778. if (pickResult.pickedMesh.actionManager) {
  19779. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19780. if (pickResult.pickedMesh.actionManager) {
  19781. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19782. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19783. }
  19784. }
  19785. }
  19786. }
  19787. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  19788. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  19789. }
  19790. if (_this.onPointerUp) {
  19791. _this.onPointerUp(evt, pickResult);
  19792. }
  19793. if (_this.onPointerObservable.hasObservers()) {
  19794. var type = PointerEventTypes.POINTERUP;
  19795. var pi = new PointerInfo(type, evt, pickResult);
  19796. _this.onPointerObservable.notifyObservers(pi, type);
  19797. }
  19798. _this._startingPointerTime = 0;
  19799. // Sprites
  19800. if (_this.spriteManagers.length > 0) {
  19801. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19802. if (pickResult.hit && pickResult.pickedSprite) {
  19803. if (pickResult.pickedSprite.actionManager) {
  19804. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19805. if (pickResult.pickedSprite.actionManager) {
  19806. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19807. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19808. }
  19809. }
  19810. }
  19811. }
  19812. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  19813. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19814. }
  19815. }
  19816. };
  19817. this._onKeyDown = function (evt) {
  19818. if (_this.actionManager) {
  19819. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19820. }
  19821. };
  19822. this._onKeyUp = function (evt) {
  19823. if (_this.actionManager) {
  19824. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19825. }
  19826. };
  19827. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19828. var canvas = this._engine.getRenderingCanvas();
  19829. if (attachMove) {
  19830. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19831. // Wheel
  19832. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19833. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19834. }
  19835. if (attachDown) {
  19836. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19837. }
  19838. if (attachUp) {
  19839. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19840. }
  19841. canvas.tabIndex = 1;
  19842. canvas.addEventListener("keydown", this._onKeyDown, false);
  19843. canvas.addEventListener("keyup", this._onKeyUp, false);
  19844. };
  19845. Scene.prototype.detachControl = function () {
  19846. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19847. var canvas = this._engine.getRenderingCanvas();
  19848. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19849. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19850. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19851. // Wheel
  19852. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19853. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19854. canvas.removeEventListener("keydown", this._onKeyDown);
  19855. canvas.removeEventListener("keyup", this._onKeyUp);
  19856. };
  19857. // Ready
  19858. Scene.prototype.isReady = function () {
  19859. if (this._pendingData.length > 0) {
  19860. return false;
  19861. }
  19862. var index;
  19863. for (index = 0; index < this._geometries.length; index++) {
  19864. var geometry = this._geometries[index];
  19865. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19866. return false;
  19867. }
  19868. }
  19869. for (index = 0; index < this.meshes.length; index++) {
  19870. var mesh = this.meshes[index];
  19871. if (!mesh.isReady()) {
  19872. return false;
  19873. }
  19874. var mat = mesh.material;
  19875. if (mat) {
  19876. if (!mat.isReady(mesh)) {
  19877. return false;
  19878. }
  19879. }
  19880. }
  19881. return true;
  19882. };
  19883. Scene.prototype.resetCachedMaterial = function () {
  19884. this._cachedMaterial = null;
  19885. };
  19886. Scene.prototype.registerBeforeRender = function (func) {
  19887. this.onBeforeRenderObservable.add(func);
  19888. };
  19889. Scene.prototype.unregisterBeforeRender = function (func) {
  19890. this.onBeforeRenderObservable.removeCallback(func);
  19891. };
  19892. Scene.prototype.registerAfterRender = function (func) {
  19893. this.onAfterRenderObservable.add(func);
  19894. };
  19895. Scene.prototype.unregisterAfterRender = function (func) {
  19896. this.onAfterRenderObservable.removeCallback(func);
  19897. };
  19898. Scene.prototype._addPendingData = function (data) {
  19899. this._pendingData.push(data);
  19900. };
  19901. Scene.prototype._removePendingData = function (data) {
  19902. var index = this._pendingData.indexOf(data);
  19903. if (index !== -1) {
  19904. this._pendingData.splice(index, 1);
  19905. }
  19906. };
  19907. Scene.prototype.getWaitingItemsCount = function () {
  19908. return this._pendingData.length;
  19909. };
  19910. /**
  19911. * Registers a function to be executed when the scene is ready.
  19912. * @param {Function} func - the function to be executed.
  19913. */
  19914. Scene.prototype.executeWhenReady = function (func) {
  19915. var _this = this;
  19916. this.onReadyObservable.add(func);
  19917. if (this._executeWhenReadyTimeoutId !== -1) {
  19918. return;
  19919. }
  19920. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19921. _this._checkIsReady();
  19922. }, 150);
  19923. };
  19924. Scene.prototype._checkIsReady = function () {
  19925. var _this = this;
  19926. if (this.isReady()) {
  19927. this.onReadyObservable.notifyObservers(this);
  19928. this.onReadyObservable.clear();
  19929. this._executeWhenReadyTimeoutId = -1;
  19930. return;
  19931. }
  19932. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19933. _this._checkIsReady();
  19934. }, 150);
  19935. };
  19936. // Animations
  19937. /**
  19938. * Will start the animation sequence of a given target
  19939. * @param target - the target
  19940. * @param {number} from - from which frame should animation start
  19941. * @param {number} to - till which frame should animation run.
  19942. * @param {boolean} [loop] - should the animation loop
  19943. * @param {number} [speedRatio] - the speed in which to run the animation
  19944. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19945. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19946. * @return {BABYLON.Animatable} the animatable object created for this animation
  19947. * @see BABYLON.Animatable
  19948. * @see http://doc.babylonjs.com/page.php?p=22081
  19949. */
  19950. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19951. if (speedRatio === void 0) { speedRatio = 1.0; }
  19952. this.stopAnimation(target);
  19953. if (!animatable) {
  19954. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19955. }
  19956. // Local animations
  19957. if (target.animations) {
  19958. animatable.appendAnimations(target, target.animations);
  19959. }
  19960. // Children animations
  19961. if (target.getAnimatables) {
  19962. var animatables = target.getAnimatables();
  19963. for (var index = 0; index < animatables.length; index++) {
  19964. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19965. }
  19966. }
  19967. animatable.reset();
  19968. return animatable;
  19969. };
  19970. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19971. if (speedRatio === undefined) {
  19972. speedRatio = 1.0;
  19973. }
  19974. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19975. return animatable;
  19976. };
  19977. Scene.prototype.getAnimatableByTarget = function (target) {
  19978. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19979. if (this._activeAnimatables[index].target === target) {
  19980. return this._activeAnimatables[index];
  19981. }
  19982. }
  19983. return null;
  19984. };
  19985. Object.defineProperty(Scene.prototype, "Animatables", {
  19986. get: function () {
  19987. return this._activeAnimatables;
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. /**
  19993. * Will stop the animation of the given target
  19994. * @param target - the target
  19995. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19996. * @see beginAnimation
  19997. */
  19998. Scene.prototype.stopAnimation = function (target, animationName) {
  19999. var animatable = this.getAnimatableByTarget(target);
  20000. if (animatable) {
  20001. animatable.stop(animationName);
  20002. }
  20003. };
  20004. Scene.prototype._animate = function () {
  20005. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20006. return;
  20007. }
  20008. // Getting time
  20009. var now = BABYLON.Tools.Now;
  20010. if (!this._animationTimeLast) {
  20011. if (this._pendingData.length > 0) {
  20012. return;
  20013. }
  20014. this._animationTimeLast = now;
  20015. }
  20016. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20017. this._animationTime += deltaTime;
  20018. this._animationTimeLast = now;
  20019. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20020. this._activeAnimatables[index]._animate(this._animationTime);
  20021. }
  20022. };
  20023. // Matrix
  20024. Scene.prototype.getViewMatrix = function () {
  20025. return this._viewMatrix;
  20026. };
  20027. Scene.prototype.getProjectionMatrix = function () {
  20028. return this._projectionMatrix;
  20029. };
  20030. Scene.prototype.getTransformMatrix = function () {
  20031. return this._transformMatrix;
  20032. };
  20033. Scene.prototype.setTransformMatrix = function (view, projection) {
  20034. this._viewMatrix = view;
  20035. this._projectionMatrix = projection;
  20036. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20037. // Update frustum
  20038. if (!this._frustumPlanes) {
  20039. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20040. }
  20041. else {
  20042. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20043. }
  20044. };
  20045. // Methods
  20046. Scene.prototype.addMesh = function (newMesh) {
  20047. newMesh.uniqueId = this._uniqueIdCounter++;
  20048. var position = this.meshes.push(newMesh);
  20049. //notify the collision coordinator
  20050. this.collisionCoordinator.onMeshAdded(newMesh);
  20051. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20052. };
  20053. Scene.prototype.removeMesh = function (toRemove) {
  20054. var index = this.meshes.indexOf(toRemove);
  20055. if (index !== -1) {
  20056. // Remove from the scene if mesh found
  20057. this.meshes.splice(index, 1);
  20058. }
  20059. //notify the collision coordinator
  20060. this.collisionCoordinator.onMeshRemoved(toRemove);
  20061. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20062. return index;
  20063. };
  20064. Scene.prototype.removeSkeleton = function (toRemove) {
  20065. var index = this.skeletons.indexOf(toRemove);
  20066. if (index !== -1) {
  20067. // Remove from the scene if mesh found
  20068. this.skeletons.splice(index, 1);
  20069. }
  20070. return index;
  20071. };
  20072. Scene.prototype.removeLight = function (toRemove) {
  20073. var index = this.lights.indexOf(toRemove);
  20074. if (index !== -1) {
  20075. // Remove from the scene if mesh found
  20076. this.lights.splice(index, 1);
  20077. }
  20078. this.onLightRemovedObservable.notifyObservers(toRemove);
  20079. return index;
  20080. };
  20081. Scene.prototype.removeCamera = function (toRemove) {
  20082. var index = this.cameras.indexOf(toRemove);
  20083. if (index !== -1) {
  20084. // Remove from the scene if mesh found
  20085. this.cameras.splice(index, 1);
  20086. }
  20087. // Remove from activeCameras
  20088. var index2 = this.activeCameras.indexOf(toRemove);
  20089. if (index2 !== -1) {
  20090. // Remove from the scene if mesh found
  20091. this.activeCameras.splice(index2, 1);
  20092. }
  20093. // Reset the activeCamera
  20094. if (this.activeCamera === toRemove) {
  20095. if (this.cameras.length > 0) {
  20096. this.activeCamera = this.cameras[0];
  20097. }
  20098. else {
  20099. this.activeCamera = null;
  20100. }
  20101. }
  20102. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20103. return index;
  20104. };
  20105. Scene.prototype.addLight = function (newLight) {
  20106. newLight.uniqueId = this._uniqueIdCounter++;
  20107. var position = this.lights.push(newLight);
  20108. this.onNewLightAddedObservable.notifyObservers(newLight);
  20109. };
  20110. Scene.prototype.addCamera = function (newCamera) {
  20111. newCamera.uniqueId = this._uniqueIdCounter++;
  20112. var position = this.cameras.push(newCamera);
  20113. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20114. };
  20115. /**
  20116. * Switch active camera
  20117. * @param {Camera} newCamera - new active camera
  20118. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20119. */
  20120. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20121. if (attachControl === void 0) { attachControl = true; }
  20122. var canvas = this._engine.getRenderingCanvas();
  20123. this.activeCamera.detachControl(canvas);
  20124. this.activeCamera = newCamera;
  20125. if (attachControl) {
  20126. newCamera.attachControl(canvas);
  20127. }
  20128. };
  20129. /**
  20130. * sets the active camera of the scene using its ID
  20131. * @param {string} id - the camera's ID
  20132. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20133. * @see activeCamera
  20134. */
  20135. Scene.prototype.setActiveCameraByID = function (id) {
  20136. var camera = this.getCameraByID(id);
  20137. if (camera) {
  20138. this.activeCamera = camera;
  20139. return camera;
  20140. }
  20141. return null;
  20142. };
  20143. /**
  20144. * sets the active camera of the scene using its name
  20145. * @param {string} name - the camera's name
  20146. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20147. * @see activeCamera
  20148. */
  20149. Scene.prototype.setActiveCameraByName = function (name) {
  20150. var camera = this.getCameraByName(name);
  20151. if (camera) {
  20152. this.activeCamera = camera;
  20153. return camera;
  20154. }
  20155. return null;
  20156. };
  20157. /**
  20158. * get a material using its id
  20159. * @param {string} the material's ID
  20160. * @return {BABYLON.Material|null} the material or null if none found.
  20161. */
  20162. Scene.prototype.getMaterialByID = function (id) {
  20163. for (var index = 0; index < this.materials.length; index++) {
  20164. if (this.materials[index].id === id) {
  20165. return this.materials[index];
  20166. }
  20167. }
  20168. return null;
  20169. };
  20170. /**
  20171. * get a material using its name
  20172. * @param {string} the material's name
  20173. * @return {BABYLON.Material|null} the material or null if none found.
  20174. */
  20175. Scene.prototype.getMaterialByName = function (name) {
  20176. for (var index = 0; index < this.materials.length; index++) {
  20177. if (this.materials[index].name === name) {
  20178. return this.materials[index];
  20179. }
  20180. }
  20181. return null;
  20182. };
  20183. Scene.prototype.getLensFlareSystemByName = function (name) {
  20184. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20185. if (this.lensFlareSystems[index].name === name) {
  20186. return this.lensFlareSystems[index];
  20187. }
  20188. }
  20189. return null;
  20190. };
  20191. Scene.prototype.getLensFlareSystemByID = function (id) {
  20192. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20193. if (this.lensFlareSystems[index].id === id) {
  20194. return this.lensFlareSystems[index];
  20195. }
  20196. }
  20197. return null;
  20198. };
  20199. Scene.prototype.getCameraByID = function (id) {
  20200. for (var index = 0; index < this.cameras.length; index++) {
  20201. if (this.cameras[index].id === id) {
  20202. return this.cameras[index];
  20203. }
  20204. }
  20205. return null;
  20206. };
  20207. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20208. for (var index = 0; index < this.cameras.length; index++) {
  20209. if (this.cameras[index].uniqueId === uniqueId) {
  20210. return this.cameras[index];
  20211. }
  20212. }
  20213. return null;
  20214. };
  20215. /**
  20216. * get a camera using its name
  20217. * @param {string} the camera's name
  20218. * @return {BABYLON.Camera|null} the camera or null if none found.
  20219. */
  20220. Scene.prototype.getCameraByName = function (name) {
  20221. for (var index = 0; index < this.cameras.length; index++) {
  20222. if (this.cameras[index].name === name) {
  20223. return this.cameras[index];
  20224. }
  20225. }
  20226. return null;
  20227. };
  20228. /**
  20229. * get a bone using its id
  20230. * @param {string} the bone's id
  20231. * @return {BABYLON.Bone|null} the bone or null if not found
  20232. */
  20233. Scene.prototype.getBoneByID = function (id) {
  20234. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20235. var skeleton = this.skeletons[skeletonIndex];
  20236. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20237. if (skeleton.bones[boneIndex].id === id) {
  20238. return skeleton.bones[boneIndex];
  20239. }
  20240. }
  20241. }
  20242. return null;
  20243. };
  20244. /**
  20245. * get a bone using its id
  20246. * @param {string} the bone's name
  20247. * @return {BABYLON.Bone|null} the bone or null if not found
  20248. */
  20249. Scene.prototype.getBoneByName = function (name) {
  20250. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20251. var skeleton = this.skeletons[skeletonIndex];
  20252. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20253. if (skeleton.bones[boneIndex].name === name) {
  20254. return skeleton.bones[boneIndex];
  20255. }
  20256. }
  20257. }
  20258. return null;
  20259. };
  20260. /**
  20261. * get a light node using its name
  20262. * @param {string} the light's name
  20263. * @return {BABYLON.Light|null} the light or null if none found.
  20264. */
  20265. Scene.prototype.getLightByName = function (name) {
  20266. for (var index = 0; index < this.lights.length; index++) {
  20267. if (this.lights[index].name === name) {
  20268. return this.lights[index];
  20269. }
  20270. }
  20271. return null;
  20272. };
  20273. /**
  20274. * get a light node using its ID
  20275. * @param {string} the light's id
  20276. * @return {BABYLON.Light|null} the light or null if none found.
  20277. */
  20278. Scene.prototype.getLightByID = function (id) {
  20279. for (var index = 0; index < this.lights.length; index++) {
  20280. if (this.lights[index].id === id) {
  20281. return this.lights[index];
  20282. }
  20283. }
  20284. return null;
  20285. };
  20286. /**
  20287. * get a light node using its scene-generated unique ID
  20288. * @param {number} the light's unique id
  20289. * @return {BABYLON.Light|null} the light or null if none found.
  20290. */
  20291. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20292. for (var index = 0; index < this.lights.length; index++) {
  20293. if (this.lights[index].uniqueId === uniqueId) {
  20294. return this.lights[index];
  20295. }
  20296. }
  20297. return null;
  20298. };
  20299. /**
  20300. * get a particle system by id
  20301. * @param id {number} the particle system id
  20302. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20303. */
  20304. Scene.prototype.getParticleSystemByID = function (id) {
  20305. for (var index = 0; index < this.particleSystems.length; index++) {
  20306. if (this.particleSystems[index].id === id) {
  20307. return this.particleSystems[index];
  20308. }
  20309. }
  20310. return null;
  20311. };
  20312. /**
  20313. * get a geometry using its ID
  20314. * @param {string} the geometry's id
  20315. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20316. */
  20317. Scene.prototype.getGeometryByID = function (id) {
  20318. for (var index = 0; index < this._geometries.length; index++) {
  20319. if (this._geometries[index].id === id) {
  20320. return this._geometries[index];
  20321. }
  20322. }
  20323. return null;
  20324. };
  20325. /**
  20326. * add a new geometry to this scene.
  20327. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20328. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20329. * @return {boolean} was the geometry added or not
  20330. */
  20331. Scene.prototype.pushGeometry = function (geometry, force) {
  20332. if (!force && this.getGeometryByID(geometry.id)) {
  20333. return false;
  20334. }
  20335. this._geometries.push(geometry);
  20336. //notify the collision coordinator
  20337. this.collisionCoordinator.onGeometryAdded(geometry);
  20338. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20339. return true;
  20340. };
  20341. /**
  20342. * Removes an existing geometry
  20343. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20344. * @return {boolean} was the geometry removed or not
  20345. */
  20346. Scene.prototype.removeGeometry = function (geometry) {
  20347. var index = this._geometries.indexOf(geometry);
  20348. if (index > -1) {
  20349. this._geometries.splice(index, 1);
  20350. //notify the collision coordinator
  20351. this.collisionCoordinator.onGeometryDeleted(geometry);
  20352. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20353. return true;
  20354. }
  20355. return false;
  20356. };
  20357. Scene.prototype.getGeometries = function () {
  20358. return this._geometries;
  20359. };
  20360. /**
  20361. * Get the first added mesh found of a given ID
  20362. * @param {string} id - the id to search for
  20363. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20364. */
  20365. Scene.prototype.getMeshByID = function (id) {
  20366. for (var index = 0; index < this.meshes.length; index++) {
  20367. if (this.meshes[index].id === id) {
  20368. return this.meshes[index];
  20369. }
  20370. }
  20371. return null;
  20372. };
  20373. Scene.prototype.getMeshesByID = function (id) {
  20374. return this.meshes.filter(function (m) {
  20375. return m.id === id;
  20376. });
  20377. };
  20378. /**
  20379. * Get a mesh with its auto-generated unique id
  20380. * @param {number} uniqueId - the unique id to search for
  20381. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20382. */
  20383. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20384. for (var index = 0; index < this.meshes.length; index++) {
  20385. if (this.meshes[index].uniqueId === uniqueId) {
  20386. return this.meshes[index];
  20387. }
  20388. }
  20389. return null;
  20390. };
  20391. /**
  20392. * Get a the last added mesh found of a given ID
  20393. * @param {string} id - the id to search for
  20394. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20395. */
  20396. Scene.prototype.getLastMeshByID = function (id) {
  20397. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20398. if (this.meshes[index].id === id) {
  20399. return this.meshes[index];
  20400. }
  20401. }
  20402. return null;
  20403. };
  20404. /**
  20405. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20406. * @param {string} id - the id to search for
  20407. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20408. */
  20409. Scene.prototype.getLastEntryByID = function (id) {
  20410. var index;
  20411. for (index = this.meshes.length - 1; index >= 0; index--) {
  20412. if (this.meshes[index].id === id) {
  20413. return this.meshes[index];
  20414. }
  20415. }
  20416. for (index = this.cameras.length - 1; index >= 0; index--) {
  20417. if (this.cameras[index].id === id) {
  20418. return this.cameras[index];
  20419. }
  20420. }
  20421. for (index = this.lights.length - 1; index >= 0; index--) {
  20422. if (this.lights[index].id === id) {
  20423. return this.lights[index];
  20424. }
  20425. }
  20426. return null;
  20427. };
  20428. Scene.prototype.getNodeByID = function (id) {
  20429. var mesh = this.getMeshByID(id);
  20430. if (mesh) {
  20431. return mesh;
  20432. }
  20433. var light = this.getLightByID(id);
  20434. if (light) {
  20435. return light;
  20436. }
  20437. var camera = this.getCameraByID(id);
  20438. if (camera) {
  20439. return camera;
  20440. }
  20441. var bone = this.getBoneByID(id);
  20442. return bone;
  20443. };
  20444. Scene.prototype.getNodeByName = function (name) {
  20445. var mesh = this.getMeshByName(name);
  20446. if (mesh) {
  20447. return mesh;
  20448. }
  20449. var light = this.getLightByName(name);
  20450. if (light) {
  20451. return light;
  20452. }
  20453. var camera = this.getCameraByName(name);
  20454. if (camera) {
  20455. return camera;
  20456. }
  20457. var bone = this.getBoneByName(name);
  20458. return bone;
  20459. };
  20460. Scene.prototype.getMeshByName = function (name) {
  20461. for (var index = 0; index < this.meshes.length; index++) {
  20462. if (this.meshes[index].name === name) {
  20463. return this.meshes[index];
  20464. }
  20465. }
  20466. return null;
  20467. };
  20468. Scene.prototype.getSoundByName = function (name) {
  20469. var index;
  20470. if (BABYLON.AudioEngine) {
  20471. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20472. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20473. return this.mainSoundTrack.soundCollection[index];
  20474. }
  20475. }
  20476. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20477. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20478. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20479. return this.soundTracks[sdIndex].soundCollection[index];
  20480. }
  20481. }
  20482. }
  20483. }
  20484. return null;
  20485. };
  20486. Scene.prototype.getLastSkeletonByID = function (id) {
  20487. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20488. if (this.skeletons[index].id === id) {
  20489. return this.skeletons[index];
  20490. }
  20491. }
  20492. return null;
  20493. };
  20494. Scene.prototype.getSkeletonById = function (id) {
  20495. for (var index = 0; index < this.skeletons.length; index++) {
  20496. if (this.skeletons[index].id === id) {
  20497. return this.skeletons[index];
  20498. }
  20499. }
  20500. return null;
  20501. };
  20502. Scene.prototype.getSkeletonByName = function (name) {
  20503. for (var index = 0; index < this.skeletons.length; index++) {
  20504. if (this.skeletons[index].name === name) {
  20505. return this.skeletons[index];
  20506. }
  20507. }
  20508. return null;
  20509. };
  20510. Scene.prototype.isActiveMesh = function (mesh) {
  20511. return (this._activeMeshes.indexOf(mesh) !== -1);
  20512. };
  20513. Object.defineProperty(Scene.prototype, "uid", {
  20514. /**
  20515. * Return a unique id as a string which can serve as an identifier for the scene
  20516. */
  20517. get: function () {
  20518. if (!this._uid) {
  20519. this._uid = BABYLON.Tools.RandomId();
  20520. }
  20521. return this._uid;
  20522. },
  20523. enumerable: true,
  20524. configurable: true
  20525. });
  20526. /**
  20527. * Add an externaly attached data from its key.
  20528. * This method call will fail and return false, if such key already exists.
  20529. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20530. * @param key the unique key that identifies the data
  20531. * @param data the data object to associate to the key for this Engine instance
  20532. * @return true if no such key were already present and the data was added successfully, false otherwise
  20533. */
  20534. Scene.prototype.addExternalData = function (key, data) {
  20535. return this._externalData.add(key, data);
  20536. };
  20537. /**
  20538. * Get an externaly attached data from its key
  20539. * @param key the unique key that identifies the data
  20540. * @return the associated data, if present (can be null), or undefined if not present
  20541. */
  20542. Scene.prototype.getExternalData = function (key) {
  20543. return this._externalData.get(key);
  20544. };
  20545. /**
  20546. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20547. * @param key the unique key that identifies the data
  20548. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20549. * @return the associated data, can be null if the factory returned null.
  20550. */
  20551. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20552. return this._externalData.getOrAddWithFactory(key, factory);
  20553. };
  20554. /**
  20555. * Remove an externaly attached data from the Engine instance
  20556. * @param key the unique key that identifies the data
  20557. * @return true if the data was successfully removed, false if it doesn't exist
  20558. */
  20559. Scene.prototype.removeExternalData = function (key) {
  20560. return this._externalData.remove(key);
  20561. };
  20562. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20563. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20564. var material = subMesh.getMaterial();
  20565. if (mesh.showSubMeshesBoundingBox) {
  20566. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  20567. }
  20568. if (material) {
  20569. // Render targets
  20570. if (material.getRenderTargetTextures) {
  20571. if (this._processedMaterials.indexOf(material) === -1) {
  20572. this._processedMaterials.push(material);
  20573. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20574. }
  20575. }
  20576. // Dispatch
  20577. this._activeIndices.addCount(subMesh.indexCount, false);
  20578. this._renderingManager.dispatch(subMesh);
  20579. }
  20580. }
  20581. };
  20582. Scene.prototype._isInIntermediateRendering = function () {
  20583. return this._intermediateRendering;
  20584. };
  20585. Scene.prototype._evaluateActiveMeshes = function () {
  20586. this.activeCamera._activeMeshes.reset();
  20587. this._activeMeshes.reset();
  20588. this._renderingManager.reset();
  20589. this._processedMaterials.reset();
  20590. this._activeParticleSystems.reset();
  20591. this._activeSkeletons.reset();
  20592. this._softwareSkinnedMeshes.reset();
  20593. this._boundingBoxRenderer.reset();
  20594. this._edgesRenderers.reset();
  20595. // Meshes
  20596. var meshes;
  20597. var len;
  20598. if (this._selectionOctree) {
  20599. var selection = this._selectionOctree.select(this._frustumPlanes);
  20600. meshes = selection.data;
  20601. len = selection.length;
  20602. }
  20603. else {
  20604. len = this.meshes.length;
  20605. meshes = this.meshes;
  20606. }
  20607. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20608. var mesh = meshes[meshIndex];
  20609. if (mesh.isBlocked) {
  20610. continue;
  20611. }
  20612. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20613. if (!mesh.isReady() || !mesh.isEnabled()) {
  20614. continue;
  20615. }
  20616. mesh.computeWorldMatrix();
  20617. // Intersections
  20618. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20619. this._meshesForIntersections.pushNoDuplicate(mesh);
  20620. }
  20621. // Switch to current LOD
  20622. var meshLOD = mesh.getLOD(this.activeCamera);
  20623. if (!meshLOD) {
  20624. continue;
  20625. }
  20626. mesh._preActivate();
  20627. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20628. this._activeMeshes.push(mesh);
  20629. this.activeCamera._activeMeshes.push(mesh);
  20630. mesh._activate(this._renderId);
  20631. this._activeMesh(mesh, meshLOD);
  20632. }
  20633. }
  20634. // Particle systems
  20635. this._particlesDuration.beginMonitoring();
  20636. var beforeParticlesDate = BABYLON.Tools.Now;
  20637. if (this.particlesEnabled) {
  20638. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  20639. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20640. var particleSystem = this.particleSystems[particleIndex];
  20641. if (!particleSystem.isStarted()) {
  20642. continue;
  20643. }
  20644. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  20645. this._activeParticleSystems.push(particleSystem);
  20646. particleSystem.animate();
  20647. this._renderingManager.dispatchParticles(particleSystem);
  20648. }
  20649. }
  20650. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  20651. }
  20652. this._particlesDuration.endMonitoring(false);
  20653. };
  20654. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20655. if (mesh.skeleton && this.skeletonsEnabled) {
  20656. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20657. mesh.skeleton.prepare();
  20658. }
  20659. if (!mesh.computeBonesUsingShaders) {
  20660. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20661. }
  20662. }
  20663. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20664. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  20665. }
  20666. if (sourceMesh._edgesRenderer) {
  20667. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  20668. }
  20669. if (mesh && mesh.subMeshes) {
  20670. // Submeshes Octrees
  20671. var len;
  20672. var subMeshes;
  20673. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20674. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20675. len = intersections.length;
  20676. subMeshes = intersections.data;
  20677. }
  20678. else {
  20679. subMeshes = mesh.subMeshes;
  20680. len = subMeshes.length;
  20681. }
  20682. for (var subIndex = 0; subIndex < len; subIndex++) {
  20683. var subMesh = subMeshes[subIndex];
  20684. this._evaluateSubMesh(subMesh, mesh);
  20685. }
  20686. }
  20687. };
  20688. Scene.prototype.updateTransformMatrix = function (force) {
  20689. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20690. };
  20691. Scene.prototype._renderForCamera = function (camera) {
  20692. var engine = this._engine;
  20693. var startTime = BABYLON.Tools.Now;
  20694. this.activeCamera = camera;
  20695. if (!this.activeCamera)
  20696. throw new Error("Active camera not set");
  20697. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20698. // Viewport
  20699. engine.setViewport(this.activeCamera.viewport);
  20700. // Camera
  20701. this.resetCachedMaterial();
  20702. this._renderId++;
  20703. this.updateTransformMatrix();
  20704. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20705. // Meshes
  20706. this._evaluateActiveMeshesDuration.beginMonitoring();
  20707. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  20708. this._evaluateActiveMeshes();
  20709. this._evaluateActiveMeshesDuration.endMonitoring(false);
  20710. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  20711. // Software skinning
  20712. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20713. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20714. mesh.applySkeleton(mesh.skeleton);
  20715. }
  20716. // Render targets
  20717. this._renderTargetsDuration.beginMonitoring();
  20718. var needsRestoreFrameBuffer = false;
  20719. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20720. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20721. this._intermediateRendering = true;
  20722. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20723. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20724. var renderTarget = this._renderTargets.data[renderIndex];
  20725. if (renderTarget._shouldRender()) {
  20726. this._renderId++;
  20727. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20728. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20729. }
  20730. }
  20731. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20732. this._intermediateRendering = false;
  20733. this._renderId++;
  20734. needsRestoreFrameBuffer = true; // Restore back buffer
  20735. }
  20736. // Render HighlightLayer Texture
  20737. var stencilState = this._engine.getStencilBuffer();
  20738. var renderhighlights = false;
  20739. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20740. this._intermediateRendering = true;
  20741. for (var i = 0; i < this.highlightLayers.length; i++) {
  20742. var highlightLayer = this.highlightLayers[i];
  20743. if (highlightLayer.shouldRender() &&
  20744. (!highlightLayer.camera ||
  20745. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20746. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20747. renderhighlights = true;
  20748. var renderTarget = highlightLayer._mainTexture;
  20749. if (renderTarget._shouldRender()) {
  20750. this._renderId++;
  20751. renderTarget.render(false, false);
  20752. needsRestoreFrameBuffer = true;
  20753. }
  20754. }
  20755. }
  20756. this._intermediateRendering = false;
  20757. this._renderId++;
  20758. }
  20759. if (needsRestoreFrameBuffer) {
  20760. engine.restoreDefaultFramebuffer();
  20761. }
  20762. this._renderTargetsDuration.endMonitoring(false);
  20763. // Prepare Frame
  20764. this.postProcessManager._prepareFrame();
  20765. this._renderDuration.beginMonitoring();
  20766. // Backgrounds
  20767. var layerIndex;
  20768. var layer;
  20769. if (this.layers.length) {
  20770. engine.setDepthBuffer(false);
  20771. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20772. layer = this.layers[layerIndex];
  20773. if (layer.isBackground) {
  20774. layer.render();
  20775. }
  20776. }
  20777. engine.setDepthBuffer(true);
  20778. }
  20779. // Render
  20780. BABYLON.Tools.StartPerformanceCounter("Main render");
  20781. // Activate HighlightLayer stencil
  20782. if (renderhighlights) {
  20783. this._engine.setStencilBuffer(true);
  20784. }
  20785. this._renderingManager.render(null, null, true, true);
  20786. // Restore HighlightLayer stencil
  20787. if (renderhighlights) {
  20788. this._engine.setStencilBuffer(stencilState);
  20789. }
  20790. BABYLON.Tools.EndPerformanceCounter("Main render");
  20791. // Bounding boxes
  20792. this._boundingBoxRenderer.render();
  20793. // Edges
  20794. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20795. this._edgesRenderers.data[edgesRendererIndex].render();
  20796. }
  20797. // Lens flares
  20798. if (this.lensFlaresEnabled) {
  20799. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20800. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20801. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20802. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20803. lensFlareSystem.render();
  20804. }
  20805. }
  20806. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20807. }
  20808. // Foregrounds
  20809. if (this.layers.length) {
  20810. engine.setDepthBuffer(false);
  20811. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20812. layer = this.layers[layerIndex];
  20813. if (!layer.isBackground) {
  20814. layer.render();
  20815. }
  20816. }
  20817. engine.setDepthBuffer(true);
  20818. }
  20819. // Highlight Layer
  20820. if (renderhighlights) {
  20821. engine.setDepthBuffer(false);
  20822. for (var i = 0; i < this.highlightLayers.length; i++) {
  20823. if (this.highlightLayers[i].shouldRender()) {
  20824. this.highlightLayers[i].render();
  20825. }
  20826. }
  20827. engine.setDepthBuffer(true);
  20828. }
  20829. this._renderDuration.endMonitoring(false);
  20830. // Finalize frame
  20831. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20832. // Update camera
  20833. this.activeCamera._updateFromScene();
  20834. // Reset some special arrays
  20835. this._renderTargets.reset();
  20836. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20837. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20838. };
  20839. Scene.prototype._processSubCameras = function (camera) {
  20840. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20841. this._renderForCamera(camera);
  20842. return;
  20843. }
  20844. // rig cameras
  20845. for (var index = 0; index < camera._rigCameras.length; index++) {
  20846. this._renderForCamera(camera._rigCameras[index]);
  20847. }
  20848. this.activeCamera = camera;
  20849. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20850. // Update camera
  20851. this.activeCamera._updateFromScene();
  20852. };
  20853. Scene.prototype._checkIntersections = function () {
  20854. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20855. var sourceMesh = this._meshesForIntersections.data[index];
  20856. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20857. var action = sourceMesh.actionManager.actions[actionIndex];
  20858. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20859. var parameters = action.getTriggerParameter();
  20860. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20861. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20862. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20863. if (areIntersecting && currentIntersectionInProgress === -1) {
  20864. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20865. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20866. sourceMesh._intersectionsInProgress.push(otherMesh);
  20867. }
  20868. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20869. sourceMesh._intersectionsInProgress.push(otherMesh);
  20870. }
  20871. }
  20872. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20873. //They intersected, and now they don't.
  20874. //is this trigger an exit trigger? execute an event.
  20875. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20876. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20877. }
  20878. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20879. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20880. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20881. }
  20882. }
  20883. }
  20884. }
  20885. }
  20886. };
  20887. Scene.prototype.render = function () {
  20888. this._lastFrameDuration.beginMonitoring();
  20889. this._particlesDuration.fetchNewFrame();
  20890. this._spritesDuration.fetchNewFrame();
  20891. this._activeParticles.fetchNewFrame();
  20892. this._renderDuration.fetchNewFrame();
  20893. this._renderTargetsDuration.fetchNewFrame();
  20894. this._evaluateActiveMeshesDuration.fetchNewFrame();
  20895. this._totalVertices.fetchNewFrame();
  20896. this._activeIndices.fetchNewFrame();
  20897. this._activeBones.fetchNewFrame();
  20898. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  20899. this._meshesForIntersections.reset();
  20900. this.resetCachedMaterial();
  20901. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  20902. // Actions
  20903. if (this.actionManager) {
  20904. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  20905. }
  20906. //Simplification Queue
  20907. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20908. this.simplificationQueue.executeNext();
  20909. }
  20910. // Animations
  20911. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20912. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20913. this._animate();
  20914. // Physics
  20915. if (this._physicsEngine) {
  20916. BABYLON.Tools.StartPerformanceCounter("Physics");
  20917. this._physicsEngine._step(deltaTime / 1000.0);
  20918. BABYLON.Tools.EndPerformanceCounter("Physics");
  20919. }
  20920. // Before render
  20921. this.onBeforeRenderObservable.notifyObservers(this);
  20922. // Customs render targets
  20923. this._renderTargetsDuration.beginMonitoring();
  20924. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20925. var engine = this.getEngine();
  20926. var currentActiveCamera = this.activeCamera;
  20927. if (this.renderTargetsEnabled) {
  20928. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20929. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20930. var renderTarget = this.customRenderTargets[customIndex];
  20931. if (renderTarget._shouldRender()) {
  20932. this._renderId++;
  20933. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20934. if (!this.activeCamera)
  20935. throw new Error("Active camera not set");
  20936. // Viewport
  20937. engine.setViewport(this.activeCamera.viewport);
  20938. // Camera
  20939. this.updateTransformMatrix();
  20940. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20941. }
  20942. }
  20943. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20944. this._renderId++;
  20945. }
  20946. if (this.customRenderTargets.length > 0) {
  20947. engine.restoreDefaultFramebuffer();
  20948. }
  20949. this._renderTargetsDuration.endMonitoring();
  20950. this.activeCamera = currentActiveCamera;
  20951. // Procedural textures
  20952. if (this.proceduralTexturesEnabled) {
  20953. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20954. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20955. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20956. if (proceduralTexture._shouldRender()) {
  20957. proceduralTexture.render();
  20958. }
  20959. }
  20960. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20961. }
  20962. // Clear
  20963. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  20964. // Shadows
  20965. if (this.shadowsEnabled) {
  20966. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20967. var light = this.lights[lightIndex];
  20968. var shadowGenerator = light.getShadowGenerator();
  20969. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  20970. this._renderTargets.push(shadowGenerator.getShadowMap());
  20971. }
  20972. }
  20973. }
  20974. // Depth renderer
  20975. if (this._depthRenderer) {
  20976. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20977. }
  20978. // RenderPipeline
  20979. this.postProcessRenderPipelineManager.update();
  20980. // Multi-cameras?
  20981. if (this.activeCameras.length > 0) {
  20982. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20983. if (cameraIndex > 0) {
  20984. this._engine.clear(null, false, true, true);
  20985. }
  20986. this._processSubCameras(this.activeCameras[cameraIndex]);
  20987. }
  20988. }
  20989. else {
  20990. if (!this.activeCamera) {
  20991. throw new Error("No camera defined");
  20992. }
  20993. this._processSubCameras(this.activeCamera);
  20994. }
  20995. // Intersection checks
  20996. this._checkIntersections();
  20997. // Update the audio listener attached to the camera
  20998. if (BABYLON.AudioEngine) {
  20999. this._updateAudioParameters();
  21000. }
  21001. // After render
  21002. if (this.afterRender) {
  21003. this.afterRender();
  21004. }
  21005. this.onAfterRenderObservable.notifyObservers(this);
  21006. // Cleaning
  21007. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21008. this._toBeDisposed.data[index].dispose();
  21009. this._toBeDisposed[index] = null;
  21010. }
  21011. this._toBeDisposed.reset();
  21012. if (this.dumpNextRenderTargets) {
  21013. this.dumpNextRenderTargets = false;
  21014. }
  21015. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21016. this._lastFrameDuration.endMonitoring();
  21017. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21018. this._totalLightsCounter.addCount(this.lights.length, true);
  21019. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21020. this._totalTexturesCounter.addCount(this.textures.length, true);
  21021. this._activeBones.addCount(0, true);
  21022. this._activeIndices.addCount(0, true);
  21023. this._activeParticles.addCount(0, true);
  21024. };
  21025. Scene.prototype._updateAudioParameters = function () {
  21026. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21027. return;
  21028. }
  21029. var listeningCamera;
  21030. var audioEngine = BABYLON.Engine.audioEngine;
  21031. if (this.activeCameras.length > 0) {
  21032. listeningCamera = this.activeCameras[0];
  21033. }
  21034. else {
  21035. listeningCamera = this.activeCamera;
  21036. }
  21037. if (listeningCamera && audioEngine.canUseWebAudio) {
  21038. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21039. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21040. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21041. cameraDirection.normalize();
  21042. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21043. var i;
  21044. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21045. var sound = this.mainSoundTrack.soundCollection[i];
  21046. if (sound.useCustomAttenuation) {
  21047. sound.updateDistanceFromListener();
  21048. }
  21049. }
  21050. for (i = 0; i < this.soundTracks.length; i++) {
  21051. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21052. sound = this.soundTracks[i].soundCollection[j];
  21053. if (sound.useCustomAttenuation) {
  21054. sound.updateDistanceFromListener();
  21055. }
  21056. }
  21057. }
  21058. }
  21059. };
  21060. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21061. // Audio
  21062. get: function () {
  21063. return this._audioEnabled;
  21064. },
  21065. set: function (value) {
  21066. this._audioEnabled = value;
  21067. if (BABYLON.AudioEngine) {
  21068. if (this._audioEnabled) {
  21069. this._enableAudio();
  21070. }
  21071. else {
  21072. this._disableAudio();
  21073. }
  21074. }
  21075. },
  21076. enumerable: true,
  21077. configurable: true
  21078. });
  21079. Scene.prototype._disableAudio = function () {
  21080. var i;
  21081. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21082. this.mainSoundTrack.soundCollection[i].pause();
  21083. }
  21084. for (i = 0; i < this.soundTracks.length; i++) {
  21085. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21086. this.soundTracks[i].soundCollection[j].pause();
  21087. }
  21088. }
  21089. };
  21090. Scene.prototype._enableAudio = function () {
  21091. var i;
  21092. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21093. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21094. this.mainSoundTrack.soundCollection[i].play();
  21095. }
  21096. }
  21097. for (i = 0; i < this.soundTracks.length; i++) {
  21098. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21099. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21100. this.soundTracks[i].soundCollection[j].play();
  21101. }
  21102. }
  21103. }
  21104. };
  21105. Object.defineProperty(Scene.prototype, "headphone", {
  21106. get: function () {
  21107. return this._headphone;
  21108. },
  21109. set: function (value) {
  21110. this._headphone = value;
  21111. if (BABYLON.AudioEngine) {
  21112. if (this._headphone) {
  21113. this._switchAudioModeForHeadphones();
  21114. }
  21115. else {
  21116. this._switchAudioModeForNormalSpeakers();
  21117. }
  21118. }
  21119. },
  21120. enumerable: true,
  21121. configurable: true
  21122. });
  21123. Scene.prototype._switchAudioModeForHeadphones = function () {
  21124. this.mainSoundTrack.switchPanningModelToHRTF();
  21125. for (var i = 0; i < this.soundTracks.length; i++) {
  21126. this.soundTracks[i].switchPanningModelToHRTF();
  21127. }
  21128. };
  21129. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21130. this.mainSoundTrack.switchPanningModelToEqualPower();
  21131. for (var i = 0; i < this.soundTracks.length; i++) {
  21132. this.soundTracks[i].switchPanningModelToEqualPower();
  21133. }
  21134. };
  21135. Scene.prototype.enableDepthRenderer = function () {
  21136. if (this._depthRenderer) {
  21137. return this._depthRenderer;
  21138. }
  21139. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21140. return this._depthRenderer;
  21141. };
  21142. Scene.prototype.disableDepthRenderer = function () {
  21143. if (!this._depthRenderer) {
  21144. return;
  21145. }
  21146. this._depthRenderer.dispose();
  21147. this._depthRenderer = null;
  21148. };
  21149. Scene.prototype.freezeMaterials = function () {
  21150. for (var i = 0; i < this.materials.length; i++) {
  21151. this.materials[i].freeze();
  21152. }
  21153. };
  21154. Scene.prototype.unfreezeMaterials = function () {
  21155. for (var i = 0; i < this.materials.length; i++) {
  21156. this.materials[i].unfreeze();
  21157. }
  21158. };
  21159. Scene.prototype.dispose = function () {
  21160. this.beforeRender = null;
  21161. this.afterRender = null;
  21162. this.skeletons = [];
  21163. this._boundingBoxRenderer.dispose();
  21164. if (this._depthRenderer) {
  21165. this._depthRenderer.dispose();
  21166. }
  21167. // Debug layer
  21168. if (this._debugLayer) {
  21169. this._debugLayer.hide();
  21170. }
  21171. // Events
  21172. this.onDisposeObservable.notifyObservers(this);
  21173. this.onDisposeObservable.clear();
  21174. this.onBeforeRenderObservable.clear();
  21175. this.onAfterRenderObservable.clear();
  21176. this.detachControl();
  21177. // Release sounds & sounds tracks
  21178. if (BABYLON.AudioEngine) {
  21179. this.disposeSounds();
  21180. }
  21181. // Detach cameras
  21182. var canvas = this._engine.getRenderingCanvas();
  21183. var index;
  21184. for (index = 0; index < this.cameras.length; index++) {
  21185. this.cameras[index].detachControl(canvas);
  21186. }
  21187. // Release lights
  21188. while (this.lights.length) {
  21189. this.lights[0].dispose();
  21190. }
  21191. // Release meshes
  21192. while (this.meshes.length) {
  21193. this.meshes[0].dispose(true);
  21194. }
  21195. // Release cameras
  21196. while (this.cameras.length) {
  21197. this.cameras[0].dispose();
  21198. }
  21199. // Release materials
  21200. while (this.materials.length) {
  21201. this.materials[0].dispose();
  21202. }
  21203. // Release particles
  21204. while (this.particleSystems.length) {
  21205. this.particleSystems[0].dispose();
  21206. }
  21207. // Release sprites
  21208. while (this.spriteManagers.length) {
  21209. this.spriteManagers[0].dispose();
  21210. }
  21211. // Release layers
  21212. while (this.layers.length) {
  21213. this.layers[0].dispose();
  21214. }
  21215. while (this.highlightLayers.length) {
  21216. this.highlightLayers[0].dispose();
  21217. }
  21218. // Release textures
  21219. while (this.textures.length) {
  21220. this.textures[0].dispose();
  21221. }
  21222. // Post-processes
  21223. this.postProcessManager.dispose();
  21224. // Physics
  21225. if (this._physicsEngine) {
  21226. this.disablePhysicsEngine();
  21227. }
  21228. // Remove from engine
  21229. index = this._engine.scenes.indexOf(this);
  21230. if (index > -1) {
  21231. this._engine.scenes.splice(index, 1);
  21232. }
  21233. this._engine.wipeCaches();
  21234. };
  21235. // Release sounds & sounds tracks
  21236. Scene.prototype.disposeSounds = function () {
  21237. this.mainSoundTrack.dispose();
  21238. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21239. this.soundTracks[scIndex].dispose();
  21240. }
  21241. };
  21242. // Octrees
  21243. Scene.prototype.getWorldExtends = function () {
  21244. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21245. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21246. for (var index = 0; index < this.meshes.length; index++) {
  21247. var mesh = this.meshes[index];
  21248. mesh.computeWorldMatrix(true);
  21249. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21250. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21251. BABYLON.Tools.CheckExtends(minBox, min, max);
  21252. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21253. }
  21254. return {
  21255. min: min,
  21256. max: max
  21257. };
  21258. };
  21259. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21260. if (maxCapacity === void 0) { maxCapacity = 64; }
  21261. if (maxDepth === void 0) { maxDepth = 2; }
  21262. if (!this._selectionOctree) {
  21263. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21264. }
  21265. var worldExtends = this.getWorldExtends();
  21266. // Update octree
  21267. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21268. return this._selectionOctree;
  21269. };
  21270. // Picking
  21271. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21272. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21273. var engine = this._engine;
  21274. if (!camera) {
  21275. if (!this.activeCamera)
  21276. throw new Error("Active camera not set");
  21277. camera = this.activeCamera;
  21278. }
  21279. var cameraViewport = camera.viewport;
  21280. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21281. // Moving coordinates to local viewport world
  21282. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21283. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21284. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21285. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21286. };
  21287. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21288. var engine = this._engine;
  21289. if (!camera) {
  21290. if (!this.activeCamera)
  21291. throw new Error("Active camera not set");
  21292. camera = this.activeCamera;
  21293. }
  21294. var cameraViewport = camera.viewport;
  21295. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21296. var identity = BABYLON.Matrix.Identity();
  21297. // Moving coordinates to local viewport world
  21298. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21299. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21300. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21301. };
  21302. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21303. var pickingInfo = null;
  21304. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21305. var mesh = this.meshes[meshIndex];
  21306. if (predicate) {
  21307. if (!predicate(mesh)) {
  21308. continue;
  21309. }
  21310. }
  21311. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21312. continue;
  21313. }
  21314. var world = mesh.getWorldMatrix();
  21315. var ray = rayFunction(world);
  21316. var result = mesh.intersects(ray, fastCheck);
  21317. if (!result || !result.hit)
  21318. continue;
  21319. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21320. continue;
  21321. pickingInfo = result;
  21322. if (fastCheck) {
  21323. break;
  21324. }
  21325. }
  21326. return pickingInfo || new BABYLON.PickingInfo();
  21327. };
  21328. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21329. var pickingInfos = new Array();
  21330. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21331. var mesh = this.meshes[meshIndex];
  21332. if (predicate) {
  21333. if (!predicate(mesh)) {
  21334. continue;
  21335. }
  21336. }
  21337. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21338. continue;
  21339. }
  21340. var world = mesh.getWorldMatrix();
  21341. var ray = rayFunction(world);
  21342. var result = mesh.intersects(ray, false);
  21343. if (!result || !result.hit)
  21344. continue;
  21345. pickingInfos.push(result);
  21346. }
  21347. return pickingInfos;
  21348. };
  21349. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21350. var pickingInfo = null;
  21351. camera = camera || this.activeCamera;
  21352. if (this.spriteManagers.length > 0) {
  21353. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21354. var spriteManager = this.spriteManagers[spriteIndex];
  21355. if (!spriteManager.isPickable) {
  21356. continue;
  21357. }
  21358. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21359. if (!result || !result.hit)
  21360. continue;
  21361. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21362. continue;
  21363. pickingInfo = result;
  21364. if (fastCheck) {
  21365. break;
  21366. }
  21367. }
  21368. }
  21369. return pickingInfo || new BABYLON.PickingInfo();
  21370. };
  21371. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21372. /// <param name="x">X position on screen</param>
  21373. /// <param name="y">Y position on screen</param>
  21374. /// <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>
  21375. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21376. /// <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>
  21377. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21378. var _this = this;
  21379. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  21380. };
  21381. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21382. /// <param name="x">X position on screen</param>
  21383. /// <param name="y">Y position on screen</param>
  21384. /// <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>
  21385. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21386. /// <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>
  21387. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21388. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  21389. };
  21390. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21391. var _this = this;
  21392. return this._internalPick(function (world) {
  21393. if (!_this._pickWithRayInverseMatrix) {
  21394. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21395. }
  21396. world.invertToRef(_this._pickWithRayInverseMatrix);
  21397. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21398. }, predicate, fastCheck);
  21399. };
  21400. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21401. /// <param name="x">X position on screen</param>
  21402. /// <param name="y">Y position on screen</param>
  21403. /// <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>
  21404. /// <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>
  21405. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21406. var _this = this;
  21407. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  21408. };
  21409. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21410. /// <param name="ray">Ray to use</param>
  21411. /// <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>
  21412. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21413. var _this = this;
  21414. return this._internalMultiPick(function (world) {
  21415. if (!_this._pickWithRayInverseMatrix) {
  21416. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21417. }
  21418. world.invertToRef(_this._pickWithRayInverseMatrix);
  21419. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21420. }, predicate);
  21421. };
  21422. Scene.prototype.setPointerOverMesh = function (mesh) {
  21423. if (this._pointerOverMesh === mesh) {
  21424. return;
  21425. }
  21426. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21427. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21428. }
  21429. this._pointerOverMesh = mesh;
  21430. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21431. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21432. }
  21433. };
  21434. Scene.prototype.getPointerOverMesh = function () {
  21435. return this._pointerOverMesh;
  21436. };
  21437. Scene.prototype.setPointerOverSprite = function (sprite) {
  21438. if (this._pointerOverSprite === sprite) {
  21439. return;
  21440. }
  21441. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21442. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21443. }
  21444. this._pointerOverSprite = sprite;
  21445. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21446. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21447. }
  21448. };
  21449. Scene.prototype.getPointerOverSprite = function () {
  21450. return this._pointerOverSprite;
  21451. };
  21452. // Physics
  21453. Scene.prototype.getPhysicsEngine = function () {
  21454. return this._physicsEngine;
  21455. };
  21456. /**
  21457. * Enables physics to the current scene
  21458. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21459. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21460. * @return {boolean} was the physics engine initialized
  21461. */
  21462. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21463. if (this._physicsEngine) {
  21464. return true;
  21465. }
  21466. try {
  21467. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21468. return true;
  21469. }
  21470. catch (e) {
  21471. BABYLON.Tools.Error(e.message);
  21472. return false;
  21473. }
  21474. };
  21475. Scene.prototype.disablePhysicsEngine = function () {
  21476. if (!this._physicsEngine) {
  21477. return;
  21478. }
  21479. this._physicsEngine.dispose();
  21480. this._physicsEngine = undefined;
  21481. };
  21482. Scene.prototype.isPhysicsEnabled = function () {
  21483. return this._physicsEngine !== undefined;
  21484. };
  21485. /**
  21486. *
  21487. * Sets the gravity of the physics engine (and NOT of the scene)
  21488. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  21489. */
  21490. Scene.prototype.setGravity = function (gravity) {
  21491. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  21492. if (!this._physicsEngine) {
  21493. return;
  21494. }
  21495. this._physicsEngine.setGravity(gravity);
  21496. };
  21497. /**
  21498. * Legacy support, using the new API
  21499. * @Deprecated
  21500. */
  21501. Scene.prototype.createCompoundImpostor = function (parts, options) {
  21502. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  21503. if (parts.parts) {
  21504. options = parts;
  21505. parts = parts.parts;
  21506. }
  21507. var mainMesh = parts[0].mesh;
  21508. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  21509. for (var index = 1; index < parts.length; index++) {
  21510. var mesh = parts[index].mesh;
  21511. if (mesh.parent !== mainMesh) {
  21512. mesh.position = mesh.position.subtract(mainMesh.position);
  21513. mesh.parent = mainMesh;
  21514. }
  21515. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  21516. }
  21517. mainMesh.physicsImpostor.forceUpdate();
  21518. };
  21519. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21520. var mesh = compound.parts[0].mesh;
  21521. mesh.physicsImpostor.dispose();
  21522. mesh.physicsImpostor = null;
  21523. };
  21524. // Misc.
  21525. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  21526. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21527. // Light
  21528. if (this.lights.length === 0) {
  21529. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21530. }
  21531. // Camera
  21532. if (!this.activeCamera) {
  21533. // Compute position
  21534. var worldExtends = this.getWorldExtends();
  21535. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  21536. var camera;
  21537. if (createArcRotateCamera) {
  21538. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  21539. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  21540. camera.setTarget(worldCenter);
  21541. }
  21542. else {
  21543. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  21544. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  21545. camera.setTarget(worldCenter);
  21546. }
  21547. this.activeCamera = camera;
  21548. }
  21549. };
  21550. // Tags
  21551. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21552. if (tagsQuery === undefined) {
  21553. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21554. return list;
  21555. }
  21556. var listByTags = [];
  21557. forEach = forEach || (function (item) { return; });
  21558. for (var i in list) {
  21559. var item = list[i];
  21560. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21561. listByTags.push(item);
  21562. forEach(item);
  21563. }
  21564. }
  21565. return listByTags;
  21566. };
  21567. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21568. return this._getByTags(this.meshes, tagsQuery, forEach);
  21569. };
  21570. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21571. return this._getByTags(this.cameras, tagsQuery, forEach);
  21572. };
  21573. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21574. return this._getByTags(this.lights, tagsQuery, forEach);
  21575. };
  21576. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21577. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21578. };
  21579. /**
  21580. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21581. * This allowed control for front to back rendering or reversly depending of the special needs.
  21582. *
  21583. * @param renderingGroupId The rendering group id corresponding to its index
  21584. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21585. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21586. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21587. */
  21588. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21589. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21590. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21591. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21592. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21593. };
  21594. /**
  21595. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21596. *
  21597. * @param renderingGroupId The rendering group id corresponding to its index
  21598. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21599. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21600. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21601. */
  21602. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21603. if (depth === void 0) { depth = true; }
  21604. if (stencil === void 0) { stencil = true; }
  21605. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21606. };
  21607. return Scene;
  21608. }());
  21609. // Statics
  21610. Scene._FOGMODE_NONE = 0;
  21611. Scene._FOGMODE_EXP = 1;
  21612. Scene._FOGMODE_EXP2 = 2;
  21613. Scene._FOGMODE_LINEAR = 3;
  21614. Scene.MinDeltaTime = 1.0;
  21615. Scene.MaxDeltaTime = 1000.0;
  21616. BABYLON.Scene = Scene;
  21617. })(BABYLON || (BABYLON = {}));
  21618. //# sourceMappingURL=babylon.scene.js.map
  21619. var BABYLON;
  21620. (function (BABYLON) {
  21621. var Buffer = (function () {
  21622. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21623. if (engine instanceof BABYLON.Mesh) {
  21624. this._engine = engine.getScene().getEngine();
  21625. }
  21626. else {
  21627. this._engine = engine;
  21628. }
  21629. this._updatable = updatable;
  21630. this._data = data;
  21631. this._strideSize = stride;
  21632. if (!postponeInternalCreation) {
  21633. this.create();
  21634. }
  21635. this._instanced = instanced;
  21636. }
  21637. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21638. // a lot of these parameters are ignored as they are overriden by the buffer
  21639. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21640. };
  21641. // Properties
  21642. Buffer.prototype.isUpdatable = function () {
  21643. return this._updatable;
  21644. };
  21645. Buffer.prototype.getData = function () {
  21646. return this._data;
  21647. };
  21648. Buffer.prototype.getBuffer = function () {
  21649. return this._buffer;
  21650. };
  21651. Buffer.prototype.getStrideSize = function () {
  21652. return this._strideSize;
  21653. };
  21654. Buffer.prototype.getIsInstanced = function () {
  21655. return this._instanced;
  21656. };
  21657. // Methods
  21658. Buffer.prototype.create = function (data) {
  21659. if (!data && this._buffer) {
  21660. return; // nothing to do
  21661. }
  21662. data = data || this._data;
  21663. if (!this._buffer) {
  21664. if (this._updatable) {
  21665. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21666. this._data = data;
  21667. }
  21668. else {
  21669. this._buffer = this._engine.createVertexBuffer(data);
  21670. }
  21671. }
  21672. else if (this._updatable) {
  21673. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21674. this._data = data;
  21675. }
  21676. };
  21677. Buffer.prototype.update = function (data) {
  21678. this.create(data);
  21679. };
  21680. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21681. if (!this._buffer) {
  21682. return;
  21683. }
  21684. if (this._updatable) {
  21685. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21686. this._data = null;
  21687. }
  21688. };
  21689. Buffer.prototype.dispose = function () {
  21690. if (!this._buffer) {
  21691. return;
  21692. }
  21693. if (this._engine._releaseBuffer(this._buffer)) {
  21694. this._buffer = null;
  21695. }
  21696. };
  21697. return Buffer;
  21698. }());
  21699. BABYLON.Buffer = Buffer;
  21700. })(BABYLON || (BABYLON = {}));
  21701. //# sourceMappingURL=babylon.buffer.js.map
  21702. var BABYLON;
  21703. (function (BABYLON) {
  21704. var VertexBuffer = (function () {
  21705. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21706. if (!stride) {
  21707. // Deduce stride from kind
  21708. switch (kind) {
  21709. case VertexBuffer.PositionKind:
  21710. stride = 3;
  21711. break;
  21712. case VertexBuffer.NormalKind:
  21713. stride = 3;
  21714. break;
  21715. case VertexBuffer.UVKind:
  21716. case VertexBuffer.UV2Kind:
  21717. case VertexBuffer.UV3Kind:
  21718. case VertexBuffer.UV4Kind:
  21719. case VertexBuffer.UV5Kind:
  21720. case VertexBuffer.UV6Kind:
  21721. stride = 2;
  21722. break;
  21723. case VertexBuffer.ColorKind:
  21724. stride = 4;
  21725. break;
  21726. case VertexBuffer.MatricesIndicesKind:
  21727. case VertexBuffer.MatricesIndicesExtraKind:
  21728. stride = 4;
  21729. break;
  21730. case VertexBuffer.MatricesWeightsKind:
  21731. case VertexBuffer.MatricesWeightsExtraKind:
  21732. stride = 4;
  21733. break;
  21734. }
  21735. }
  21736. if (data instanceof BABYLON.Buffer) {
  21737. if (!stride) {
  21738. stride = data.getStrideSize();
  21739. }
  21740. this._buffer = data;
  21741. this._ownsBuffer = false;
  21742. }
  21743. else {
  21744. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21745. this._ownsBuffer = true;
  21746. }
  21747. this._stride = stride;
  21748. this._offset = offset ? offset : 0;
  21749. this._size = size ? size : stride;
  21750. this._kind = kind;
  21751. }
  21752. /**
  21753. * Returns the kind of the VertexBuffer (string).
  21754. */
  21755. VertexBuffer.prototype.getKind = function () {
  21756. return this._kind;
  21757. };
  21758. // Properties
  21759. /**
  21760. * Boolean : is the VertexBuffer updatable ?
  21761. */
  21762. VertexBuffer.prototype.isUpdatable = function () {
  21763. return this._buffer.isUpdatable();
  21764. };
  21765. /**
  21766. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21767. */
  21768. VertexBuffer.prototype.getData = function () {
  21769. return this._buffer.getData();
  21770. };
  21771. /**
  21772. * Returns the WebGLBuffer associated to the VertexBuffer.
  21773. */
  21774. VertexBuffer.prototype.getBuffer = function () {
  21775. return this._buffer.getBuffer();
  21776. };
  21777. /**
  21778. * Returns the stride of the VertexBuffer (integer).
  21779. */
  21780. VertexBuffer.prototype.getStrideSize = function () {
  21781. return this._stride;
  21782. };
  21783. /**
  21784. * Returns the offset (integer).
  21785. */
  21786. VertexBuffer.prototype.getOffset = function () {
  21787. return this._offset;
  21788. };
  21789. /**
  21790. * Returns the VertexBuffer total size (integer).
  21791. */
  21792. VertexBuffer.prototype.getSize = function () {
  21793. return this._size;
  21794. };
  21795. /**
  21796. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21797. */
  21798. VertexBuffer.prototype.getIsInstanced = function () {
  21799. return this._buffer.getIsInstanced();
  21800. };
  21801. // Methods
  21802. /**
  21803. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21804. * Returns the created WebGLBuffer.
  21805. */
  21806. VertexBuffer.prototype.create = function (data) {
  21807. return this._buffer.create(data);
  21808. };
  21809. /**
  21810. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21811. * Returns the updated WebGLBuffer.
  21812. */
  21813. VertexBuffer.prototype.update = function (data) {
  21814. return this._buffer.update(data);
  21815. };
  21816. /**
  21817. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21818. * Returns the directly updated WebGLBuffer.
  21819. */
  21820. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21821. return this._buffer.updateDirectly(data, offset);
  21822. };
  21823. /**
  21824. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21825. */
  21826. VertexBuffer.prototype.dispose = function () {
  21827. if (this._ownsBuffer) {
  21828. this._buffer.dispose();
  21829. }
  21830. };
  21831. Object.defineProperty(VertexBuffer, "PositionKind", {
  21832. get: function () {
  21833. return VertexBuffer._PositionKind;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(VertexBuffer, "NormalKind", {
  21839. get: function () {
  21840. return VertexBuffer._NormalKind;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(VertexBuffer, "UVKind", {
  21846. get: function () {
  21847. return VertexBuffer._UVKind;
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21853. get: function () {
  21854. return VertexBuffer._UV2Kind;
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21860. get: function () {
  21861. return VertexBuffer._UV3Kind;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21867. get: function () {
  21868. return VertexBuffer._UV4Kind;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21874. get: function () {
  21875. return VertexBuffer._UV5Kind;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21881. get: function () {
  21882. return VertexBuffer._UV6Kind;
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(VertexBuffer, "ColorKind", {
  21888. get: function () {
  21889. return VertexBuffer._ColorKind;
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21895. get: function () {
  21896. return VertexBuffer._MatricesIndicesKind;
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21902. get: function () {
  21903. return VertexBuffer._MatricesWeightsKind;
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21909. get: function () {
  21910. return VertexBuffer._MatricesIndicesExtraKind;
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21916. get: function () {
  21917. return VertexBuffer._MatricesWeightsExtraKind;
  21918. },
  21919. enumerable: true,
  21920. configurable: true
  21921. });
  21922. return VertexBuffer;
  21923. }());
  21924. // Enums
  21925. VertexBuffer._PositionKind = "position";
  21926. VertexBuffer._NormalKind = "normal";
  21927. VertexBuffer._UVKind = "uv";
  21928. VertexBuffer._UV2Kind = "uv2";
  21929. VertexBuffer._UV3Kind = "uv3";
  21930. VertexBuffer._UV4Kind = "uv4";
  21931. VertexBuffer._UV5Kind = "uv5";
  21932. VertexBuffer._UV6Kind = "uv6";
  21933. VertexBuffer._ColorKind = "color";
  21934. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21935. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21936. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21937. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21938. BABYLON.VertexBuffer = VertexBuffer;
  21939. })(BABYLON || (BABYLON = {}));
  21940. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21941. var BABYLON;
  21942. (function (BABYLON) {
  21943. /**
  21944. * Creates an instance based on a source mesh.
  21945. */
  21946. var InstancedMesh = (function (_super) {
  21947. __extends(InstancedMesh, _super);
  21948. function InstancedMesh(name, source) {
  21949. var _this = _super.call(this, name, source.getScene()) || this;
  21950. source.instances.push(_this);
  21951. _this._sourceMesh = source;
  21952. _this.position.copyFrom(source.position);
  21953. _this.rotation.copyFrom(source.rotation);
  21954. _this.scaling.copyFrom(source.scaling);
  21955. if (source.rotationQuaternion) {
  21956. _this.rotationQuaternion = source.rotationQuaternion.clone();
  21957. }
  21958. _this.infiniteDistance = source.infiniteDistance;
  21959. _this.setPivotMatrix(source.getPivotMatrix());
  21960. _this.refreshBoundingInfo();
  21961. _this._syncSubMeshes();
  21962. return _this;
  21963. }
  21964. /**
  21965. * Returns the string "InstancedMesh".
  21966. */
  21967. InstancedMesh.prototype.getClassName = function () {
  21968. return "InstancedMesh";
  21969. };
  21970. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  21971. // Methods
  21972. get: function () {
  21973. return this._sourceMesh.receiveShadows;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Object.defineProperty(InstancedMesh.prototype, "material", {
  21979. get: function () {
  21980. return this._sourceMesh.material;
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  21986. get: function () {
  21987. return this._sourceMesh.visibility;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  21993. get: function () {
  21994. return this._sourceMesh.skeleton;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22000. get: function () {
  22001. return this._sourceMesh.renderingGroupId;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. /**
  22007. * Returns the total number of vertices (integer).
  22008. */
  22009. InstancedMesh.prototype.getTotalVertices = function () {
  22010. return this._sourceMesh.getTotalVertices();
  22011. };
  22012. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22013. get: function () {
  22014. return this._sourceMesh;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. /**
  22020. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22021. */
  22022. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22023. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22024. };
  22025. /**
  22026. * Boolean : True if the mesh owns the requested kind of data.
  22027. */
  22028. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22029. return this._sourceMesh.isVerticesDataPresent(kind);
  22030. };
  22031. /**
  22032. * Returns an array of indices (IndicesArray).
  22033. */
  22034. InstancedMesh.prototype.getIndices = function () {
  22035. return this._sourceMesh.getIndices();
  22036. };
  22037. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22038. get: function () {
  22039. return this._sourceMesh._positions;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. /**
  22045. * Sets a new updated BoundingInfo to the mesh.
  22046. * Returns the mesh.
  22047. */
  22048. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22049. var meshBB = this._sourceMesh.getBoundingInfo();
  22050. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22051. this._updateBoundingInfo();
  22052. return this;
  22053. };
  22054. InstancedMesh.prototype._preActivate = function () {
  22055. if (this._currentLOD) {
  22056. this._currentLOD._preActivate();
  22057. }
  22058. return this;
  22059. };
  22060. InstancedMesh.prototype._activate = function (renderId) {
  22061. if (this._currentLOD) {
  22062. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22063. }
  22064. return this;
  22065. };
  22066. /**
  22067. * Returns the current associated LOD AbstractMesh.
  22068. */
  22069. InstancedMesh.prototype.getLOD = function (camera) {
  22070. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22071. if (this._currentLOD === this.sourceMesh) {
  22072. return this;
  22073. }
  22074. return this._currentLOD;
  22075. };
  22076. InstancedMesh.prototype._syncSubMeshes = function () {
  22077. this.releaseSubMeshes();
  22078. if (this._sourceMesh.subMeshes) {
  22079. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22080. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22081. }
  22082. }
  22083. return this;
  22084. };
  22085. InstancedMesh.prototype._generatePointsArray = function () {
  22086. return this._sourceMesh._generatePointsArray();
  22087. };
  22088. /**
  22089. * Creates a new InstancedMesh from the current mesh.
  22090. * - name (string) : the cloned mesh name
  22091. * - newParent (optional Node) : the optional Node to parent the clone to.
  22092. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22093. *
  22094. * Returns the clone.
  22095. */
  22096. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22097. var result = this._sourceMesh.createInstance(name);
  22098. // Deep copy
  22099. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  22100. // Bounding info
  22101. this.refreshBoundingInfo();
  22102. // Parent
  22103. if (newParent) {
  22104. result.parent = newParent;
  22105. }
  22106. if (!doNotCloneChildren) {
  22107. // Children
  22108. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22109. var mesh = this.getScene().meshes[index];
  22110. if (mesh.parent === this) {
  22111. mesh.clone(mesh.name, result);
  22112. }
  22113. }
  22114. }
  22115. result.computeWorldMatrix(true);
  22116. return result;
  22117. };
  22118. /**
  22119. * Disposes the InstancedMesh.
  22120. * Returns nothing.
  22121. */
  22122. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22123. // Remove from mesh
  22124. var index = this._sourceMesh.instances.indexOf(this);
  22125. this._sourceMesh.instances.splice(index, 1);
  22126. _super.prototype.dispose.call(this, doNotRecurse);
  22127. };
  22128. return InstancedMesh;
  22129. }(BABYLON.AbstractMesh));
  22130. BABYLON.InstancedMesh = InstancedMesh;
  22131. })(BABYLON || (BABYLON = {}));
  22132. //# sourceMappingURL=babylon.instancedMesh.js.map
  22133. var BABYLON;
  22134. (function (BABYLON) {
  22135. var _InstancesBatch = (function () {
  22136. function _InstancesBatch() {
  22137. this.mustReturn = false;
  22138. this.visibleInstances = new Array();
  22139. this.renderSelf = new Array();
  22140. }
  22141. return _InstancesBatch;
  22142. }());
  22143. BABYLON._InstancesBatch = _InstancesBatch;
  22144. var Mesh = (function (_super) {
  22145. __extends(Mesh, _super);
  22146. /**
  22147. * @constructor
  22148. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22149. * @param {Scene} scene The scene to add this mesh to.
  22150. * @param {Node} parent The parent of this mesh, if it has one
  22151. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22152. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22153. * When false, achieved by calling a clone(), also passing False.
  22154. * This will make creation of children, recursive.
  22155. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22156. */
  22157. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22158. if (parent === void 0) { parent = null; }
  22159. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22160. var _this = _super.call(this, name, scene) || this;
  22161. // Events
  22162. /**
  22163. * An event triggered before rendering the mesh
  22164. * @type {BABYLON.Observable}
  22165. */
  22166. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22167. /**
  22168. * An event triggered after rendering the mesh
  22169. * @type {BABYLON.Observable}
  22170. */
  22171. _this.onAfterRenderObservable = new BABYLON.Observable();
  22172. /**
  22173. * An event triggered before drawing the mesh
  22174. * @type {BABYLON.Observable}
  22175. */
  22176. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22177. // Members
  22178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22179. _this.instances = new Array();
  22180. _this._LODLevels = new Array();
  22181. _this._visibleInstances = {};
  22182. _this._renderIdForInstances = new Array();
  22183. _this._batchCache = new _InstancesBatch();
  22184. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22185. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22186. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22187. // Will be used to save a source mesh reference, If any
  22188. _this._source = null;
  22189. if (source) {
  22190. // Source mesh
  22191. _this._source = source;
  22192. // Geometry
  22193. if (source._geometry) {
  22194. source._geometry.applyToMesh(_this);
  22195. }
  22196. // Deep copy
  22197. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  22198. // Parent
  22199. _this.parent = source.parent;
  22200. // Pivot
  22201. _this.setPivotMatrix(source.getPivotMatrix());
  22202. _this.id = name + "." + source.id;
  22203. // Material
  22204. _this.material = source.material;
  22205. var index;
  22206. if (!doNotCloneChildren) {
  22207. // Children
  22208. for (index = 0; index < scene.meshes.length; index++) {
  22209. var mesh = scene.meshes[index];
  22210. if (mesh.parent === source) {
  22211. // doNotCloneChildren is always going to be False
  22212. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22213. }
  22214. }
  22215. }
  22216. // Physics clone
  22217. var physicsEngine = _this.getScene().getPhysicsEngine();
  22218. if (clonePhysicsImpostor && physicsEngine) {
  22219. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22220. if (impostor) {
  22221. _this.physicsImpostor = impostor.clone(_this);
  22222. }
  22223. }
  22224. // Particles
  22225. for (index = 0; index < scene.particleSystems.length; index++) {
  22226. var system = scene.particleSystems[index];
  22227. if (system.emitter === source) {
  22228. system.clone(system.name, _this);
  22229. }
  22230. }
  22231. _this.computeWorldMatrix(true);
  22232. }
  22233. // Parent
  22234. if (parent !== null) {
  22235. _this.parent = parent;
  22236. }
  22237. return _this;
  22238. }
  22239. Object.defineProperty(Mesh, "FRONTSIDE", {
  22240. /**
  22241. * Mesh side orientation : usually the external or front surface
  22242. */
  22243. get: function () {
  22244. return Mesh._FRONTSIDE;
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Object.defineProperty(Mesh, "BACKSIDE", {
  22250. /**
  22251. * Mesh side orientation : usually the internal or back surface
  22252. */
  22253. get: function () {
  22254. return Mesh._BACKSIDE;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22260. /**
  22261. * Mesh side orientation : both internal and external or front and back surfaces
  22262. */
  22263. get: function () {
  22264. return Mesh._DOUBLESIDE;
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22270. /**
  22271. * Mesh side orientation : by default, `FRONTSIDE`
  22272. */
  22273. get: function () {
  22274. return Mesh._DEFAULTSIDE;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(Mesh, "NO_CAP", {
  22280. /**
  22281. * Mesh cap setting : no cap
  22282. */
  22283. get: function () {
  22284. return Mesh._NO_CAP;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Mesh, "CAP_START", {
  22290. /**
  22291. * Mesh cap setting : one cap at the beginning of the mesh
  22292. */
  22293. get: function () {
  22294. return Mesh._CAP_START;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. Object.defineProperty(Mesh, "CAP_END", {
  22300. /**
  22301. * Mesh cap setting : one cap at the end of the mesh
  22302. */
  22303. get: function () {
  22304. return Mesh._CAP_END;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Object.defineProperty(Mesh, "CAP_ALL", {
  22310. /**
  22311. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22312. */
  22313. get: function () {
  22314. return Mesh._CAP_ALL;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22320. set: function (callback) {
  22321. if (this._onBeforeDrawObserver) {
  22322. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22323. }
  22324. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Mesh.prototype, "source", {
  22330. get: function () {
  22331. return this._source;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. // Methods
  22337. /**
  22338. * Returns the string "Mesh".
  22339. */
  22340. Mesh.prototype.getClassName = function () {
  22341. return "Mesh";
  22342. };
  22343. /**
  22344. * Returns a string.
  22345. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22346. */
  22347. Mesh.prototype.toString = function (fullDetails) {
  22348. var ret = _super.prototype.toString.call(this, fullDetails);
  22349. ret += ", n vertices: " + this.getTotalVertices();
  22350. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22351. if (this.animations) {
  22352. for (var i = 0; i < this.animations.length; i++) {
  22353. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22354. }
  22355. }
  22356. if (fullDetails) {
  22357. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22358. }
  22359. return ret;
  22360. };
  22361. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22362. /**
  22363. * True if the mesh has some Levels Of Details (LOD).
  22364. * Returns a boolean.
  22365. */
  22366. get: function () {
  22367. return this._LODLevels.length > 0;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Mesh.prototype._sortLODLevels = function () {
  22373. this._LODLevels.sort(function (a, b) {
  22374. if (a.distance < b.distance) {
  22375. return 1;
  22376. }
  22377. if (a.distance > b.distance) {
  22378. return -1;
  22379. }
  22380. return 0;
  22381. });
  22382. };
  22383. /**
  22384. * Add a mesh as LOD level triggered at the given distance.
  22385. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22386. * @param {number} distance The distance from the center of the object to show this level
  22387. * @param {Mesh} mesh The mesh to be added as LOD level
  22388. * @return {Mesh} This mesh (for chaining)
  22389. */
  22390. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22391. if (mesh && mesh._masterMesh) {
  22392. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22393. return this;
  22394. }
  22395. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22396. this._LODLevels.push(level);
  22397. if (mesh) {
  22398. mesh._masterMesh = this;
  22399. }
  22400. this._sortLODLevels();
  22401. return this;
  22402. };
  22403. /**
  22404. * Returns the LOD level mesh at the passed distance or null if not found.
  22405. * It is related to the method `addLODLevel(distance, mesh)`.
  22406. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22407. * Returns an object Mesh or `null`.
  22408. */
  22409. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22410. for (var index = 0; index < this._LODLevels.length; index++) {
  22411. var level = this._LODLevels[index];
  22412. if (level.distance === distance) {
  22413. return level.mesh;
  22414. }
  22415. }
  22416. return null;
  22417. };
  22418. /**
  22419. * Remove a mesh from the LOD array
  22420. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22421. * @param {Mesh} mesh The mesh to be removed.
  22422. * @return {Mesh} This mesh (for chaining)
  22423. */
  22424. Mesh.prototype.removeLODLevel = function (mesh) {
  22425. for (var index = 0; index < this._LODLevels.length; index++) {
  22426. if (this._LODLevels[index].mesh === mesh) {
  22427. this._LODLevels.splice(index, 1);
  22428. if (mesh) {
  22429. mesh._masterMesh = null;
  22430. }
  22431. }
  22432. }
  22433. this._sortLODLevels();
  22434. return this;
  22435. };
  22436. /**
  22437. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22438. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22439. */
  22440. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22441. if (!this._LODLevels || this._LODLevels.length === 0) {
  22442. return this;
  22443. }
  22444. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  22445. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22446. if (this.onLODLevelSelection) {
  22447. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22448. }
  22449. return this;
  22450. }
  22451. for (var index = 0; index < this._LODLevels.length; index++) {
  22452. var level = this._LODLevels[index];
  22453. if (level.distance < distanceToCamera) {
  22454. if (level.mesh) {
  22455. level.mesh._preActivate();
  22456. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22457. }
  22458. if (this.onLODLevelSelection) {
  22459. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22460. }
  22461. return level.mesh;
  22462. }
  22463. }
  22464. if (this.onLODLevelSelection) {
  22465. this.onLODLevelSelection(distanceToCamera, this, this);
  22466. }
  22467. return this;
  22468. };
  22469. Object.defineProperty(Mesh.prototype, "geometry", {
  22470. /**
  22471. * Returns the mesh internal Geometry object.
  22472. */
  22473. get: function () {
  22474. return this._geometry;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. /**
  22480. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22481. */
  22482. Mesh.prototype.getTotalVertices = function () {
  22483. if (!this._geometry) {
  22484. return 0;
  22485. }
  22486. return this._geometry.getTotalVertices();
  22487. };
  22488. /**
  22489. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22490. * 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.
  22491. * Returns null if the mesh has no geometry or no vertex buffer.
  22492. * Possible `kind` values :
  22493. * - BABYLON.VertexBuffer.PositionKind
  22494. * - BABYLON.VertexBuffer.UVKind
  22495. * - BABYLON.VertexBuffer.UV2Kind
  22496. * - BABYLON.VertexBuffer.UV3Kind
  22497. * - BABYLON.VertexBuffer.UV4Kind
  22498. * - BABYLON.VertexBuffer.UV5Kind
  22499. * - BABYLON.VertexBuffer.UV6Kind
  22500. * - BABYLON.VertexBuffer.ColorKind
  22501. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22502. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22503. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22504. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22505. */
  22506. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22507. if (!this._geometry) {
  22508. return null;
  22509. }
  22510. return this._geometry.getVerticesData(kind, copyWhenShared);
  22511. };
  22512. /**
  22513. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22514. * Returns `undefined` if the mesh has no geometry.
  22515. * Possible `kind` values :
  22516. * - BABYLON.VertexBuffer.PositionKind
  22517. * - BABYLON.VertexBuffer.UVKind
  22518. * - BABYLON.VertexBuffer.UV2Kind
  22519. * - BABYLON.VertexBuffer.UV3Kind
  22520. * - BABYLON.VertexBuffer.UV4Kind
  22521. * - BABYLON.VertexBuffer.UV5Kind
  22522. * - BABYLON.VertexBuffer.UV6Kind
  22523. * - BABYLON.VertexBuffer.ColorKind
  22524. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22525. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22526. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22527. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22528. */
  22529. Mesh.prototype.getVertexBuffer = function (kind) {
  22530. if (!this._geometry) {
  22531. return undefined;
  22532. }
  22533. return this._geometry.getVertexBuffer(kind);
  22534. };
  22535. /**
  22536. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22537. * Possible `kind` values :
  22538. * - BABYLON.VertexBuffer.PositionKind
  22539. * - BABYLON.VertexBuffer.UVKind
  22540. * - BABYLON.VertexBuffer.UV2Kind
  22541. * - BABYLON.VertexBuffer.UV3Kind
  22542. * - BABYLON.VertexBuffer.UV4Kind
  22543. * - BABYLON.VertexBuffer.UV5Kind
  22544. * - BABYLON.VertexBuffer.UV6Kind
  22545. * - BABYLON.VertexBuffer.ColorKind
  22546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22550. */
  22551. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22552. if (!this._geometry) {
  22553. if (this._delayInfo) {
  22554. return this._delayInfo.indexOf(kind) !== -1;
  22555. }
  22556. return false;
  22557. }
  22558. return this._geometry.isVerticesDataPresent(kind);
  22559. };
  22560. /**
  22561. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22562. * Possible `kind` values :
  22563. * - BABYLON.VertexBuffer.PositionKind
  22564. * - BABYLON.VertexBuffer.UVKind
  22565. * - BABYLON.VertexBuffer.UV2Kind
  22566. * - BABYLON.VertexBuffer.UV3Kind
  22567. * - BABYLON.VertexBuffer.UV4Kind
  22568. * - BABYLON.VertexBuffer.UV5Kind
  22569. * - BABYLON.VertexBuffer.UV6Kind
  22570. * - BABYLON.VertexBuffer.ColorKind
  22571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22575. */
  22576. Mesh.prototype.getVerticesDataKinds = function () {
  22577. if (!this._geometry) {
  22578. var result = [];
  22579. if (this._delayInfo) {
  22580. this._delayInfo.forEach(function (kind, index, array) {
  22581. result.push(kind);
  22582. });
  22583. }
  22584. return result;
  22585. }
  22586. return this._geometry.getVerticesDataKinds();
  22587. };
  22588. /**
  22589. * Returns a positive integer : the total number of indices in this mesh geometry.
  22590. * Returns zero if the mesh has no geometry.
  22591. */
  22592. Mesh.prototype.getTotalIndices = function () {
  22593. if (!this._geometry) {
  22594. return 0;
  22595. }
  22596. return this._geometry.getTotalIndices();
  22597. };
  22598. /**
  22599. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22600. * 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.
  22601. * Returns an empty array if the mesh has no geometry.
  22602. */
  22603. Mesh.prototype.getIndices = function (copyWhenShared) {
  22604. if (!this._geometry) {
  22605. return [];
  22606. }
  22607. return this._geometry.getIndices(copyWhenShared);
  22608. };
  22609. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22610. get: function () {
  22611. return this._masterMesh !== null && this._masterMesh !== undefined;
  22612. },
  22613. enumerable: true,
  22614. configurable: true
  22615. });
  22616. /**
  22617. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22618. */
  22619. Mesh.prototype.isReady = function () {
  22620. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22621. return false;
  22622. }
  22623. return _super.prototype.isReady.call(this);
  22624. };
  22625. /**
  22626. * Boolean : true if the mesh has been disposed.
  22627. */
  22628. Mesh.prototype.isDisposed = function () {
  22629. return this._isDisposed;
  22630. };
  22631. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  22632. get: function () {
  22633. return this._sideOrientation;
  22634. },
  22635. /**
  22636. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  22637. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  22638. */
  22639. set: function (sideO) {
  22640. this._sideOrientation = sideO;
  22641. },
  22642. enumerable: true,
  22643. configurable: true
  22644. });
  22645. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22646. /**
  22647. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22648. * This property is pertinent only for updatable parametric shapes.
  22649. */
  22650. get: function () {
  22651. return this._areNormalsFrozen;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. /**
  22657. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22658. * It has no effect at all on other shapes.
  22659. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22660. * Returns the Mesh.
  22661. */
  22662. Mesh.prototype.freezeNormals = function () {
  22663. this._areNormalsFrozen = true;
  22664. return this;
  22665. };
  22666. /**
  22667. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22668. * It has no effect at all on other shapes.
  22669. * It reactivates the mesh normals computation if it was previously frozen.
  22670. * Returns the Mesh.
  22671. */
  22672. Mesh.prototype.unfreezeNormals = function () {
  22673. this._areNormalsFrozen = false;
  22674. return this;
  22675. };
  22676. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22677. /**
  22678. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22679. */
  22680. set: function (count) {
  22681. this._overridenInstanceCount = count;
  22682. },
  22683. enumerable: true,
  22684. configurable: true
  22685. });
  22686. // Methods
  22687. Mesh.prototype._preActivate = function () {
  22688. var sceneRenderId = this.getScene().getRenderId();
  22689. if (this._preActivateId === sceneRenderId) {
  22690. return this;
  22691. }
  22692. this._preActivateId = sceneRenderId;
  22693. this._visibleInstances = null;
  22694. return this;
  22695. };
  22696. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22697. if (this._visibleInstances) {
  22698. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22699. }
  22700. return this;
  22701. };
  22702. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22703. if (!this._visibleInstances) {
  22704. this._visibleInstances = {};
  22705. this._visibleInstances.defaultRenderId = renderId;
  22706. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22707. }
  22708. if (!this._visibleInstances[renderId]) {
  22709. this._visibleInstances[renderId] = new Array();
  22710. }
  22711. this._visibleInstances[renderId].push(instance);
  22712. return this;
  22713. };
  22714. /**
  22715. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22716. * This means the mesh underlying bounding box and sphere are recomputed.
  22717. * Returns the Mesh.
  22718. */
  22719. Mesh.prototype.refreshBoundingInfo = function () {
  22720. if (this._boundingInfo.isLocked) {
  22721. return;
  22722. }
  22723. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22724. if (data) {
  22725. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22726. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22727. }
  22728. if (this.subMeshes) {
  22729. for (var index = 0; index < this.subMeshes.length; index++) {
  22730. this.subMeshes[index].refreshBoundingInfo();
  22731. }
  22732. }
  22733. this._updateBoundingInfo();
  22734. return this;
  22735. };
  22736. Mesh.prototype._createGlobalSubMesh = function () {
  22737. var totalVertices = this.getTotalVertices();
  22738. if (!totalVertices || !this.getIndices()) {
  22739. return null;
  22740. }
  22741. this.releaseSubMeshes();
  22742. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22743. };
  22744. Mesh.prototype.subdivide = function (count) {
  22745. if (count < 1) {
  22746. return;
  22747. }
  22748. var totalIndices = this.getTotalIndices();
  22749. var subdivisionSize = (totalIndices / count) | 0;
  22750. var offset = 0;
  22751. // Ensure that subdivisionSize is a multiple of 3
  22752. while (subdivisionSize % 3 !== 0) {
  22753. subdivisionSize++;
  22754. }
  22755. this.releaseSubMeshes();
  22756. for (var index = 0; index < count; index++) {
  22757. if (offset >= totalIndices) {
  22758. break;
  22759. }
  22760. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22761. offset += subdivisionSize;
  22762. }
  22763. this.synchronizeInstances();
  22764. };
  22765. /**
  22766. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22767. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22768. * The `data` are either a numeric array either a Float32Array.
  22769. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22770. * 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).
  22771. * Note that a new underlying VertexBuffer object is created each call.
  22772. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22773. *
  22774. * Possible `kind` values :
  22775. * - BABYLON.VertexBuffer.PositionKind
  22776. * - BABYLON.VertexBuffer.UVKind
  22777. * - BABYLON.VertexBuffer.UV2Kind
  22778. * - BABYLON.VertexBuffer.UV3Kind
  22779. * - BABYLON.VertexBuffer.UV4Kind
  22780. * - BABYLON.VertexBuffer.UV5Kind
  22781. * - BABYLON.VertexBuffer.UV6Kind
  22782. * - BABYLON.VertexBuffer.ColorKind
  22783. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22784. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22785. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22786. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22787. *
  22788. * Returns the Mesh.
  22789. */
  22790. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22791. if (!this._geometry) {
  22792. var vertexData = new BABYLON.VertexData();
  22793. vertexData.set(data, kind);
  22794. var scene = this.getScene();
  22795. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22796. }
  22797. else {
  22798. this._geometry.setVerticesData(kind, data, updatable, stride);
  22799. }
  22800. return this;
  22801. };
  22802. /**
  22803. * Sets the mesh VertexBuffer.
  22804. * Returns the Mesh.
  22805. */
  22806. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22807. if (!this._geometry) {
  22808. var scene = this.getScene();
  22809. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22810. }
  22811. this._geometry.setVerticesBuffer(buffer);
  22812. return this;
  22813. };
  22814. /**
  22815. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22816. * If the mesh has no geometry, it is simply returned as it is.
  22817. * The `data` are either a numeric array either a Float32Array.
  22818. * No new underlying VertexBuffer object is created.
  22819. * 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.
  22820. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22821. *
  22822. * Possible `kind` values :
  22823. * - BABYLON.VertexBuffer.PositionKind
  22824. * - BABYLON.VertexBuffer.UVKind
  22825. * - BABYLON.VertexBuffer.UV2Kind
  22826. * - BABYLON.VertexBuffer.UV3Kind
  22827. * - BABYLON.VertexBuffer.UV4Kind
  22828. * - BABYLON.VertexBuffer.UV5Kind
  22829. * - BABYLON.VertexBuffer.UV6Kind
  22830. * - BABYLON.VertexBuffer.ColorKind
  22831. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22832. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22833. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22834. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22835. *
  22836. * Returns the Mesh.
  22837. */
  22838. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22839. if (!this._geometry) {
  22840. return;
  22841. }
  22842. if (!makeItUnique) {
  22843. this._geometry.updateVerticesData(kind, data, updateExtends);
  22844. }
  22845. else {
  22846. this.makeGeometryUnique();
  22847. this.updateVerticesData(kind, data, updateExtends, false);
  22848. }
  22849. return this;
  22850. };
  22851. /**
  22852. * Deprecated since BabylonJS v2.3
  22853. */
  22854. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  22855. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  22856. if (!this._geometry) {
  22857. return;
  22858. }
  22859. if (!makeItUnique) {
  22860. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  22861. }
  22862. else {
  22863. this.makeGeometryUnique();
  22864. this.updateVerticesDataDirectly(kind, data, offset, false);
  22865. }
  22866. };
  22867. /**
  22868. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22869. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22870. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22871. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22872. * Returns the Mesh.
  22873. */
  22874. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22875. if (computeNormals === void 0) { computeNormals = true; }
  22876. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22877. positionFunction(positions);
  22878. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22879. if (computeNormals) {
  22880. var indices = this.getIndices();
  22881. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22882. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22883. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22884. }
  22885. return this;
  22886. };
  22887. /**
  22888. * Creates a un-shared specific occurence of the geometry for the mesh.
  22889. * Returns the Mesh.
  22890. */
  22891. Mesh.prototype.makeGeometryUnique = function () {
  22892. if (!this._geometry) {
  22893. return;
  22894. }
  22895. var oldGeometry = this._geometry;
  22896. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22897. oldGeometry.releaseForMesh(this, true);
  22898. geometry.applyToMesh(this);
  22899. return this;
  22900. };
  22901. /**
  22902. * Sets the mesh indices.
  22903. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22904. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22905. * This method creates a new index buffer each call.
  22906. * Returns the Mesh.
  22907. */
  22908. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22909. if (!this._geometry) {
  22910. var vertexData = new BABYLON.VertexData();
  22911. vertexData.indices = indices;
  22912. var scene = this.getScene();
  22913. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22914. }
  22915. else {
  22916. this._geometry.setIndices(indices, totalVertices);
  22917. }
  22918. return this;
  22919. };
  22920. /**
  22921. * Invert the geometry to move from a right handed system to a left handed one.
  22922. * Returns the Mesh.
  22923. */
  22924. Mesh.prototype.toLeftHanded = function () {
  22925. if (!this._geometry) {
  22926. return;
  22927. }
  22928. this._geometry.toLeftHanded();
  22929. return this;
  22930. };
  22931. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22932. var engine = this.getScene().getEngine();
  22933. // Wireframe
  22934. var indexToBind;
  22935. if (this._unIndexed) {
  22936. indexToBind = null;
  22937. }
  22938. else {
  22939. switch (fillMode) {
  22940. case BABYLON.Material.PointFillMode:
  22941. indexToBind = null;
  22942. break;
  22943. case BABYLON.Material.WireFrameFillMode:
  22944. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22945. break;
  22946. default:
  22947. case BABYLON.Material.TriangleFillMode:
  22948. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22949. break;
  22950. }
  22951. }
  22952. // VBOs
  22953. this._geometry._bind(effect, indexToBind);
  22954. return this;
  22955. };
  22956. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  22957. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22958. return this;
  22959. }
  22960. this.onBeforeDrawObservable.notifyObservers(this);
  22961. var engine = this.getScene().getEngine();
  22962. // Draw order
  22963. switch (fillMode) {
  22964. case BABYLON.Material.PointFillMode:
  22965. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22966. break;
  22967. case BABYLON.Material.WireFrameFillMode:
  22968. if (this._unIndexed) {
  22969. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22970. }
  22971. else {
  22972. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  22973. }
  22974. break;
  22975. default:
  22976. if (this._unIndexed) {
  22977. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22978. }
  22979. else {
  22980. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22981. }
  22982. }
  22983. return this;
  22984. };
  22985. /**
  22986. * Registers for this mesh a javascript function called just before the rendering process.
  22987. * This function is passed the current mesh.
  22988. * Return the Mesh.
  22989. */
  22990. Mesh.prototype.registerBeforeRender = function (func) {
  22991. this.onBeforeRenderObservable.add(func);
  22992. return this;
  22993. };
  22994. /**
  22995. * Disposes a previously registered javascript function called before the rendering.
  22996. * This function is passed the current mesh.
  22997. * Returns the Mesh.
  22998. */
  22999. Mesh.prototype.unregisterBeforeRender = function (func) {
  23000. this.onBeforeRenderObservable.removeCallback(func);
  23001. return this;
  23002. };
  23003. /**
  23004. * Registers for this mesh a javascript function called just after the rendering is complete.
  23005. * This function is passed the current mesh.
  23006. * Returns the Mesh.
  23007. */
  23008. Mesh.prototype.registerAfterRender = function (func) {
  23009. this.onAfterRenderObservable.add(func);
  23010. return this;
  23011. };
  23012. /**
  23013. * Disposes a previously registered javascript function called after the rendering.
  23014. * This function is passed the current mesh.
  23015. * Return the Mesh.
  23016. */
  23017. Mesh.prototype.unregisterAfterRender = function (func) {
  23018. this.onAfterRenderObservable.removeCallback(func);
  23019. return this;
  23020. };
  23021. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23022. var scene = this.getScene();
  23023. this._batchCache.mustReturn = false;
  23024. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23025. this._batchCache.visibleInstances[subMeshId] = null;
  23026. if (this._visibleInstances) {
  23027. var currentRenderId = scene.getRenderId();
  23028. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23029. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23030. var selfRenderId = this._renderId;
  23031. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23032. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23033. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23034. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23035. }
  23036. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23037. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23038. this._batchCache.mustReturn = true;
  23039. return this._batchCache;
  23040. }
  23041. if (currentRenderId !== selfRenderId) {
  23042. this._batchCache.renderSelf[subMeshId] = false;
  23043. }
  23044. }
  23045. this._renderIdForInstances[subMeshId] = currentRenderId;
  23046. }
  23047. return this._batchCache;
  23048. };
  23049. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23050. var visibleInstances = batch.visibleInstances[subMesh._id];
  23051. var matricesCount = visibleInstances.length + 1;
  23052. var bufferSize = matricesCount * 16 * 4;
  23053. var currentInstancesBufferSize = this._instancesBufferSize;
  23054. var instancesBuffer = this._instancesBuffer;
  23055. while (this._instancesBufferSize < bufferSize) {
  23056. this._instancesBufferSize *= 2;
  23057. }
  23058. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23059. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23060. }
  23061. var offset = 0;
  23062. var instancesCount = 0;
  23063. var world = this.getWorldMatrix();
  23064. if (batch.renderSelf[subMesh._id]) {
  23065. world.copyToArray(this._instancesData, offset);
  23066. offset += 16;
  23067. instancesCount++;
  23068. }
  23069. if (visibleInstances) {
  23070. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23071. var instance = visibleInstances[instanceIndex];
  23072. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23073. offset += 16;
  23074. instancesCount++;
  23075. }
  23076. }
  23077. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23078. if (instancesBuffer) {
  23079. instancesBuffer.dispose();
  23080. }
  23081. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23082. this._instancesBuffer = instancesBuffer;
  23083. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23084. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23085. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23086. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23087. }
  23088. else {
  23089. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23090. }
  23091. this.geometry._bind(effect);
  23092. this._draw(subMesh, fillMode, instancesCount);
  23093. engine.unbindInstanceAttributes();
  23094. return this;
  23095. };
  23096. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23097. var scene = this.getScene();
  23098. var engine = scene.getEngine();
  23099. if (hardwareInstancedRendering) {
  23100. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23101. }
  23102. else {
  23103. if (batch.renderSelf[subMesh._id]) {
  23104. // Draw
  23105. if (onBeforeDraw) {
  23106. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23107. }
  23108. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23109. }
  23110. if (batch.visibleInstances[subMesh._id]) {
  23111. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23112. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23113. // World
  23114. var world = instance.getWorldMatrix();
  23115. if (onBeforeDraw) {
  23116. onBeforeDraw(true, world, effectiveMaterial);
  23117. }
  23118. // Draw
  23119. this._draw(subMesh, fillMode);
  23120. }
  23121. }
  23122. }
  23123. return this;
  23124. };
  23125. /**
  23126. * Triggers the draw call for the mesh.
  23127. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23128. * Returns the Mesh.
  23129. */
  23130. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23131. var scene = this.getScene();
  23132. // Managing instances
  23133. var batch = this._getInstancesRenderList(subMesh._id);
  23134. if (batch.mustReturn) {
  23135. return this;
  23136. }
  23137. // Checking geometry state
  23138. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23139. return this;
  23140. }
  23141. var callbackIndex;
  23142. this.onBeforeRenderObservable.notifyObservers(this);
  23143. var engine = scene.getEngine();
  23144. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23145. // Material
  23146. var effectiveMaterial = subMesh.getMaterial();
  23147. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23148. return this;
  23149. }
  23150. // Outline - step 1
  23151. var savedDepthWrite = engine.getDepthWrite();
  23152. if (this.renderOutline) {
  23153. engine.setDepthWrite(false);
  23154. scene.getOutlineRenderer().render(subMesh, batch);
  23155. engine.setDepthWrite(savedDepthWrite);
  23156. }
  23157. effectiveMaterial._preBind();
  23158. var effect = effectiveMaterial.getEffect();
  23159. // Bind
  23160. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23161. this._bind(subMesh, effect, fillMode);
  23162. var world = this.getWorldMatrix();
  23163. effectiveMaterial.bind(world, this);
  23164. // Alpha mode
  23165. if (enableAlphaMode) {
  23166. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23167. }
  23168. // Draw
  23169. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23170. // Unbind
  23171. effectiveMaterial.unbind();
  23172. // Outline - step 2
  23173. if (this.renderOutline && savedDepthWrite) {
  23174. engine.setDepthWrite(true);
  23175. engine.setColorWrite(false);
  23176. scene.getOutlineRenderer().render(subMesh, batch);
  23177. engine.setColorWrite(true);
  23178. }
  23179. // Overlay
  23180. if (this.renderOverlay) {
  23181. var currentMode = engine.getAlphaMode();
  23182. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23183. scene.getOutlineRenderer().render(subMesh, batch, true);
  23184. engine.setAlphaMode(currentMode);
  23185. }
  23186. this.onAfterRenderObservable.notifyObservers(this);
  23187. return this;
  23188. };
  23189. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23190. if (isInstance) {
  23191. effectiveMaterial.bindOnlyWorldMatrix(world);
  23192. }
  23193. return this;
  23194. };
  23195. /**
  23196. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23197. */
  23198. Mesh.prototype.getEmittedParticleSystems = function () {
  23199. var results = new Array();
  23200. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23201. var particleSystem = this.getScene().particleSystems[index];
  23202. if (particleSystem.emitter === this) {
  23203. results.push(particleSystem);
  23204. }
  23205. }
  23206. return results;
  23207. };
  23208. /**
  23209. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23210. */
  23211. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23212. var results = new Array();
  23213. var descendants = this.getDescendants();
  23214. descendants.push(this);
  23215. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23216. var particleSystem = this.getScene().particleSystems[index];
  23217. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23218. results.push(particleSystem);
  23219. }
  23220. }
  23221. return results;
  23222. };
  23223. Mesh.prototype._checkDelayState = function () {
  23224. var scene = this.getScene();
  23225. if (this._geometry) {
  23226. this._geometry.load(scene);
  23227. }
  23228. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23229. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23230. this._queueLoad(this, scene);
  23231. }
  23232. return this;
  23233. };
  23234. Mesh.prototype._queueLoad = function (mesh, scene) {
  23235. var _this = this;
  23236. scene._addPendingData(mesh);
  23237. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23238. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23239. if (data instanceof ArrayBuffer) {
  23240. _this._delayLoadingFunction(data, _this);
  23241. }
  23242. else {
  23243. _this._delayLoadingFunction(JSON.parse(data), _this);
  23244. }
  23245. _this.instances.forEach(function (instance) {
  23246. instance._syncSubMeshes();
  23247. });
  23248. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23249. scene._removePendingData(_this);
  23250. }, function () { }, scene.database, getBinaryData);
  23251. return this;
  23252. };
  23253. /**
  23254. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23255. */
  23256. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23257. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23258. return false;
  23259. }
  23260. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23261. return false;
  23262. }
  23263. this._checkDelayState();
  23264. return true;
  23265. };
  23266. /**
  23267. * Sets the mesh material by the material or multiMaterial `id` property.
  23268. * The material `id` is a string identifying the material or the multiMaterial.
  23269. * This method returns the Mesh.
  23270. */
  23271. Mesh.prototype.setMaterialByID = function (id) {
  23272. var materials = this.getScene().materials;
  23273. var index;
  23274. for (index = 0; index < materials.length; index++) {
  23275. if (materials[index].id === id) {
  23276. this.material = materials[index];
  23277. return this;
  23278. }
  23279. }
  23280. // Multi
  23281. var multiMaterials = this.getScene().multiMaterials;
  23282. for (index = 0; index < multiMaterials.length; index++) {
  23283. if (multiMaterials[index].id === id) {
  23284. this.material = multiMaterials[index];
  23285. return this;
  23286. }
  23287. }
  23288. return this;
  23289. };
  23290. /**
  23291. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23292. */
  23293. Mesh.prototype.getAnimatables = function () {
  23294. var results = [];
  23295. if (this.material) {
  23296. results.push(this.material);
  23297. }
  23298. if (this.skeleton) {
  23299. results.push(this.skeleton);
  23300. }
  23301. return results;
  23302. };
  23303. /**
  23304. * Modifies the mesh geometry according to the passed transformation matrix.
  23305. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23306. * The mesh normals are modified accordingly the same transformation.
  23307. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23308. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23309. * Returns the Mesh.
  23310. */
  23311. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23312. // Position
  23313. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23314. return this;
  23315. }
  23316. var submeshes = this.subMeshes.splice(0);
  23317. this._resetPointsArrayCache();
  23318. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23319. var temp = [];
  23320. var index;
  23321. for (index = 0; index < data.length; index += 3) {
  23322. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23323. }
  23324. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23325. // Normals
  23326. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23327. return this;
  23328. }
  23329. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23330. temp = [];
  23331. for (index = 0; index < data.length; index += 3) {
  23332. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23333. }
  23334. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23335. // flip faces?
  23336. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23337. this.flipFaces();
  23338. }
  23339. // Restore submeshes
  23340. this.releaseSubMeshes();
  23341. this.subMeshes = submeshes;
  23342. return this;
  23343. };
  23344. /**
  23345. * Modifies the mesh geometry according to its own current World Matrix.
  23346. * The mesh World Matrix is then reset.
  23347. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23348. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23349. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23350. * Returns the Mesh.
  23351. */
  23352. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23353. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23354. this.scaling.copyFromFloats(1, 1, 1);
  23355. this.position.copyFromFloats(0, 0, 0);
  23356. this.rotation.copyFromFloats(0, 0, 0);
  23357. //only if quaternion is already set
  23358. if (this.rotationQuaternion) {
  23359. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23360. }
  23361. this._worldMatrix = BABYLON.Matrix.Identity();
  23362. return this;
  23363. };
  23364. // Cache
  23365. Mesh.prototype._resetPointsArrayCache = function () {
  23366. this._positions = null;
  23367. return this;
  23368. };
  23369. Mesh.prototype._generatePointsArray = function () {
  23370. if (this._positions)
  23371. return true;
  23372. this._positions = [];
  23373. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23374. if (!data) {
  23375. return false;
  23376. }
  23377. for (var index = 0; index < data.length; index += 3) {
  23378. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23379. }
  23380. return true;
  23381. };
  23382. /**
  23383. * Returns a new Mesh object generated from the current mesh properties.
  23384. * This method must not get confused with createInstance().
  23385. * The parameter `name` is a string, the name given to the new mesh.
  23386. * The optional parameter `newParent` can be any Node object (default `null`).
  23387. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23388. * 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.
  23389. */
  23390. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23391. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23392. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23393. };
  23394. /**
  23395. * Disposes the mesh.
  23396. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23397. */
  23398. Mesh.prototype.dispose = function (doNotRecurse) {
  23399. var _this = this;
  23400. if (this._geometry) {
  23401. this._geometry.releaseForMesh(this, true);
  23402. }
  23403. // Sources
  23404. var meshes = this.getScene().meshes;
  23405. meshes.forEach(function (mesh) {
  23406. if (mesh._source && mesh._source === _this) {
  23407. mesh._source = null;
  23408. }
  23409. });
  23410. this._source = null;
  23411. // Instances
  23412. if (this._instancesBuffer) {
  23413. this._instancesBuffer.dispose();
  23414. this._instancesBuffer = null;
  23415. }
  23416. while (this.instances.length) {
  23417. this.instances[0].dispose();
  23418. }
  23419. // Highlight layers.
  23420. var highlightLayers = this.getScene().highlightLayers;
  23421. for (var i = 0; i < highlightLayers.length; i++) {
  23422. var highlightLayer = highlightLayers[i];
  23423. if (highlightLayer) {
  23424. highlightLayer.removeMesh(this);
  23425. highlightLayer.removeExcludedMesh(this);
  23426. }
  23427. }
  23428. _super.prototype.dispose.call(this, doNotRecurse);
  23429. };
  23430. /**
  23431. * Modifies the mesh geometry according to a displacement map.
  23432. * 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.
  23433. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23434. * This method returns nothing.
  23435. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23436. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23437. * 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.
  23438. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23439. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23440. *
  23441. * Returns the Mesh.
  23442. */
  23443. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23444. var _this = this;
  23445. var scene = this.getScene();
  23446. var onload = function (img) {
  23447. // Getting height map data
  23448. var canvas = document.createElement("canvas");
  23449. var context = canvas.getContext("2d");
  23450. var heightMapWidth = img.width;
  23451. var heightMapHeight = img.height;
  23452. canvas.width = heightMapWidth;
  23453. canvas.height = heightMapHeight;
  23454. context.drawImage(img, 0, 0);
  23455. // Create VertexData from map data
  23456. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23457. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23458. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23459. //execute success callback, if set
  23460. if (onSuccess) {
  23461. onSuccess(_this);
  23462. }
  23463. };
  23464. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23465. return this;
  23466. };
  23467. /**
  23468. * Modifies the mesh geometry according to a displacementMap buffer.
  23469. * 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.
  23470. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23471. * This method returns nothing.
  23472. * 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.
  23473. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23474. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23475. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23476. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23477. *
  23478. * Returns the Mesh.
  23479. */
  23480. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23481. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23482. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23483. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23484. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23485. return this;
  23486. }
  23487. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23488. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23489. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23490. var position = BABYLON.Vector3.Zero();
  23491. var normal = BABYLON.Vector3.Zero();
  23492. var uv = BABYLON.Vector2.Zero();
  23493. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23494. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23495. for (var index = 0; index < positions.length; index += 3) {
  23496. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23497. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23498. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23499. // Compute height
  23500. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23501. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23502. var pos = (u + v * heightMapWidth) * 4;
  23503. var r = buffer[pos] / 255.0;
  23504. var g = buffer[pos + 1] / 255.0;
  23505. var b = buffer[pos + 2] / 255.0;
  23506. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23507. normal.normalize();
  23508. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23509. position = position.add(normal);
  23510. position.toArray(positions, index);
  23511. }
  23512. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23513. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23514. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23515. return this;
  23516. };
  23517. /**
  23518. * Modify the mesh to get a flat shading rendering.
  23519. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23520. * This method returns the Mesh.
  23521. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23522. */
  23523. Mesh.prototype.convertToFlatShadedMesh = function () {
  23524. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23525. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23526. var kinds = this.getVerticesDataKinds();
  23527. var vbs = [];
  23528. var data = [];
  23529. var newdata = [];
  23530. var updatableNormals = false;
  23531. var kindIndex;
  23532. var kind;
  23533. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23534. kind = kinds[kindIndex];
  23535. var vertexBuffer = this.getVertexBuffer(kind);
  23536. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23537. updatableNormals = vertexBuffer.isUpdatable();
  23538. kinds.splice(kindIndex, 1);
  23539. kindIndex--;
  23540. continue;
  23541. }
  23542. vbs[kind] = vertexBuffer;
  23543. data[kind] = vbs[kind].getData();
  23544. newdata[kind] = [];
  23545. }
  23546. // Save previous submeshes
  23547. var previousSubmeshes = this.subMeshes.slice(0);
  23548. var indices = this.getIndices();
  23549. var totalIndices = this.getTotalIndices();
  23550. // Generating unique vertices per face
  23551. var index;
  23552. for (index = 0; index < totalIndices; index++) {
  23553. var vertexIndex = indices[index];
  23554. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23555. kind = kinds[kindIndex];
  23556. var stride = vbs[kind].getStrideSize();
  23557. for (var offset = 0; offset < stride; offset++) {
  23558. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23559. }
  23560. }
  23561. }
  23562. // Updating faces & normal
  23563. var normals = [];
  23564. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23565. for (index = 0; index < totalIndices; index += 3) {
  23566. indices[index] = index;
  23567. indices[index + 1] = index + 1;
  23568. indices[index + 2] = index + 2;
  23569. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23570. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23571. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23572. var p1p2 = p1.subtract(p2);
  23573. var p3p2 = p3.subtract(p2);
  23574. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23575. // Store same normals for every vertex
  23576. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23577. normals.push(normal.x);
  23578. normals.push(normal.y);
  23579. normals.push(normal.z);
  23580. }
  23581. }
  23582. this.setIndices(indices);
  23583. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23584. // Updating vertex buffers
  23585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23586. kind = kinds[kindIndex];
  23587. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23588. }
  23589. // Updating submeshes
  23590. this.releaseSubMeshes();
  23591. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23592. var previousOne = previousSubmeshes[submeshIndex];
  23593. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23594. }
  23595. this.synchronizeInstances();
  23596. return this;
  23597. };
  23598. /**
  23599. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23600. * In other words, more vertices, no more indices and a single bigger VBO.
  23601. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23602. * Returns the Mesh.
  23603. */
  23604. Mesh.prototype.convertToUnIndexedMesh = function () {
  23605. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23606. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23607. var kinds = this.getVerticesDataKinds();
  23608. var vbs = [];
  23609. var data = [];
  23610. var newdata = [];
  23611. var updatableNormals = false;
  23612. var kindIndex;
  23613. var kind;
  23614. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23615. kind = kinds[kindIndex];
  23616. var vertexBuffer = this.getVertexBuffer(kind);
  23617. vbs[kind] = vertexBuffer;
  23618. data[kind] = vbs[kind].getData();
  23619. newdata[kind] = [];
  23620. }
  23621. // Save previous submeshes
  23622. var previousSubmeshes = this.subMeshes.slice(0);
  23623. var indices = this.getIndices();
  23624. var totalIndices = this.getTotalIndices();
  23625. // Generating unique vertices per face
  23626. var index;
  23627. for (index = 0; index < totalIndices; index++) {
  23628. var vertexIndex = indices[index];
  23629. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23630. kind = kinds[kindIndex];
  23631. var stride = vbs[kind].getStrideSize();
  23632. for (var offset = 0; offset < stride; offset++) {
  23633. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23634. }
  23635. }
  23636. }
  23637. // Updating indices
  23638. for (index = 0; index < totalIndices; index += 3) {
  23639. indices[index] = index;
  23640. indices[index + 1] = index + 1;
  23641. indices[index + 2] = index + 2;
  23642. }
  23643. this.setIndices(indices);
  23644. // Updating vertex buffers
  23645. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23646. kind = kinds[kindIndex];
  23647. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23648. }
  23649. // Updating submeshes
  23650. this.releaseSubMeshes();
  23651. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23652. var previousOne = previousSubmeshes[submeshIndex];
  23653. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23654. }
  23655. this._unIndexed = true;
  23656. this.synchronizeInstances();
  23657. return this;
  23658. };
  23659. /**
  23660. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23661. * This method returns the Mesh.
  23662. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23663. */
  23664. Mesh.prototype.flipFaces = function (flipNormals) {
  23665. if (flipNormals === void 0) { flipNormals = false; }
  23666. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23667. var i;
  23668. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23669. for (i = 0; i < vertex_data.normals.length; i++) {
  23670. vertex_data.normals[i] *= -1;
  23671. }
  23672. }
  23673. var temp;
  23674. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23675. // reassign indices
  23676. temp = vertex_data.indices[i + 1];
  23677. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23678. vertex_data.indices[i + 2] = temp;
  23679. }
  23680. vertex_data.applyToMesh(this);
  23681. return this;
  23682. };
  23683. // Instances
  23684. /**
  23685. * Creates a new InstancedMesh object from the mesh model.
  23686. * An instance shares the same properties and the same material than its model.
  23687. * Only these properties of each instance can then be set individually :
  23688. * - position
  23689. * - rotation
  23690. * - rotationQuaternion
  23691. * - setPivotMatrix
  23692. * - scaling
  23693. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23694. * Warning : this method is not supported for Line mesh and LineSystem
  23695. */
  23696. Mesh.prototype.createInstance = function (name) {
  23697. return new BABYLON.InstancedMesh(name, this);
  23698. };
  23699. /**
  23700. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23701. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23702. * This method returns the Mesh.
  23703. */
  23704. Mesh.prototype.synchronizeInstances = function () {
  23705. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23706. var instance = this.instances[instanceIndex];
  23707. instance._syncSubMeshes();
  23708. }
  23709. return this;
  23710. };
  23711. /**
  23712. * Simplify the mesh according to the given array of settings.
  23713. * Function will return immediately and will simplify async. It returns the Mesh.
  23714. * @param settings a collection of simplification settings.
  23715. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23716. * @param type the type of simplification to run.
  23717. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23718. */
  23719. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23720. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23721. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23722. this.getScene().simplificationQueue.addTask({
  23723. settings: settings,
  23724. parallelProcessing: parallelProcessing,
  23725. mesh: this,
  23726. simplificationType: simplificationType,
  23727. successCallback: successCallback
  23728. });
  23729. return this;
  23730. };
  23731. /**
  23732. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23733. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23734. * This should be used together with the simplification to avoid disappearing triangles.
  23735. * Returns the Mesh.
  23736. * @param successCallback an optional success callback to be called after the optimization finished.
  23737. */
  23738. Mesh.prototype.optimizeIndices = function (successCallback) {
  23739. var _this = this;
  23740. var indices = this.getIndices();
  23741. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23742. var vectorPositions = [];
  23743. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23744. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23745. }
  23746. var dupes = [];
  23747. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23748. var realPos = vectorPositions.length - 1 - iteration;
  23749. var testedPosition = vectorPositions[realPos];
  23750. for (var j = 0; j < realPos; ++j) {
  23751. var againstPosition = vectorPositions[j];
  23752. if (testedPosition.equals(againstPosition)) {
  23753. dupes[realPos] = j;
  23754. break;
  23755. }
  23756. }
  23757. }, function () {
  23758. for (var i = 0; i < indices.length; ++i) {
  23759. indices[i] = dupes[indices[i]] || indices[i];
  23760. }
  23761. //indices are now reordered
  23762. var originalSubMeshes = _this.subMeshes.slice(0);
  23763. _this.setIndices(indices);
  23764. _this.subMeshes = originalSubMeshes;
  23765. if (successCallback) {
  23766. successCallback(_this);
  23767. }
  23768. });
  23769. return this;
  23770. };
  23771. // Statics
  23772. /**
  23773. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23774. * The parameter `parsedMesh` is the mesh to be copied.
  23775. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23776. */
  23777. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23778. var mesh = new Mesh(parsedMesh.name, scene);
  23779. mesh.id = parsedMesh.id;
  23780. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23781. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23782. if (parsedMesh.metadata !== undefined) {
  23783. mesh.metadata = parsedMesh.metadata;
  23784. }
  23785. if (parsedMesh.rotationQuaternion) {
  23786. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23787. }
  23788. else if (parsedMesh.rotation) {
  23789. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23790. }
  23791. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23792. if (parsedMesh.localMatrix) {
  23793. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23794. }
  23795. else if (parsedMesh.pivotMatrix) {
  23796. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23797. }
  23798. mesh.setEnabled(parsedMesh.isEnabled);
  23799. mesh.isVisible = parsedMesh.isVisible;
  23800. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23801. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23802. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23803. if (parsedMesh.applyFog !== undefined) {
  23804. mesh.applyFog = parsedMesh.applyFog;
  23805. }
  23806. if (parsedMesh.pickable !== undefined) {
  23807. mesh.isPickable = parsedMesh.pickable;
  23808. }
  23809. if (parsedMesh.alphaIndex !== undefined) {
  23810. mesh.alphaIndex = parsedMesh.alphaIndex;
  23811. }
  23812. mesh.receiveShadows = parsedMesh.receiveShadows;
  23813. mesh.billboardMode = parsedMesh.billboardMode;
  23814. if (parsedMesh.visibility !== undefined) {
  23815. mesh.visibility = parsedMesh.visibility;
  23816. }
  23817. mesh.checkCollisions = parsedMesh.checkCollisions;
  23818. if (parsedMesh.isBlocker !== undefined) {
  23819. mesh.isBlocker = parsedMesh.isBlocker;
  23820. }
  23821. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23822. // freezeWorldMatrix
  23823. if (parsedMesh.freezeWorldMatrix) {
  23824. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23825. }
  23826. // Parent
  23827. if (parsedMesh.parentId) {
  23828. mesh._waitingParentId = parsedMesh.parentId;
  23829. }
  23830. // Actions
  23831. if (parsedMesh.actions !== undefined) {
  23832. mesh._waitingActions = parsedMesh.actions;
  23833. }
  23834. // Overlay
  23835. if (parsedMesh.overlayAlpha !== undefined) {
  23836. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23837. }
  23838. if (parsedMesh.overlayColor !== undefined) {
  23839. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23840. }
  23841. if (parsedMesh.renderOverlay !== undefined) {
  23842. mesh.renderOverlay = parsedMesh.renderOverlay;
  23843. }
  23844. // Geometry
  23845. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23846. if (parsedMesh.delayLoadingFile) {
  23847. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23848. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23849. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23850. if (parsedMesh._binaryInfo) {
  23851. mesh._binaryInfo = parsedMesh._binaryInfo;
  23852. }
  23853. mesh._delayInfo = [];
  23854. if (parsedMesh.hasUVs) {
  23855. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23856. }
  23857. if (parsedMesh.hasUVs2) {
  23858. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23859. }
  23860. if (parsedMesh.hasUVs3) {
  23861. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23862. }
  23863. if (parsedMesh.hasUVs4) {
  23864. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23865. }
  23866. if (parsedMesh.hasUVs5) {
  23867. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23868. }
  23869. if (parsedMesh.hasUVs6) {
  23870. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23871. }
  23872. if (parsedMesh.hasColors) {
  23873. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23874. }
  23875. if (parsedMesh.hasMatricesIndices) {
  23876. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23877. }
  23878. if (parsedMesh.hasMatricesWeights) {
  23879. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23880. }
  23881. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23882. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23883. mesh._checkDelayState();
  23884. }
  23885. }
  23886. else {
  23887. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23888. }
  23889. // Material
  23890. if (parsedMesh.materialId) {
  23891. mesh.setMaterialByID(parsedMesh.materialId);
  23892. }
  23893. else {
  23894. mesh.material = null;
  23895. }
  23896. // Skeleton
  23897. if (parsedMesh.skeletonId > -1) {
  23898. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23899. if (parsedMesh.numBoneInfluencers) {
  23900. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23901. }
  23902. }
  23903. // Animations
  23904. if (parsedMesh.animations) {
  23905. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23906. var parsedAnimation = parsedMesh.animations[animationIndex];
  23907. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23908. }
  23909. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23910. }
  23911. if (parsedMesh.autoAnimate) {
  23912. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23913. }
  23914. // Layer Mask
  23915. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23916. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23917. }
  23918. else {
  23919. mesh.layerMask = 0x0FFFFFFF;
  23920. }
  23921. //(Deprecated) physics
  23922. if (parsedMesh.physicsImpostor) {
  23923. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23924. mass: parsedMesh.physicsMass,
  23925. friction: parsedMesh.physicsFriction,
  23926. restitution: parsedMesh.physicsRestitution
  23927. }, scene);
  23928. }
  23929. // Instances
  23930. if (parsedMesh.instances) {
  23931. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23932. var parsedInstance = parsedMesh.instances[index];
  23933. var instance = mesh.createInstance(parsedInstance.name);
  23934. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23935. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23936. if (parsedInstance.parentId) {
  23937. instance._waitingParentId = parsedInstance.parentId;
  23938. }
  23939. if (parsedInstance.rotationQuaternion) {
  23940. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23941. }
  23942. else if (parsedInstance.rotation) {
  23943. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23944. }
  23945. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23946. instance.checkCollisions = mesh.checkCollisions;
  23947. if (parsedMesh.animations) {
  23948. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23949. parsedAnimation = parsedMesh.animations[animationIndex];
  23950. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23951. }
  23952. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23953. }
  23954. }
  23955. }
  23956. return mesh;
  23957. };
  23958. /**
  23959. * Creates a ribbon mesh.
  23960. * Please consider using the same method from the MeshBuilder class instead.
  23961. * 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.
  23962. *
  23963. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23964. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23965. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23966. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23967. * 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.
  23968. * 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.
  23969. * 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
  23970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23973. */
  23974. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23975. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23976. pathArray: pathArray,
  23977. closeArray: closeArray,
  23978. closePath: closePath,
  23979. offset: offset,
  23980. updatable: updatable,
  23981. sideOrientation: sideOrientation,
  23982. instance: instance
  23983. }, scene);
  23984. };
  23985. /**
  23986. * Creates a plane polygonal mesh. By default, this is a disc.
  23987. * Please consider using the same method from the MeshBuilder class instead.
  23988. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23989. * 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.
  23990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23993. */
  23994. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23995. var options = {
  23996. radius: radius,
  23997. tessellation: tessellation,
  23998. sideOrientation: sideOrientation,
  23999. updatable: updatable
  24000. };
  24001. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24002. };
  24003. /**
  24004. * Creates a box mesh.
  24005. * Please consider using the same method from the MeshBuilder class instead.
  24006. * The parameter `size` sets the size (float) of each box side (default 1).
  24007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24010. */
  24011. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24012. var options = {
  24013. size: size,
  24014. sideOrientation: sideOrientation,
  24015. updatable: updatable
  24016. };
  24017. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24018. };
  24019. /**
  24020. * Creates a sphere mesh.
  24021. * Please consider using the same method from the MeshBuilder class instead.
  24022. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24023. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24027. */
  24028. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24029. var options = {
  24030. segments: segments,
  24031. diameterX: diameter,
  24032. diameterY: diameter,
  24033. diameterZ: diameter,
  24034. sideOrientation: sideOrientation,
  24035. updatable: updatable
  24036. };
  24037. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24038. };
  24039. /**
  24040. * Creates a cylinder or a cone mesh.
  24041. * Please consider using the same method from the MeshBuilder class instead.
  24042. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24043. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24044. * 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.
  24045. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24046. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24050. */
  24051. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24052. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24053. if (scene !== undefined) {
  24054. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24055. updatable = scene;
  24056. }
  24057. scene = subdivisions;
  24058. subdivisions = 1;
  24059. }
  24060. var options = {
  24061. height: height,
  24062. diameterTop: diameterTop,
  24063. diameterBottom: diameterBottom,
  24064. tessellation: tessellation,
  24065. subdivisions: subdivisions,
  24066. sideOrientation: sideOrientation,
  24067. updatable: updatable
  24068. };
  24069. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24070. };
  24071. // Torus (Code from SharpDX.org)
  24072. /**
  24073. * Creates a torus mesh.
  24074. * Please consider using the same method from the MeshBuilder class instead.
  24075. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24076. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24077. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24081. */
  24082. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24083. var options = {
  24084. diameter: diameter,
  24085. thickness: thickness,
  24086. tessellation: tessellation,
  24087. sideOrientation: sideOrientation,
  24088. updatable: updatable
  24089. };
  24090. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24091. };
  24092. /**
  24093. * Creates a torus knot mesh.
  24094. * Please consider using the same method from the MeshBuilder class instead.
  24095. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24096. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24097. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24098. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24102. */
  24103. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24104. var options = {
  24105. radius: radius,
  24106. tube: tube,
  24107. radialSegments: radialSegments,
  24108. tubularSegments: tubularSegments,
  24109. p: p,
  24110. q: q,
  24111. sideOrientation: sideOrientation,
  24112. updatable: updatable
  24113. };
  24114. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24115. };
  24116. /**
  24117. * Creates a line mesh.
  24118. * Please consider using the same method from the MeshBuilder class instead.
  24119. * 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.
  24120. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24121. * The parameter `points` is an array successive Vector3.
  24122. * 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
  24123. * When updating an instance, remember that only point positions can change, not the number of points.
  24124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24125. */
  24126. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24127. var options = {
  24128. points: points,
  24129. updatable: updatable,
  24130. instance: instance
  24131. };
  24132. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24133. };
  24134. /**
  24135. * Creates a dashed line mesh.
  24136. * Please consider using the same method from the MeshBuilder class instead.
  24137. * 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.
  24138. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24139. * The parameter `points` is an array successive Vector3.
  24140. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24141. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24142. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24143. * 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
  24144. * When updating an instance, remember that only point positions can change, not the number of points.
  24145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24146. */
  24147. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24148. var options = {
  24149. points: points,
  24150. dashSize: dashSize,
  24151. gapSize: gapSize,
  24152. dashNb: dashNb,
  24153. updatable: updatable,
  24154. instance: instance
  24155. };
  24156. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24157. };
  24158. /**
  24159. * Creates an extruded shape mesh.
  24160. * 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.
  24161. * Please consider using the same method from the MeshBuilder class instead.
  24162. *
  24163. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24164. * 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
  24165. * extruded along the Z axis.
  24166. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24167. * 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.
  24168. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24169. * 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
  24170. * 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
  24171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24175. */
  24176. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24177. var options = {
  24178. shape: shape,
  24179. path: path,
  24180. scale: scale,
  24181. rotation: rotation,
  24182. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24183. sideOrientation: sideOrientation,
  24184. instance: instance,
  24185. updatable: updatable
  24186. };
  24187. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24188. };
  24189. /**
  24190. * Creates an custom extruded shape mesh.
  24191. * 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.
  24192. * Please consider using the same method from the MeshBuilder class instead.
  24193. *
  24194. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24195. * 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
  24196. * extruded along the Z axis.
  24197. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24198. * 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
  24199. * and the distance of this point from the begining of the path :
  24200. * ```javascript
  24201. * var rotationFunction = function(i, distance) {
  24202. * // do things
  24203. * return rotationValue; }
  24204. * ```
  24205. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24206. * 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
  24207. * and the distance of this point from the begining of the path :
  24208. * ```javascript
  24209. * var scaleFunction = function(i, distance) {
  24210. * // do things
  24211. * return scaleValue;}
  24212. * ```
  24213. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24214. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24215. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24216. * 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
  24217. * 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
  24218. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24219. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24222. */
  24223. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24224. var options = {
  24225. shape: shape,
  24226. path: path,
  24227. scaleFunction: scaleFunction,
  24228. rotationFunction: rotationFunction,
  24229. ribbonCloseArray: ribbonCloseArray,
  24230. ribbonClosePath: ribbonClosePath,
  24231. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24232. sideOrientation: sideOrientation,
  24233. instance: instance,
  24234. updatable: updatable
  24235. };
  24236. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24237. };
  24238. /**
  24239. * Creates lathe mesh.
  24240. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24241. * Please consider using the same method from the MeshBuilder class instead.
  24242. * 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
  24243. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24244. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24245. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24249. */
  24250. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24251. var options = {
  24252. shape: shape,
  24253. radius: radius,
  24254. tessellation: tessellation,
  24255. sideOrientation: sideOrientation,
  24256. updatable: updatable
  24257. };
  24258. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24259. };
  24260. /**
  24261. * Creates a plane mesh.
  24262. * Please consider using the same method from the MeshBuilder class instead.
  24263. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24267. */
  24268. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24269. var options = {
  24270. size: size,
  24271. width: size,
  24272. height: size,
  24273. sideOrientation: sideOrientation,
  24274. updatable: updatable
  24275. };
  24276. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24277. };
  24278. /**
  24279. * Creates a ground mesh.
  24280. * Please consider using the same method from the MeshBuilder class instead.
  24281. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24282. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24284. */
  24285. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24286. var options = {
  24287. width: width,
  24288. height: height,
  24289. subdivisions: subdivisions,
  24290. updatable: updatable
  24291. };
  24292. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24293. };
  24294. /**
  24295. * Creates a tiled ground mesh.
  24296. * Please consider using the same method from the MeshBuilder class instead.
  24297. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24298. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24299. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24300. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24301. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24302. * numbers of subdivisions on the ground width and height of each tile.
  24303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24304. */
  24305. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24306. var options = {
  24307. xmin: xmin,
  24308. zmin: zmin,
  24309. xmax: xmax,
  24310. zmax: zmax,
  24311. subdivisions: subdivisions,
  24312. precision: precision,
  24313. updatable: updatable
  24314. };
  24315. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24316. };
  24317. /**
  24318. * Creates a ground mesh from a height map.
  24319. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24320. * Please consider using the same method from the MeshBuilder class instead.
  24321. * The parameter `url` sets the URL of the height map image resource.
  24322. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24323. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24324. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24325. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24326. * 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).
  24327. * This function is passed the newly built mesh :
  24328. * ```javascript
  24329. * function(mesh) { // do things
  24330. * return; }
  24331. * ```
  24332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24333. */
  24334. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24335. var options = {
  24336. width: width,
  24337. height: height,
  24338. subdivisions: subdivisions,
  24339. minHeight: minHeight,
  24340. maxHeight: maxHeight,
  24341. updatable: updatable,
  24342. onReady: onReady
  24343. };
  24344. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24345. };
  24346. /**
  24347. * Creates a tube mesh.
  24348. * 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.
  24349. * Please consider using the same method from the MeshBuilder class instead.
  24350. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24351. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24352. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24353. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24354. * 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.
  24355. * It must return a radius value (positive float) :
  24356. * ```javascript
  24357. * var radiusFunction = function(i, distance) {
  24358. * // do things
  24359. * return radius; }
  24360. * ```
  24361. * 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
  24362. * 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
  24363. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24364. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24366. */
  24367. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24368. var options = {
  24369. path: path,
  24370. radius: radius,
  24371. tessellation: tessellation,
  24372. radiusFunction: radiusFunction,
  24373. arc: 1,
  24374. cap: cap,
  24375. updatable: updatable,
  24376. sideOrientation: sideOrientation,
  24377. instance: instance
  24378. };
  24379. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24380. };
  24381. /**
  24382. * Creates a polyhedron mesh.
  24383. * Please consider using the same method from the MeshBuilder class instead.
  24384. * 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
  24385. * to choose the wanted type.
  24386. * The parameter `size` (positive float, default 1) sets the polygon size.
  24387. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24388. * 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`.
  24389. * 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
  24390. * 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)`).
  24391. * 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
  24392. * 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.
  24393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24396. */
  24397. Mesh.CreatePolyhedron = function (name, options, scene) {
  24398. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24399. };
  24400. /**
  24401. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24402. * Please consider using the same method from the MeshBuilder class instead.
  24403. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24404. * 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`).
  24405. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24406. * 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.
  24407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24410. */
  24411. Mesh.CreateIcoSphere = function (name, options, scene) {
  24412. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24413. };
  24414. /**
  24415. * Creates a decal mesh.
  24416. * Please consider using the same method from the MeshBuilder class instead.
  24417. * 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.
  24418. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24419. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24420. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24421. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24422. */
  24423. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24424. var options = {
  24425. position: position,
  24426. normal: normal,
  24427. size: size,
  24428. angle: angle
  24429. };
  24430. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24431. };
  24432. // Skeletons
  24433. /**
  24434. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24435. */
  24436. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24437. var source;
  24438. if (!this._sourcePositions) {
  24439. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24440. this._sourcePositions = new Float32Array(source);
  24441. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24442. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24443. }
  24444. }
  24445. return this._sourcePositions;
  24446. };
  24447. /**
  24448. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24449. */
  24450. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24451. var source;
  24452. if (!this._sourceNormals) {
  24453. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24454. this._sourceNormals = new Float32Array(source);
  24455. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24456. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24457. }
  24458. }
  24459. return this._sourceNormals;
  24460. };
  24461. /**
  24462. * Updates the vertex buffer by applying transformation from the bones.
  24463. * Returns the Mesh.
  24464. *
  24465. * @param {skeleton} skeleton to apply
  24466. */
  24467. Mesh.prototype.applySkeleton = function (skeleton) {
  24468. if (!this.geometry) {
  24469. return this;
  24470. }
  24471. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24472. return this;
  24473. }
  24474. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24475. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24476. return this;
  24477. }
  24478. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24479. return this;
  24480. }
  24481. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24482. return this;
  24483. }
  24484. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24485. return this;
  24486. }
  24487. if (!this._sourcePositions) {
  24488. var submeshes = this.subMeshes.slice();
  24489. this.setPositionsForCPUSkinning();
  24490. this.subMeshes = submeshes;
  24491. }
  24492. if (!this._sourceNormals) {
  24493. this.setNormalsForCPUSkinning();
  24494. }
  24495. // positionsData checks for not being Float32Array will only pass at most once
  24496. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24497. if (!(positionsData instanceof Float32Array)) {
  24498. positionsData = new Float32Array(positionsData);
  24499. }
  24500. // normalsData checks for not being Float32Array will only pass at most once
  24501. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24502. if (!(normalsData instanceof Float32Array)) {
  24503. normalsData = new Float32Array(normalsData);
  24504. }
  24505. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24506. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24507. var needExtras = this.numBoneInfluencers > 4;
  24508. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24509. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24510. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24511. var tempVector3 = BABYLON.Vector3.Zero();
  24512. var finalMatrix = new BABYLON.Matrix();
  24513. var tempMatrix = new BABYLON.Matrix();
  24514. var matWeightIdx = 0;
  24515. var inf;
  24516. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24517. var weight;
  24518. for (inf = 0; inf < 4; inf++) {
  24519. weight = matricesWeightsData[matWeightIdx + inf];
  24520. if (weight > 0) {
  24521. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24522. finalMatrix.addToSelf(tempMatrix);
  24523. }
  24524. else
  24525. break;
  24526. }
  24527. if (needExtras) {
  24528. for (inf = 0; inf < 4; inf++) {
  24529. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24530. if (weight > 0) {
  24531. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24532. finalMatrix.addToSelf(tempMatrix);
  24533. }
  24534. else
  24535. break;
  24536. }
  24537. }
  24538. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24539. tempVector3.toArray(positionsData, index);
  24540. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24541. tempVector3.toArray(normalsData, index);
  24542. finalMatrix.reset();
  24543. }
  24544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24546. return this;
  24547. };
  24548. // Tools
  24549. /**
  24550. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24551. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24552. */
  24553. Mesh.MinMax = function (meshes) {
  24554. var minVector = null;
  24555. var maxVector = null;
  24556. meshes.forEach(function (mesh, index, array) {
  24557. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24558. if (!minVector) {
  24559. minVector = boundingBox.minimumWorld;
  24560. maxVector = boundingBox.maximumWorld;
  24561. }
  24562. else {
  24563. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24564. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24565. }
  24566. });
  24567. return {
  24568. min: minVector,
  24569. max: maxVector
  24570. };
  24571. };
  24572. /**
  24573. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24574. */
  24575. Mesh.Center = function (meshesOrMinMaxVector) {
  24576. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24577. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24578. };
  24579. /**
  24580. * Merge the array of meshes into a single mesh for performance reasons.
  24581. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24582. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24583. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24584. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24585. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24586. */
  24587. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24588. if (disposeSource === void 0) { disposeSource = true; }
  24589. var index;
  24590. if (!allow32BitsIndices) {
  24591. var totalVertices = 0;
  24592. // Counting vertices
  24593. for (index = 0; index < meshes.length; index++) {
  24594. if (meshes[index]) {
  24595. totalVertices += meshes[index].getTotalVertices();
  24596. if (totalVertices > 65536) {
  24597. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24598. return null;
  24599. }
  24600. }
  24601. }
  24602. }
  24603. // Merge
  24604. var vertexData;
  24605. var otherVertexData;
  24606. var indiceArray = new Array();
  24607. var source;
  24608. for (index = 0; index < meshes.length; index++) {
  24609. if (meshes[index]) {
  24610. meshes[index].computeWorldMatrix(true);
  24611. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24612. otherVertexData.transform(meshes[index].getWorldMatrix());
  24613. if (vertexData) {
  24614. vertexData.merge(otherVertexData);
  24615. }
  24616. else {
  24617. vertexData = otherVertexData;
  24618. source = meshes[index];
  24619. }
  24620. if (subdivideWithSubMeshes) {
  24621. indiceArray.push(meshes[index].getTotalIndices());
  24622. }
  24623. }
  24624. }
  24625. if (!meshSubclass) {
  24626. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24627. }
  24628. vertexData.applyToMesh(meshSubclass);
  24629. // Setting properties
  24630. meshSubclass.material = source.material;
  24631. meshSubclass.checkCollisions = source.checkCollisions;
  24632. // Cleaning
  24633. if (disposeSource) {
  24634. for (index = 0; index < meshes.length; index++) {
  24635. if (meshes[index]) {
  24636. meshes[index].dispose();
  24637. }
  24638. }
  24639. }
  24640. // Subdivide
  24641. if (subdivideWithSubMeshes) {
  24642. //-- Suppresions du submesh global
  24643. meshSubclass.releaseSubMeshes();
  24644. index = 0;
  24645. var offset = 0;
  24646. //-- aplique la subdivision en fonction du tableau d'indices
  24647. while (index < indiceArray.length) {
  24648. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24649. offset += indiceArray[index];
  24650. index++;
  24651. }
  24652. }
  24653. return meshSubclass;
  24654. };
  24655. return Mesh;
  24656. }(BABYLON.AbstractMesh));
  24657. // Consts
  24658. Mesh._FRONTSIDE = 0;
  24659. Mesh._BACKSIDE = 1;
  24660. Mesh._DOUBLESIDE = 2;
  24661. Mesh._DEFAULTSIDE = 0;
  24662. Mesh._NO_CAP = 0;
  24663. Mesh._CAP_START = 1;
  24664. Mesh._CAP_END = 2;
  24665. Mesh._CAP_ALL = 3;
  24666. BABYLON.Mesh = Mesh;
  24667. })(BABYLON || (BABYLON = {}));
  24668. //# sourceMappingURL=babylon.mesh.js.map
  24669. var BABYLON;
  24670. (function (BABYLON) {
  24671. var SubMesh = (function () {
  24672. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24673. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24674. this.materialIndex = materialIndex;
  24675. this.verticesStart = verticesStart;
  24676. this.verticesCount = verticesCount;
  24677. this.indexStart = indexStart;
  24678. this.indexCount = indexCount;
  24679. this._renderId = 0;
  24680. this._mesh = mesh;
  24681. this._renderingMesh = renderingMesh || mesh;
  24682. mesh.subMeshes.push(this);
  24683. this._trianglePlanes = [];
  24684. this._id = mesh.subMeshes.length - 1;
  24685. if (createBoundingBox) {
  24686. this.refreshBoundingInfo();
  24687. mesh.computeWorldMatrix(true);
  24688. }
  24689. }
  24690. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24691. get: function () {
  24692. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. /**
  24698. * Returns the submesh BoudingInfo object.
  24699. */
  24700. SubMesh.prototype.getBoundingInfo = function () {
  24701. if (this.IsGlobal) {
  24702. return this._mesh.getBoundingInfo();
  24703. }
  24704. return this._boundingInfo;
  24705. };
  24706. /**
  24707. * Sets the submesh BoundingInfo.
  24708. * Return the SubMesh.
  24709. */
  24710. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24711. this._boundingInfo = boundingInfo;
  24712. return this;
  24713. };
  24714. /**
  24715. * Returns the mesh of the current submesh.
  24716. */
  24717. SubMesh.prototype.getMesh = function () {
  24718. return this._mesh;
  24719. };
  24720. /**
  24721. * Returns the rendering mesh of the submesh.
  24722. */
  24723. SubMesh.prototype.getRenderingMesh = function () {
  24724. return this._renderingMesh;
  24725. };
  24726. /**
  24727. * Returns the submesh material.
  24728. */
  24729. SubMesh.prototype.getMaterial = function () {
  24730. var rootMaterial = this._renderingMesh.material;
  24731. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  24732. var multiMaterial = rootMaterial;
  24733. return multiMaterial.getSubMaterial(this.materialIndex);
  24734. }
  24735. if (!rootMaterial) {
  24736. return this._mesh.getScene().defaultMaterial;
  24737. }
  24738. return rootMaterial;
  24739. };
  24740. // Methods
  24741. /**
  24742. * Sets a new updated BoundingInfo object to the submesh.
  24743. * Returns the SubMesh.
  24744. */
  24745. SubMesh.prototype.refreshBoundingInfo = function () {
  24746. this._lastColliderWorldVertices = null;
  24747. if (this.IsGlobal) {
  24748. return;
  24749. }
  24750. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24751. if (!data) {
  24752. this._boundingInfo = this._mesh._boundingInfo;
  24753. return;
  24754. }
  24755. var indices = this._renderingMesh.getIndices();
  24756. var extend;
  24757. //is this the only submesh?
  24758. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24759. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24760. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24761. }
  24762. else {
  24763. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24764. }
  24765. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24766. return this;
  24767. };
  24768. SubMesh.prototype._checkCollision = function (collider) {
  24769. return this.getBoundingInfo()._checkCollision(collider);
  24770. };
  24771. /**
  24772. * Updates the submesh BoundingInfo.
  24773. * Returns the Submesh.
  24774. */
  24775. SubMesh.prototype.updateBoundingInfo = function (world) {
  24776. if (!this.getBoundingInfo()) {
  24777. this.refreshBoundingInfo();
  24778. }
  24779. this.getBoundingInfo().update(world);
  24780. return this;
  24781. };
  24782. /**
  24783. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24784. * Boolean returned.
  24785. */
  24786. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24787. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24788. };
  24789. /**
  24790. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24791. * Boolean returned.
  24792. */
  24793. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24794. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24795. };
  24796. /**
  24797. * Renders the submesh.
  24798. * Returns it.
  24799. */
  24800. SubMesh.prototype.render = function (enableAlphaMode) {
  24801. this._renderingMesh.render(this, enableAlphaMode);
  24802. return this;
  24803. };
  24804. /**
  24805. * Returns a new Index Buffer.
  24806. * Type returned : WebGLBuffer.
  24807. */
  24808. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24809. if (!this._linesIndexBuffer) {
  24810. var linesIndices = [];
  24811. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24812. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24813. }
  24814. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24815. this.linesIndexCount = linesIndices.length;
  24816. }
  24817. return this._linesIndexBuffer;
  24818. };
  24819. /**
  24820. * True is the passed Ray intersects the submesh bounding box.
  24821. * Boolean returned.
  24822. */
  24823. SubMesh.prototype.canIntersects = function (ray) {
  24824. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24825. };
  24826. /**
  24827. * Returns an object IntersectionInfo.
  24828. */
  24829. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24830. var intersectInfo = null;
  24831. // LineMesh first as it's also a Mesh...
  24832. if (this._mesh instanceof BABYLON.LinesMesh) {
  24833. var lineMesh = this._mesh;
  24834. // Line test
  24835. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24836. var p0 = positions[indices[index]];
  24837. var p1 = positions[indices[index + 1]];
  24838. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24839. if (length < 0) {
  24840. continue;
  24841. }
  24842. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24843. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24844. if (fastCheck) {
  24845. break;
  24846. }
  24847. }
  24848. }
  24849. }
  24850. else {
  24851. // Triangles test
  24852. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24853. var p0 = positions[indices[index]];
  24854. var p1 = positions[indices[index + 1]];
  24855. var p2 = positions[indices[index + 2]];
  24856. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24857. if (currentIntersectInfo) {
  24858. if (currentIntersectInfo.distance < 0) {
  24859. continue;
  24860. }
  24861. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24862. intersectInfo = currentIntersectInfo;
  24863. intersectInfo.faceId = index / 3;
  24864. if (fastCheck) {
  24865. break;
  24866. }
  24867. }
  24868. }
  24869. }
  24870. }
  24871. return intersectInfo;
  24872. };
  24873. // Clone
  24874. /**
  24875. * Creates a new Submesh from the passed Mesh.
  24876. */
  24877. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24878. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24879. if (!this.IsGlobal) {
  24880. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24881. }
  24882. return result;
  24883. };
  24884. // Dispose
  24885. /**
  24886. * Disposes the Submesh.
  24887. * Returns nothing.
  24888. */
  24889. SubMesh.prototype.dispose = function () {
  24890. if (this._linesIndexBuffer) {
  24891. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24892. this._linesIndexBuffer = null;
  24893. }
  24894. // Remove from mesh
  24895. var index = this._mesh.subMeshes.indexOf(this);
  24896. this._mesh.subMeshes.splice(index, 1);
  24897. };
  24898. // Statics
  24899. /**
  24900. * Creates a new Submesh from the passed parameters :
  24901. * - materialIndex (integer) : the index of the main mesh material.
  24902. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24903. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24904. * - mesh (Mesh) : the main mesh to create the submesh from.
  24905. * - renderingMesh (optional Mesh) : rendering mesh.
  24906. */
  24907. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24908. var minVertexIndex = Number.MAX_VALUE;
  24909. var maxVertexIndex = -Number.MAX_VALUE;
  24910. renderingMesh = renderingMesh || mesh;
  24911. var indices = renderingMesh.getIndices();
  24912. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24913. var vertexIndex = indices[index];
  24914. if (vertexIndex < minVertexIndex)
  24915. minVertexIndex = vertexIndex;
  24916. if (vertexIndex > maxVertexIndex)
  24917. maxVertexIndex = vertexIndex;
  24918. }
  24919. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24920. };
  24921. return SubMesh;
  24922. }());
  24923. BABYLON.SubMesh = SubMesh;
  24924. })(BABYLON || (BABYLON = {}));
  24925. //# sourceMappingURL=babylon.subMesh.js.map
  24926. var BABYLON;
  24927. (function (BABYLON) {
  24928. var MeshBuilder = (function () {
  24929. function MeshBuilder() {
  24930. }
  24931. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  24932. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  24933. return BABYLON.Mesh.DOUBLESIDE;
  24934. }
  24935. if (orientation === undefined || orientation === null) {
  24936. return BABYLON.Mesh.FRONTSIDE;
  24937. }
  24938. return orientation;
  24939. };
  24940. /**
  24941. * Creates a box mesh.
  24942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  24943. * The parameter `size` sets the size (float) of each box side (default 1).
  24944. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  24945. * 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).
  24946. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  24947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24950. */
  24951. MeshBuilder.CreateBox = function (name, options, scene) {
  24952. var box = new BABYLON.Mesh(name, scene);
  24953. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  24954. box.sideOrientation = options.sideOrientation;
  24955. var vertexData = BABYLON.VertexData.CreateBox(options);
  24956. vertexData.applyToMesh(box, options.updatable);
  24957. return box;
  24958. };
  24959. /**
  24960. * Creates a sphere mesh.
  24961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  24962. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24963. * 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`).
  24964. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24965. * 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
  24966. * 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).
  24967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24970. */
  24971. MeshBuilder.CreateSphere = function (name, options, scene) {
  24972. var sphere = new BABYLON.Mesh(name, scene);
  24973. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  24974. sphere.sideOrientation = options.sideOrientation;
  24975. var vertexData = BABYLON.VertexData.CreateSphere(options);
  24976. vertexData.applyToMesh(sphere, options.updatable);
  24977. return sphere;
  24978. };
  24979. /**
  24980. * Creates a plane polygonal mesh. By default, this is a disc.
  24981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  24982. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24983. * 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.
  24984. * 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
  24985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24988. */
  24989. MeshBuilder.CreateDisc = function (name, options, scene) {
  24990. var disc = new BABYLON.Mesh(name, scene);
  24991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  24992. disc.sideOrientation = options.sideOrientation;
  24993. var vertexData = BABYLON.VertexData.CreateDisc(options);
  24994. vertexData.applyToMesh(disc, options.updatable);
  24995. return disc;
  24996. };
  24997. /**
  24998. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25000. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25001. * 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`).
  25002. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25003. * 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.
  25004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25007. */
  25008. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25009. var sphere = new BABYLON.Mesh(name, scene);
  25010. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25011. sphere.sideOrientation = options.sideOrientation;
  25012. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25013. vertexData.applyToMesh(sphere, options.updatable);
  25014. return sphere;
  25015. };
  25016. ;
  25017. /**
  25018. * Creates a ribbon mesh.
  25019. * 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.
  25020. *
  25021. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25022. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25023. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25024. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25025. * 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.
  25026. * 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.
  25027. * 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
  25028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25030. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25032. */
  25033. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25034. var pathArray = options.pathArray;
  25035. var closeArray = options.closeArray;
  25036. var closePath = options.closePath;
  25037. var offset = options.offset;
  25038. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25039. var instance = options.instance;
  25040. var updatable = options.updatable;
  25041. if (instance) {
  25042. // positionFunction : ribbon case
  25043. // only pathArray and sideOrientation parameters are taken into account for positions update
  25044. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25045. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25046. var positionFunction = function (positions) {
  25047. var minlg = pathArray[0].length;
  25048. var i = 0;
  25049. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25050. for (var si = 1; si <= ns; si++) {
  25051. for (var p = 0; p < pathArray.length; p++) {
  25052. var path = pathArray[p];
  25053. var l = path.length;
  25054. minlg = (minlg < l) ? minlg : l;
  25055. var j = 0;
  25056. while (j < minlg) {
  25057. positions[i] = path[j].x;
  25058. positions[i + 1] = path[j].y;
  25059. positions[i + 2] = path[j].z;
  25060. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25061. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25062. }
  25063. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25064. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25065. }
  25066. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25067. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25068. }
  25069. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25070. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25071. }
  25072. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25073. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25074. }
  25075. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25076. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25077. }
  25078. j++;
  25079. i += 3;
  25080. }
  25081. if (instance._closePath) {
  25082. positions[i] = path[0].x;
  25083. positions[i + 1] = path[0].y;
  25084. positions[i + 2] = path[0].z;
  25085. i += 3;
  25086. }
  25087. }
  25088. }
  25089. };
  25090. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25091. positionFunction(positions);
  25092. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25093. instance._boundingInfo.update(instance._worldMatrix);
  25094. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25095. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25096. var indices = instance.getIndices();
  25097. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25098. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25099. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25100. if (instance._closePath) {
  25101. var indexFirst = 0;
  25102. var indexLast = 0;
  25103. for (var p = 0; p < pathArray.length; p++) {
  25104. indexFirst = instance._idx[p] * 3;
  25105. if (p + 1 < pathArray.length) {
  25106. indexLast = (instance._idx[p + 1] - 1) * 3;
  25107. }
  25108. else {
  25109. indexLast = normals.length - 3;
  25110. }
  25111. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25112. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25113. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25114. normals[indexLast] = normals[indexFirst];
  25115. normals[indexLast + 1] = normals[indexFirst + 1];
  25116. normals[indexLast + 2] = normals[indexFirst + 2];
  25117. }
  25118. }
  25119. if (!(instance.areNormalsFrozen)) {
  25120. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25121. }
  25122. }
  25123. return instance;
  25124. }
  25125. else {
  25126. var ribbon = new BABYLON.Mesh(name, scene);
  25127. ribbon.sideOrientation = sideOrientation;
  25128. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25129. if (closePath) {
  25130. ribbon._idx = vertexData._idx;
  25131. }
  25132. ribbon._closePath = closePath;
  25133. ribbon._closeArray = closeArray;
  25134. vertexData.applyToMesh(ribbon, updatable);
  25135. return ribbon;
  25136. }
  25137. };
  25138. /**
  25139. * Creates a cylinder or a cone mesh.
  25140. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25141. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25142. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25143. * 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.
  25144. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25145. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25146. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25147. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25148. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25149. * 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).
  25150. * 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
  25151. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25152. * 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
  25153. * 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.
  25154. * If `enclose` is false, a ring surface is one element.
  25155. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25156. * 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
  25157. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25160. */
  25161. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25162. var cylinder = new BABYLON.Mesh(name, scene);
  25163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25164. cylinder.sideOrientation = options.sideOrientation;
  25165. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25166. vertexData.applyToMesh(cylinder, options.updatable);
  25167. return cylinder;
  25168. };
  25169. /**
  25170. * Creates a torus mesh.
  25171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25172. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25173. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25174. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25176. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25178. */
  25179. MeshBuilder.CreateTorus = function (name, options, scene) {
  25180. var torus = new BABYLON.Mesh(name, scene);
  25181. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25182. torus.sideOrientation = options.sideOrientation;
  25183. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25184. vertexData.applyToMesh(torus, options.updatable);
  25185. return torus;
  25186. };
  25187. /**
  25188. * Creates a torus knot mesh.
  25189. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25190. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25191. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25192. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25193. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25195. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25197. */
  25198. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25199. var torusKnot = new BABYLON.Mesh(name, scene);
  25200. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25201. torusKnot.sideOrientation = options.sideOrientation;
  25202. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25203. vertexData.applyToMesh(torusKnot, options.updatable);
  25204. return torusKnot;
  25205. };
  25206. /**
  25207. * Creates a line system mesh.
  25208. * A line system is a pool of many lines gathered in a single mesh.
  25209. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25210. * 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.
  25211. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25212. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25213. * 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
  25214. * 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
  25215. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25217. */
  25218. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25219. var instance = options.instance;
  25220. var lines = options.lines;
  25221. if (instance) {
  25222. var positionFunction = function (positions) {
  25223. var i = 0;
  25224. for (var l = 0; l < lines.length; l++) {
  25225. var points = lines[l];
  25226. for (var p = 0; p < points.length; p++) {
  25227. positions[i] = points[p].x;
  25228. positions[i + 1] = points[p].y;
  25229. positions[i + 2] = points[p].z;
  25230. i += 3;
  25231. }
  25232. }
  25233. };
  25234. instance.updateMeshPositions(positionFunction, false);
  25235. return instance;
  25236. }
  25237. // line system creation
  25238. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25239. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25240. vertexData.applyToMesh(lineSystem, options.updatable);
  25241. return lineSystem;
  25242. };
  25243. /**
  25244. * Creates a line mesh.
  25245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25246. * 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.
  25247. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25248. * The parameter `points` is an array successive Vector3.
  25249. * 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
  25250. * When updating an instance, remember that only point positions can change, not the number of points.
  25251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25252. */
  25253. MeshBuilder.CreateLines = function (name, options, scene) {
  25254. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25255. return lines;
  25256. };
  25257. /**
  25258. * Creates a dashed line mesh.
  25259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  25260. * 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.
  25261. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25262. * The parameter `points` is an array successive Vector3.
  25263. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25264. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25265. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25266. * 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
  25267. * When updating an instance, remember that only point positions can change, not the number of points.
  25268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25269. */
  25270. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  25271. var points = options.points;
  25272. var instance = options.instance;
  25273. var gapSize = options.gapSize;
  25274. var dashNb = options.dashNb;
  25275. var dashSize = options.dashSize;
  25276. if (instance) {
  25277. var positionFunction = function (positions) {
  25278. var curvect = BABYLON.Vector3.Zero();
  25279. var nbSeg = positions.length / 6;
  25280. var lg = 0;
  25281. var nb = 0;
  25282. var shft = 0;
  25283. var dashshft = 0;
  25284. var curshft = 0;
  25285. var p = 0;
  25286. var i = 0;
  25287. var j = 0;
  25288. for (i = 0; i < points.length - 1; i++) {
  25289. points[i + 1].subtractToRef(points[i], curvect);
  25290. lg += curvect.length();
  25291. }
  25292. shft = lg / nbSeg;
  25293. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  25294. for (i = 0; i < points.length - 1; i++) {
  25295. points[i + 1].subtractToRef(points[i], curvect);
  25296. nb = Math.floor(curvect.length() / shft);
  25297. curvect.normalize();
  25298. j = 0;
  25299. while (j < nb && p < positions.length) {
  25300. curshft = shft * j;
  25301. positions[p] = points[i].x + curshft * curvect.x;
  25302. positions[p + 1] = points[i].y + curshft * curvect.y;
  25303. positions[p + 2] = points[i].z + curshft * curvect.z;
  25304. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  25305. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  25306. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  25307. p += 6;
  25308. j++;
  25309. }
  25310. }
  25311. while (p < positions.length) {
  25312. positions[p] = points[i].x;
  25313. positions[p + 1] = points[i].y;
  25314. positions[p + 2] = points[i].z;
  25315. p += 3;
  25316. }
  25317. };
  25318. instance.updateMeshPositions(positionFunction, false);
  25319. return instance;
  25320. }
  25321. // dashed lines creation
  25322. var dashedLines = new BABYLON.LinesMesh(name, scene);
  25323. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  25324. vertexData.applyToMesh(dashedLines, options.updatable);
  25325. dashedLines.dashSize = dashSize;
  25326. dashedLines.gapSize = gapSize;
  25327. return dashedLines;
  25328. };
  25329. /**
  25330. * Creates an extruded shape mesh.
  25331. * 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.
  25332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  25333. *
  25334. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25335. * 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
  25336. * extruded along the Z axis.
  25337. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25338. * 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.
  25339. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25340. * 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
  25341. * 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
  25342. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25344. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25345. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25347. */
  25348. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  25349. var path = options.path;
  25350. var shape = options.shape;
  25351. var scale = options.scale || 1;
  25352. var rotation = options.rotation || 0;
  25353. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25354. var updatable = options.updatable;
  25355. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25356. var instance = options.instance;
  25357. var invertUV = options.invertUV || false;
  25358. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  25359. };
  25360. /**
  25361. * Creates an custom extruded shape mesh.
  25362. * 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.
  25363. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  25364. *
  25365. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25366. * 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
  25367. * extruded along the Z axis.
  25368. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25369. * 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
  25370. * and the distance of this point from the begining of the path :
  25371. * ```javascript
  25372. * var rotationFunction = function(i, distance) {
  25373. * // do things
  25374. * return rotationValue; }
  25375. * ```
  25376. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25377. * 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
  25378. * and the distance of this point from the begining of the path :
  25379. * ```javascript
  25380. * var scaleFunction = function(i, distance) {
  25381. * // do things
  25382. * return scaleValue;}
  25383. * ```
  25384. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25385. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25386. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25387. * 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
  25388. * 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
  25389. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25391. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25392. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25394. */
  25395. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  25396. var path = options.path;
  25397. var shape = options.shape;
  25398. var scaleFunction = options.scaleFunction || (function () { return 1; });
  25399. var rotationFunction = options.rotationFunction || (function () { return 0; });
  25400. var ribbonCloseArray = options.ribbonCloseArray || false;
  25401. var ribbonClosePath = options.ribbonClosePath || false;
  25402. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25403. var updatable = options.updatable;
  25404. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25405. var instance = options.instance;
  25406. var invertUV = options.invertUV || false;
  25407. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  25408. };
  25409. /**
  25410. * Creates lathe mesh.
  25411. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25412. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  25413. *
  25414. * 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
  25415. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25416. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25417. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25418. * 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.
  25419. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  25420. * 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
  25421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25423. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25425. */
  25426. MeshBuilder.CreateLathe = function (name, options, scene) {
  25427. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  25428. var closed = (options.closed === undefined) ? true : options.closed;
  25429. var shape = options.shape;
  25430. var radius = options.radius || 1;
  25431. var tessellation = options.tessellation || 64;
  25432. var updatable = options.updatable;
  25433. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25434. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25435. var pi2 = Math.PI * 2;
  25436. var paths = new Array();
  25437. var invertUV = options.invertUV || false;
  25438. var i = 0;
  25439. var p = 0;
  25440. var step = pi2 / tessellation * arc;
  25441. var rotated;
  25442. var path = new Array();
  25443. ;
  25444. for (i = 0; i <= tessellation; i++) {
  25445. var path = [];
  25446. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  25447. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  25448. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  25449. }
  25450. for (p = 0; p < shape.length; p++) {
  25451. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  25452. path.push(rotated);
  25453. }
  25454. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  25455. 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));
  25456. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  25457. }
  25458. paths.push(path);
  25459. }
  25460. // lathe ribbon
  25461. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  25462. return lathe;
  25463. };
  25464. /**
  25465. * Creates a plane mesh.
  25466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25467. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25468. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  25469. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  25470. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25471. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25473. */
  25474. MeshBuilder.CreatePlane = function (name, options, scene) {
  25475. var plane = new BABYLON.Mesh(name, scene);
  25476. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25477. plane.sideOrientation = options.sideOrientation;
  25478. var vertexData = BABYLON.VertexData.CreatePlane(options);
  25479. vertexData.applyToMesh(plane, options.updatable);
  25480. if (options.sourcePlane) {
  25481. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  25482. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  25483. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  25484. plane.rotate(vectorProduct, product);
  25485. }
  25486. return plane;
  25487. };
  25488. /**
  25489. * Creates a ground mesh.
  25490. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25491. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25492. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25494. */
  25495. MeshBuilder.CreateGround = function (name, options, scene) {
  25496. var ground = new BABYLON.GroundMesh(name, scene);
  25497. ground._setReady(false);
  25498. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25499. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25500. ground._width = options.width || 1;
  25501. ground._height = options.height || 1;
  25502. ground._maxX = ground._width / 2;
  25503. ground._maxZ = ground._height / 2;
  25504. ground._minX = -ground._maxX;
  25505. ground._minZ = -ground._maxZ;
  25506. var vertexData = BABYLON.VertexData.CreateGround(options);
  25507. vertexData.applyToMesh(ground, options.updatable);
  25508. ground._setReady(true);
  25509. return ground;
  25510. };
  25511. /**
  25512. * Creates a tiled ground mesh.
  25513. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  25514. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25515. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25516. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25517. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25518. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25519. * numbers of subdivisions on the ground width and height of each tile.
  25520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25521. */
  25522. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  25523. var tiledGround = new BABYLON.Mesh(name, scene);
  25524. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  25525. vertexData.applyToMesh(tiledGround, options.updatable);
  25526. return tiledGround;
  25527. };
  25528. /**
  25529. * Creates a ground mesh from a height map.
  25530. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25531. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  25532. * The parameter `url` sets the URL of the height map image resource.
  25533. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25534. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25535. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25536. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25537. * 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.
  25538. * 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).
  25539. * This function is passed the newly built mesh :
  25540. * ```javascript
  25541. * function(mesh) { // do things
  25542. * return; }
  25543. * ```
  25544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25545. */
  25546. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  25547. var width = options.width || 10.0;
  25548. var height = options.height || 10.0;
  25549. var subdivisions = options.subdivisions || 1 | 0;
  25550. var minHeight = options.minHeight || 0.0;
  25551. var maxHeight = options.maxHeight || 10.0;
  25552. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25553. var updatable = options.updatable;
  25554. var onReady = options.onReady;
  25555. var ground = new BABYLON.GroundMesh(name, scene);
  25556. ground._subdivisionsX = subdivisions;
  25557. ground._subdivisionsY = subdivisions;
  25558. ground._width = width;
  25559. ground._height = height;
  25560. ground._maxX = ground._width / 2.0;
  25561. ground._maxZ = ground._height / 2.0;
  25562. ground._minX = -ground._maxX;
  25563. ground._minZ = -ground._maxZ;
  25564. ground._setReady(false);
  25565. var onload = function (img) {
  25566. // Getting height map data
  25567. var canvas = document.createElement("canvas");
  25568. var context = canvas.getContext("2d");
  25569. var bufferWidth = img.width;
  25570. var bufferHeight = img.height;
  25571. canvas.width = bufferWidth;
  25572. canvas.height = bufferHeight;
  25573. context.drawImage(img, 0, 0);
  25574. // Create VertexData from map data
  25575. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25576. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  25577. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  25578. width: width, height: height,
  25579. subdivisions: subdivisions,
  25580. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  25581. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  25582. });
  25583. vertexData.applyToMesh(ground, updatable);
  25584. ground._setReady(true);
  25585. //execute ready callback, if set
  25586. if (onReady) {
  25587. onReady(ground);
  25588. }
  25589. };
  25590. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25591. return ground;
  25592. };
  25593. /**
  25594. * Creates a tube mesh.
  25595. * 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.
  25596. *
  25597. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  25598. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25599. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25600. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25601. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25602. * 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.
  25603. * It must return a radius value (positive float) :
  25604. * ```javascript
  25605. * var radiusFunction = function(i, distance) {
  25606. * // do things
  25607. * return radius; }
  25608. * ```
  25609. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  25610. * 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
  25611. * 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
  25612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25614. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25616. */
  25617. MeshBuilder.CreateTube = function (name, options, scene) {
  25618. var path = options.path;
  25619. var radius = options.radius || 1.0;
  25620. var tessellation = options.tessellation || 64 | 0;
  25621. var radiusFunction = options.radiusFunction;
  25622. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25623. var invertUV = options.invertUV || false;
  25624. var updatable = options.updatable;
  25625. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25626. var instance = options.instance;
  25627. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  25628. // tube geometry
  25629. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  25630. var tangents = path3D.getTangents();
  25631. var normals = path3D.getNormals();
  25632. var distances = path3D.getDistances();
  25633. var pi2 = Math.PI * 2;
  25634. var step = pi2 / tessellation * arc;
  25635. var returnRadius = function () { return radius; };
  25636. var radiusFunctionFinal = radiusFunction || returnRadius;
  25637. var circlePath;
  25638. var rad;
  25639. var normal;
  25640. var rotated;
  25641. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25642. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25643. for (var i = 0; i < path.length; i++) {
  25644. rad = radiusFunctionFinal(i, distances[i]); // current radius
  25645. circlePath = Array(); // current circle array
  25646. normal = normals[i]; // current normal
  25647. for (var t = 0; t < tessellation; t++) {
  25648. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  25649. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  25650. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  25651. rotated.scaleInPlace(rad).addInPlace(path[i]);
  25652. circlePath[t] = rotated;
  25653. }
  25654. circlePaths[index] = circlePath;
  25655. index++;
  25656. }
  25657. // cap
  25658. var capPath = function (nbPoints, pathIndex) {
  25659. var pointCap = Array();
  25660. for (var i = 0; i < nbPoints; i++) {
  25661. pointCap.push(path[pathIndex]);
  25662. }
  25663. return pointCap;
  25664. };
  25665. switch (cap) {
  25666. case BABYLON.Mesh.NO_CAP:
  25667. break;
  25668. case BABYLON.Mesh.CAP_START:
  25669. circlePaths[0] = capPath(tessellation, 0);
  25670. circlePaths[1] = circlePaths[2].slice(0);
  25671. break;
  25672. case BABYLON.Mesh.CAP_END:
  25673. circlePaths[index] = circlePaths[index - 1].slice(0);
  25674. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25675. break;
  25676. case BABYLON.Mesh.CAP_ALL:
  25677. circlePaths[0] = capPath(tessellation, 0);
  25678. circlePaths[1] = circlePaths[2].slice(0);
  25679. circlePaths[index] = circlePaths[index - 1].slice(0);
  25680. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25681. break;
  25682. default:
  25683. break;
  25684. }
  25685. return circlePaths;
  25686. };
  25687. var path3D;
  25688. var pathArray;
  25689. if (instance) {
  25690. var arc = options.arc || instance.arc;
  25691. path3D = (instance.path3D).update(path);
  25692. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  25693. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  25694. instance.path3D = path3D;
  25695. instance.pathArray = pathArray;
  25696. instance.arc = arc;
  25697. return instance;
  25698. }
  25699. // tube creation
  25700. path3D = new BABYLON.Path3D(path);
  25701. var newPathArray = new Array();
  25702. cap = (cap < 0 || cap > 3) ? 0 : cap;
  25703. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  25704. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  25705. tube.pathArray = pathArray;
  25706. tube.path3D = path3D;
  25707. tube.tessellation = tessellation;
  25708. tube.cap = cap;
  25709. tube.arc = options.arc;
  25710. return tube;
  25711. };
  25712. /**
  25713. * Creates a polyhedron mesh.
  25714. *
  25715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  25716. * 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
  25717. * to choose the wanted type.
  25718. * The parameter `size` (positive float, default 1) sets the polygon size.
  25719. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25720. * 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`.
  25721. * 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
  25722. * 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)`).
  25723. * 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
  25724. * 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.
  25725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25728. */
  25729. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  25730. var polyhedron = new BABYLON.Mesh(name, scene);
  25731. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25732. polyhedron.sideOrientation = options.sideOrientation;
  25733. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  25734. vertexData.applyToMesh(polyhedron, options.updatable);
  25735. return polyhedron;
  25736. };
  25737. /**
  25738. * Creates a decal mesh.
  25739. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  25740. * 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.
  25741. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25742. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25743. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25744. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25745. */
  25746. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  25747. var indices = sourceMesh.getIndices();
  25748. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25749. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25750. var position = options.position || BABYLON.Vector3.Zero();
  25751. var normal = options.normal || BABYLON.Vector3.Up();
  25752. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  25753. var angle = options.angle || 0;
  25754. // Getting correct rotation
  25755. if (!normal) {
  25756. var target = new BABYLON.Vector3(0, 0, 1);
  25757. var camera = sourceMesh.getScene().activeCamera;
  25758. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  25759. normal = camera.globalPosition.subtract(cameraWorldTarget);
  25760. }
  25761. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  25762. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  25763. var pitch = Math.atan2(normal.y, len);
  25764. // Matrix
  25765. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  25766. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  25767. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  25768. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  25769. var vertexData = new BABYLON.VertexData();
  25770. vertexData.indices = [];
  25771. vertexData.positions = [];
  25772. vertexData.normals = [];
  25773. vertexData.uvs = [];
  25774. var currentVertexDataIndex = 0;
  25775. var extractDecalVector3 = function (indexId) {
  25776. var vertexId = indices[indexId];
  25777. var result = new BABYLON.PositionNormalVertex();
  25778. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  25779. // Send vector to decal local world
  25780. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  25781. // Get normal
  25782. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  25783. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  25784. return result;
  25785. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  25786. var clip = function (vertices, axis) {
  25787. if (vertices.length === 0) {
  25788. return vertices;
  25789. }
  25790. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  25791. var clipVertices = function (v0, v1) {
  25792. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  25793. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  25794. };
  25795. var result = new Array();
  25796. for (var index = 0; index < vertices.length; index += 3) {
  25797. var v1Out;
  25798. var v2Out;
  25799. var v3Out;
  25800. var total = 0;
  25801. var nV1, nV2, nV3, nV4;
  25802. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  25803. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  25804. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  25805. v1Out = d1 > 0;
  25806. v2Out = d2 > 0;
  25807. v3Out = d3 > 0;
  25808. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  25809. switch (total) {
  25810. case 0:
  25811. result.push(vertices[index]);
  25812. result.push(vertices[index + 1]);
  25813. result.push(vertices[index + 2]);
  25814. break;
  25815. case 1:
  25816. if (v1Out) {
  25817. nV1 = vertices[index + 1];
  25818. nV2 = vertices[index + 2];
  25819. nV3 = clipVertices(vertices[index], nV1);
  25820. nV4 = clipVertices(vertices[index], nV2);
  25821. }
  25822. if (v2Out) {
  25823. nV1 = vertices[index];
  25824. nV2 = vertices[index + 2];
  25825. nV3 = clipVertices(vertices[index + 1], nV1);
  25826. nV4 = clipVertices(vertices[index + 1], nV2);
  25827. result.push(nV3);
  25828. result.push(nV2.clone());
  25829. result.push(nV1.clone());
  25830. result.push(nV2.clone());
  25831. result.push(nV3.clone());
  25832. result.push(nV4);
  25833. break;
  25834. }
  25835. if (v3Out) {
  25836. nV1 = vertices[index];
  25837. nV2 = vertices[index + 1];
  25838. nV3 = clipVertices(vertices[index + 2], nV1);
  25839. nV4 = clipVertices(vertices[index + 2], nV2);
  25840. }
  25841. result.push(nV1.clone());
  25842. result.push(nV2.clone());
  25843. result.push(nV3);
  25844. result.push(nV4);
  25845. result.push(nV3.clone());
  25846. result.push(nV2.clone());
  25847. break;
  25848. case 2:
  25849. if (!v1Out) {
  25850. nV1 = vertices[index].clone();
  25851. nV2 = clipVertices(nV1, vertices[index + 1]);
  25852. nV3 = clipVertices(nV1, vertices[index + 2]);
  25853. result.push(nV1);
  25854. result.push(nV2);
  25855. result.push(nV3);
  25856. }
  25857. if (!v2Out) {
  25858. nV1 = vertices[index + 1].clone();
  25859. nV2 = clipVertices(nV1, vertices[index + 2]);
  25860. nV3 = clipVertices(nV1, vertices[index]);
  25861. result.push(nV1);
  25862. result.push(nV2);
  25863. result.push(nV3);
  25864. }
  25865. if (!v3Out) {
  25866. nV1 = vertices[index + 2].clone();
  25867. nV2 = clipVertices(nV1, vertices[index]);
  25868. nV3 = clipVertices(nV1, vertices[index + 1]);
  25869. result.push(nV1);
  25870. result.push(nV2);
  25871. result.push(nV3);
  25872. }
  25873. break;
  25874. case 3:
  25875. break;
  25876. }
  25877. }
  25878. return result;
  25879. };
  25880. for (var index = 0; index < indices.length; index += 3) {
  25881. var faceVertices = new Array();
  25882. faceVertices.push(extractDecalVector3(index));
  25883. faceVertices.push(extractDecalVector3(index + 1));
  25884. faceVertices.push(extractDecalVector3(index + 2));
  25885. // Clip
  25886. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  25887. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  25888. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  25889. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  25890. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  25891. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  25892. if (faceVertices.length === 0) {
  25893. continue;
  25894. }
  25895. // Add UVs and get back to world
  25896. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  25897. var vertex = faceVertices[vIndex];
  25898. //TODO check for Int32Array | Uint32Array | Uint16Array
  25899. vertexData.indices.push(currentVertexDataIndex);
  25900. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  25901. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  25902. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  25903. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  25904. currentVertexDataIndex++;
  25905. }
  25906. }
  25907. // Return mesh
  25908. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  25909. vertexData.applyToMesh(decal);
  25910. decal.position = position.clone();
  25911. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  25912. return decal;
  25913. };
  25914. // Privates
  25915. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  25916. // extrusion geometry
  25917. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  25918. var tangents = path3D.getTangents();
  25919. var normals = path3D.getNormals();
  25920. var binormals = path3D.getBinormals();
  25921. var distances = path3D.getDistances();
  25922. var angle = 0;
  25923. var returnScale = function () { return scale; };
  25924. var returnRotation = function () { return rotation; };
  25925. var rotate = custom ? rotateFunction : returnRotation;
  25926. var scl = custom ? scaleFunction : returnScale;
  25927. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25928. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25929. for (var i = 0; i < curve.length; i++) {
  25930. var shapePath = new Array();
  25931. var angleStep = rotate(i, distances[i]);
  25932. var scaleRatio = scl(i, distances[i]);
  25933. for (var p = 0; p < shape.length; p++) {
  25934. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  25935. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  25936. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  25937. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  25938. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  25939. shapePath[p] = rotated;
  25940. }
  25941. shapePaths[index] = shapePath;
  25942. angle += angleStep;
  25943. index++;
  25944. }
  25945. // cap
  25946. var capPath = function (shapePath) {
  25947. var pointCap = Array();
  25948. var barycenter = BABYLON.Vector3.Zero();
  25949. var i;
  25950. for (i = 0; i < shapePath.length; i++) {
  25951. barycenter.addInPlace(shapePath[i]);
  25952. }
  25953. barycenter.scaleInPlace(1.0 / shapePath.length);
  25954. for (i = 0; i < shapePath.length; i++) {
  25955. pointCap.push(barycenter);
  25956. }
  25957. return pointCap;
  25958. };
  25959. switch (cap) {
  25960. case BABYLON.Mesh.NO_CAP:
  25961. break;
  25962. case BABYLON.Mesh.CAP_START:
  25963. shapePaths[0] = capPath(shapePaths[2]);
  25964. shapePaths[1] = shapePaths[2];
  25965. break;
  25966. case BABYLON.Mesh.CAP_END:
  25967. shapePaths[index] = shapePaths[index - 1];
  25968. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  25969. break;
  25970. case BABYLON.Mesh.CAP_ALL:
  25971. shapePaths[0] = capPath(shapePaths[2]);
  25972. shapePaths[1] = shapePaths[2];
  25973. shapePaths[index] = shapePaths[index - 1];
  25974. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  25975. break;
  25976. default:
  25977. break;
  25978. }
  25979. return shapePaths;
  25980. };
  25981. var path3D;
  25982. var pathArray;
  25983. if (instance) {
  25984. path3D = (instance.path3D).update(curve);
  25985. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  25986. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  25987. return instance;
  25988. }
  25989. // extruded shape creation
  25990. path3D = new BABYLON.Path3D(curve);
  25991. var newShapePaths = new Array();
  25992. cap = (cap < 0 || cap > 3) ? 0 : cap;
  25993. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  25994. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  25995. extrudedGeneric.pathArray = pathArray;
  25996. extrudedGeneric.path3D = path3D;
  25997. extrudedGeneric.cap = cap;
  25998. return extrudedGeneric;
  25999. };
  26000. return MeshBuilder;
  26001. }());
  26002. BABYLON.MeshBuilder = MeshBuilder;
  26003. })(BABYLON || (BABYLON = {}));
  26004. //# sourceMappingURL=babylon.meshBuilder.js.map
  26005. var BABYLON;
  26006. (function (BABYLON) {
  26007. var BaseTexture = (function () {
  26008. function BaseTexture(scene) {
  26009. this.hasAlpha = false;
  26010. this.getAlphaFromRGB = false;
  26011. this.level = 1;
  26012. this.coordinatesIndex = 0;
  26013. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26014. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26015. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26016. this.anisotropicFilteringLevel = 4;
  26017. this.isCube = false;
  26018. this.isRenderTarget = false;
  26019. this.animations = new Array();
  26020. /**
  26021. * An event triggered when the texture is disposed.
  26022. * @type {BABYLON.Observable}
  26023. */
  26024. this.onDisposeObservable = new BABYLON.Observable();
  26025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26026. this._scene = scene;
  26027. this._scene.textures.push(this);
  26028. this._uid = null;
  26029. }
  26030. Object.defineProperty(BaseTexture.prototype, "uid", {
  26031. get: function () {
  26032. if (!this._uid) {
  26033. this._uid = BABYLON.Tools.RandomId();
  26034. }
  26035. return this._uid;
  26036. },
  26037. enumerable: true,
  26038. configurable: true
  26039. });
  26040. BaseTexture.prototype.toString = function () {
  26041. return this.name;
  26042. };
  26043. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26044. set: function (callback) {
  26045. if (this._onDisposeObserver) {
  26046. this.onDisposeObservable.remove(this._onDisposeObserver);
  26047. }
  26048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. BaseTexture.prototype.getScene = function () {
  26054. return this._scene;
  26055. };
  26056. BaseTexture.prototype.getTextureMatrix = function () {
  26057. return null;
  26058. };
  26059. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26060. return null;
  26061. };
  26062. BaseTexture.prototype.getInternalTexture = function () {
  26063. return this._texture;
  26064. };
  26065. BaseTexture.prototype.isReady = function () {
  26066. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26067. return true;
  26068. }
  26069. if (this._texture) {
  26070. return this._texture.isReady;
  26071. }
  26072. return false;
  26073. };
  26074. BaseTexture.prototype.getSize = function () {
  26075. if (this._texture._width) {
  26076. return new BABYLON.Size(this._texture._width, this._texture._height);
  26077. }
  26078. if (this._texture._size) {
  26079. return new BABYLON.Size(this._texture._size, this._texture._size);
  26080. }
  26081. return BABYLON.Size.Zero();
  26082. };
  26083. BaseTexture.prototype.getBaseSize = function () {
  26084. if (!this.isReady() || !this._texture)
  26085. return BABYLON.Size.Zero();
  26086. if (this._texture._size) {
  26087. return new BABYLON.Size(this._texture._size, this._texture._size);
  26088. }
  26089. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26090. };
  26091. BaseTexture.prototype.scale = function (ratio) {
  26092. };
  26093. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26094. get: function () {
  26095. return false;
  26096. },
  26097. enumerable: true,
  26098. configurable: true
  26099. });
  26100. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26101. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26102. for (var index = 0; index < texturesCache.length; index++) {
  26103. var texturesCacheEntry = texturesCache[index];
  26104. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26105. texturesCache.splice(index, 1);
  26106. return;
  26107. }
  26108. }
  26109. };
  26110. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26111. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26112. for (var index = 0; index < texturesCache.length; index++) {
  26113. var texturesCacheEntry = texturesCache[index];
  26114. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26115. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26116. texturesCacheEntry.references++;
  26117. return texturesCacheEntry;
  26118. }
  26119. }
  26120. }
  26121. return null;
  26122. };
  26123. BaseTexture.prototype.delayLoad = function () {
  26124. };
  26125. BaseTexture.prototype.clone = function () {
  26126. return null;
  26127. };
  26128. BaseTexture.prototype.releaseInternalTexture = function () {
  26129. if (this._texture) {
  26130. this._scene.getEngine().releaseInternalTexture(this._texture);
  26131. delete this._texture;
  26132. }
  26133. };
  26134. BaseTexture.prototype.dispose = function () {
  26135. // Animations
  26136. this.getScene().stopAnimation(this);
  26137. // Remove from scene
  26138. var index = this._scene.textures.indexOf(this);
  26139. if (index >= 0) {
  26140. this._scene.textures.splice(index, 1);
  26141. }
  26142. if (this._texture === undefined) {
  26143. return;
  26144. }
  26145. // Release
  26146. this.releaseInternalTexture();
  26147. // Callback
  26148. this.onDisposeObservable.notifyObservers(this);
  26149. this.onDisposeObservable.clear();
  26150. };
  26151. BaseTexture.prototype.serialize = function () {
  26152. if (!this.name) {
  26153. return null;
  26154. }
  26155. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26156. // Animations
  26157. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26158. return serializationObject;
  26159. };
  26160. return BaseTexture;
  26161. }());
  26162. __decorate([
  26163. BABYLON.serialize()
  26164. ], BaseTexture.prototype, "name", void 0);
  26165. __decorate([
  26166. BABYLON.serialize()
  26167. ], BaseTexture.prototype, "hasAlpha", void 0);
  26168. __decorate([
  26169. BABYLON.serialize()
  26170. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26171. __decorate([
  26172. BABYLON.serialize()
  26173. ], BaseTexture.prototype, "level", void 0);
  26174. __decorate([
  26175. BABYLON.serialize()
  26176. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26177. __decorate([
  26178. BABYLON.serialize()
  26179. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26180. __decorate([
  26181. BABYLON.serialize()
  26182. ], BaseTexture.prototype, "wrapU", void 0);
  26183. __decorate([
  26184. BABYLON.serialize()
  26185. ], BaseTexture.prototype, "wrapV", void 0);
  26186. __decorate([
  26187. BABYLON.serialize()
  26188. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26189. __decorate([
  26190. BABYLON.serialize()
  26191. ], BaseTexture.prototype, "isCube", void 0);
  26192. __decorate([
  26193. BABYLON.serialize()
  26194. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26195. BABYLON.BaseTexture = BaseTexture;
  26196. })(BABYLON || (BABYLON = {}));
  26197. //# sourceMappingURL=babylon.baseTexture.js.map
  26198. var BABYLON;
  26199. (function (BABYLON) {
  26200. var Texture = (function (_super) {
  26201. __extends(Texture, _super);
  26202. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26203. if (noMipmap === void 0) { noMipmap = false; }
  26204. if (invertY === void 0) { invertY = true; }
  26205. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26206. if (onLoad === void 0) { onLoad = null; }
  26207. if (onError === void 0) { onError = null; }
  26208. if (buffer === void 0) { buffer = null; }
  26209. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26210. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26211. var _this = _super.call(this, scene) || this;
  26212. _this.uOffset = 0;
  26213. _this.vOffset = 0;
  26214. _this.uScale = 1.0;
  26215. _this.vScale = 1.0;
  26216. _this.uAng = 0;
  26217. _this.vAng = 0;
  26218. _this.wAng = 0;
  26219. _this.name = url;
  26220. _this.url = url;
  26221. _this._noMipmap = noMipmap;
  26222. _this._invertY = invertY;
  26223. _this._samplingMode = samplingMode;
  26224. _this._buffer = buffer;
  26225. _this._deleteBuffer = deleteBuffer;
  26226. _this._format = format;
  26227. if (!url) {
  26228. return _this;
  26229. }
  26230. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26231. var load = function () {
  26232. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26233. _this.onLoadObservable.notifyObservers(true);
  26234. }
  26235. if (onLoad) {
  26236. onLoad();
  26237. }
  26238. };
  26239. if (!_this._texture) {
  26240. if (!scene.useDelayedTextureLoading) {
  26241. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26242. if (deleteBuffer) {
  26243. delete _this._buffer;
  26244. }
  26245. }
  26246. else {
  26247. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26248. _this._delayedOnLoad = load;
  26249. _this._delayedOnError = onError;
  26250. }
  26251. }
  26252. else {
  26253. if (_this._texture.isReady) {
  26254. BABYLON.Tools.SetImmediate(function () { return load(); });
  26255. }
  26256. else {
  26257. _this._texture.onLoadedCallbacks.push(load);
  26258. }
  26259. }
  26260. return _this;
  26261. }
  26262. Object.defineProperty(Texture.prototype, "noMipmap", {
  26263. get: function () {
  26264. return this._noMipmap;
  26265. },
  26266. enumerable: true,
  26267. configurable: true
  26268. });
  26269. Texture.prototype.delayLoad = function () {
  26270. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26271. return;
  26272. }
  26273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26274. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26275. if (!this._texture) {
  26276. 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);
  26277. if (this._deleteBuffer) {
  26278. delete this._buffer;
  26279. }
  26280. }
  26281. };
  26282. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26283. if (!this._texture) {
  26284. return;
  26285. }
  26286. this._samplingMode = samplingMode;
  26287. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26288. };
  26289. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26290. x *= this.uScale;
  26291. y *= this.vScale;
  26292. x -= 0.5 * this.uScale;
  26293. y -= 0.5 * this.vScale;
  26294. z -= 0.5;
  26295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26296. t.x += 0.5 * this.uScale + this.uOffset;
  26297. t.y += 0.5 * this.vScale + this.vOffset;
  26298. t.z += 0.5;
  26299. };
  26300. Texture.prototype.getTextureMatrix = function () {
  26301. if (this.uOffset === this._cachedUOffset &&
  26302. this.vOffset === this._cachedVOffset &&
  26303. this.uScale === this._cachedUScale &&
  26304. this.vScale === this._cachedVScale &&
  26305. this.uAng === this._cachedUAng &&
  26306. this.vAng === this._cachedVAng &&
  26307. this.wAng === this._cachedWAng) {
  26308. return this._cachedTextureMatrix;
  26309. }
  26310. this._cachedUOffset = this.uOffset;
  26311. this._cachedVOffset = this.vOffset;
  26312. this._cachedUScale = this.uScale;
  26313. this._cachedVScale = this.vScale;
  26314. this._cachedUAng = this.uAng;
  26315. this._cachedVAng = this.vAng;
  26316. this._cachedWAng = this.wAng;
  26317. if (!this._cachedTextureMatrix) {
  26318. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26319. this._rowGenerationMatrix = new BABYLON.Matrix();
  26320. this._t0 = BABYLON.Vector3.Zero();
  26321. this._t1 = BABYLON.Vector3.Zero();
  26322. this._t2 = BABYLON.Vector3.Zero();
  26323. }
  26324. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26325. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26326. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26327. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26328. this._t1.subtractInPlace(this._t0);
  26329. this._t2.subtractInPlace(this._t0);
  26330. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26331. this._cachedTextureMatrix.m[0] = this._t1.x;
  26332. this._cachedTextureMatrix.m[1] = this._t1.y;
  26333. this._cachedTextureMatrix.m[2] = this._t1.z;
  26334. this._cachedTextureMatrix.m[4] = this._t2.x;
  26335. this._cachedTextureMatrix.m[5] = this._t2.y;
  26336. this._cachedTextureMatrix.m[6] = this._t2.z;
  26337. this._cachedTextureMatrix.m[8] = this._t0.x;
  26338. this._cachedTextureMatrix.m[9] = this._t0.y;
  26339. this._cachedTextureMatrix.m[10] = this._t0.z;
  26340. return this._cachedTextureMatrix;
  26341. };
  26342. Texture.prototype.getReflectionTextureMatrix = function () {
  26343. if (this.uOffset === this._cachedUOffset &&
  26344. this.vOffset === this._cachedVOffset &&
  26345. this.uScale === this._cachedUScale &&
  26346. this.vScale === this._cachedVScale &&
  26347. this.coordinatesMode === this._cachedCoordinatesMode) {
  26348. return this._cachedTextureMatrix;
  26349. }
  26350. if (!this._cachedTextureMatrix) {
  26351. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26352. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26353. }
  26354. this._cachedCoordinatesMode = this.coordinatesMode;
  26355. switch (this.coordinatesMode) {
  26356. case Texture.PLANAR_MODE:
  26357. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26358. this._cachedTextureMatrix[0] = this.uScale;
  26359. this._cachedTextureMatrix[5] = this.vScale;
  26360. this._cachedTextureMatrix[12] = this.uOffset;
  26361. this._cachedTextureMatrix[13] = this.vOffset;
  26362. break;
  26363. case Texture.PROJECTION_MODE:
  26364. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26365. this._projectionModeMatrix.m[0] = 0.5;
  26366. this._projectionModeMatrix.m[5] = -0.5;
  26367. this._projectionModeMatrix.m[10] = 0.0;
  26368. this._projectionModeMatrix.m[12] = 0.5;
  26369. this._projectionModeMatrix.m[13] = 0.5;
  26370. this._projectionModeMatrix.m[14] = 1.0;
  26371. this._projectionModeMatrix.m[15] = 1.0;
  26372. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26373. break;
  26374. default:
  26375. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26376. break;
  26377. }
  26378. return this._cachedTextureMatrix;
  26379. };
  26380. Texture.prototype.clone = function () {
  26381. var _this = this;
  26382. return BABYLON.SerializationHelper.Clone(function () {
  26383. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26384. }, this);
  26385. };
  26386. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26387. get: function () {
  26388. if (!this._onLoadObservarble) {
  26389. this._onLoadObservarble = new BABYLON.Observable();
  26390. }
  26391. return this._onLoadObservarble;
  26392. },
  26393. enumerable: true,
  26394. configurable: true
  26395. });
  26396. // Statics
  26397. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26398. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26399. if (onLoad === void 0) { onLoad = null; }
  26400. if (onError === void 0) { onError = null; }
  26401. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26402. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26403. };
  26404. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26405. if (parsedTexture.customType) {
  26406. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26407. return customTexture.Parse(parsedTexture, scene, rootUrl);
  26408. }
  26409. if (parsedTexture.isCube) {
  26410. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26411. }
  26412. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26413. return null;
  26414. }
  26415. var texture = BABYLON.SerializationHelper.Parse(function () {
  26416. if (parsedTexture.mirrorPlane) {
  26417. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26418. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26419. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26420. return mirrorTexture;
  26421. }
  26422. else if (parsedTexture.isRenderTarget) {
  26423. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26424. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26425. return renderTargetTexture;
  26426. }
  26427. else {
  26428. var texture;
  26429. if (parsedTexture.base64String) {
  26430. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  26431. }
  26432. else {
  26433. texture = new Texture(rootUrl + parsedTexture.name, scene);
  26434. }
  26435. return texture;
  26436. }
  26437. }, parsedTexture, scene);
  26438. // Animations
  26439. if (parsedTexture.animations) {
  26440. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26441. var parsedAnimation = parsedTexture.animations[animationIndex];
  26442. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26443. }
  26444. }
  26445. return texture;
  26446. };
  26447. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26448. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26449. if (noMipmap === void 0) { noMipmap = false; }
  26450. if (invertY === void 0) { invertY = true; }
  26451. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26452. if (onLoad === void 0) { onLoad = null; }
  26453. if (onError === void 0) { onError = null; }
  26454. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26455. if (name.substr(0, 5) !== "data:") {
  26456. name = "data:" + name;
  26457. }
  26458. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26459. };
  26460. return Texture;
  26461. }(BABYLON.BaseTexture));
  26462. // Constants
  26463. Texture.NEAREST_SAMPLINGMODE = 1;
  26464. Texture.BILINEAR_SAMPLINGMODE = 2;
  26465. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26466. Texture.EXPLICIT_MODE = 0;
  26467. Texture.SPHERICAL_MODE = 1;
  26468. Texture.PLANAR_MODE = 2;
  26469. Texture.CUBIC_MODE = 3;
  26470. Texture.PROJECTION_MODE = 4;
  26471. Texture.SKYBOX_MODE = 5;
  26472. Texture.INVCUBIC_MODE = 6;
  26473. Texture.EQUIRECTANGULAR_MODE = 7;
  26474. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26475. Texture.CLAMP_ADDRESSMODE = 0;
  26476. Texture.WRAP_ADDRESSMODE = 1;
  26477. Texture.MIRROR_ADDRESSMODE = 2;
  26478. __decorate([
  26479. BABYLON.serialize()
  26480. ], Texture.prototype, "url", void 0);
  26481. __decorate([
  26482. BABYLON.serialize()
  26483. ], Texture.prototype, "uOffset", void 0);
  26484. __decorate([
  26485. BABYLON.serialize()
  26486. ], Texture.prototype, "vOffset", void 0);
  26487. __decorate([
  26488. BABYLON.serialize()
  26489. ], Texture.prototype, "uScale", void 0);
  26490. __decorate([
  26491. BABYLON.serialize()
  26492. ], Texture.prototype, "vScale", void 0);
  26493. __decorate([
  26494. BABYLON.serialize()
  26495. ], Texture.prototype, "uAng", void 0);
  26496. __decorate([
  26497. BABYLON.serialize()
  26498. ], Texture.prototype, "vAng", void 0);
  26499. __decorate([
  26500. BABYLON.serialize()
  26501. ], Texture.prototype, "wAng", void 0);
  26502. BABYLON.Texture = Texture;
  26503. })(BABYLON || (BABYLON = {}));
  26504. //# sourceMappingURL=babylon.texture.js.map
  26505. var BABYLON;
  26506. (function (BABYLON) {
  26507. var CubeTexture = (function (_super) {
  26508. __extends(CubeTexture, _super);
  26509. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  26510. if (onLoad === void 0) { onLoad = null; }
  26511. if (onError === void 0) { onError = null; }
  26512. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26513. var _this = _super.call(this, scene) || this;
  26514. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  26515. _this.name = rootUrl;
  26516. _this.url = rootUrl;
  26517. _this._noMipmap = noMipmap;
  26518. _this.hasAlpha = false;
  26519. _this._format = format;
  26520. if (!rootUrl && !files) {
  26521. return _this;
  26522. }
  26523. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  26524. if (!files) {
  26525. if (!extensions) {
  26526. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  26527. }
  26528. files = [];
  26529. for (var index = 0; index < extensions.length; index++) {
  26530. files.push(rootUrl + extensions[index]);
  26531. }
  26532. _this._extensions = extensions;
  26533. }
  26534. _this._files = files;
  26535. if (!_this._texture) {
  26536. if (!scene.useDelayedTextureLoading) {
  26537. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  26538. }
  26539. else {
  26540. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26541. }
  26542. }
  26543. else if (onLoad) {
  26544. if (_this._texture.isReady) {
  26545. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  26546. }
  26547. else {
  26548. _this._texture.onLoadedCallbacks.push(onLoad);
  26549. }
  26550. }
  26551. _this.isCube = true;
  26552. _this._textureMatrix = BABYLON.Matrix.Identity();
  26553. return _this;
  26554. }
  26555. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  26556. return new CubeTexture("", scene, null, noMipmap, files);
  26557. };
  26558. // Methods
  26559. CubeTexture.prototype.delayLoad = function () {
  26560. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26561. return;
  26562. }
  26563. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26564. this._texture = this._getFromCache(this.url, this._noMipmap);
  26565. if (!this._texture) {
  26566. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  26567. }
  26568. };
  26569. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  26570. return this._textureMatrix;
  26571. };
  26572. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  26573. var texture = BABYLON.SerializationHelper.Parse(function () {
  26574. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  26575. }, parsedTexture, scene);
  26576. // Animations
  26577. if (parsedTexture.animations) {
  26578. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26579. var parsedAnimation = parsedTexture.animations[animationIndex];
  26580. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26581. }
  26582. }
  26583. return texture;
  26584. };
  26585. CubeTexture.prototype.clone = function () {
  26586. var _this = this;
  26587. return BABYLON.SerializationHelper.Clone(function () {
  26588. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  26589. }, this);
  26590. };
  26591. return CubeTexture;
  26592. }(BABYLON.BaseTexture));
  26593. BABYLON.CubeTexture = CubeTexture;
  26594. })(BABYLON || (BABYLON = {}));
  26595. //# sourceMappingURL=babylon.cubeTexture.js.map
  26596. var BABYLON;
  26597. (function (BABYLON) {
  26598. var RenderTargetTexture = (function (_super) {
  26599. __extends(RenderTargetTexture, _super);
  26600. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  26601. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  26602. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26603. if (isCube === void 0) { isCube = false; }
  26604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26605. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  26606. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  26607. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  26608. _this.isCube = isCube;
  26609. /**
  26610. * Use this list to define the list of mesh you want to render.
  26611. */
  26612. _this.renderList = new Array();
  26613. _this.renderParticles = true;
  26614. _this.renderSprites = false;
  26615. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  26616. // Events
  26617. /**
  26618. * An event triggered when the texture is unbind.
  26619. * @type {BABYLON.Observable}
  26620. */
  26621. _this.onAfterUnbindObservable = new BABYLON.Observable();
  26622. /**
  26623. * An event triggered before rendering the texture
  26624. * @type {BABYLON.Observable}
  26625. */
  26626. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26627. /**
  26628. * An event triggered after rendering the texture
  26629. * @type {BABYLON.Observable}
  26630. */
  26631. _this.onAfterRenderObservable = new BABYLON.Observable();
  26632. /**
  26633. * An event triggered after the texture clear
  26634. * @type {BABYLON.Observable}
  26635. */
  26636. _this.onClearObservable = new BABYLON.Observable();
  26637. _this._currentRefreshId = -1;
  26638. _this._refreshRate = 1;
  26639. _this.name = name;
  26640. _this.isRenderTarget = true;
  26641. _this._size = size;
  26642. _this._generateMipMaps = generateMipMaps;
  26643. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  26644. _this._renderTargetOptions = {
  26645. generateMipMaps: generateMipMaps,
  26646. type: type,
  26647. samplingMode: samplingMode,
  26648. generateDepthBuffer: generateDepthBuffer,
  26649. generateStencilBuffer: generateStencilBuffer
  26650. };
  26651. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26652. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26653. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26654. }
  26655. if (isCube) {
  26656. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  26657. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  26658. _this._textureMatrix = BABYLON.Matrix.Identity();
  26659. }
  26660. else {
  26661. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  26662. }
  26663. // Rendering groups
  26664. _this._renderingManager = new BABYLON.RenderingManager(scene);
  26665. return _this;
  26666. }
  26667. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  26668. get: function () {
  26669. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  26675. get: function () {
  26676. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  26677. },
  26678. enumerable: true,
  26679. configurable: true
  26680. });
  26681. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  26682. get: function () {
  26683. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  26689. set: function (callback) {
  26690. if (this._onAfterUnbindObserver) {
  26691. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  26692. }
  26693. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  26694. },
  26695. enumerable: true,
  26696. configurable: true
  26697. });
  26698. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  26699. set: function (callback) {
  26700. if (this._onBeforeRenderObserver) {
  26701. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26702. }
  26703. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26704. },
  26705. enumerable: true,
  26706. configurable: true
  26707. });
  26708. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  26709. set: function (callback) {
  26710. if (this._onAfterRenderObserver) {
  26711. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26712. }
  26713. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26714. },
  26715. enumerable: true,
  26716. configurable: true
  26717. });
  26718. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  26719. set: function (callback) {
  26720. if (this._onClearObserver) {
  26721. this.onClearObservable.remove(this._onClearObserver);
  26722. }
  26723. this._onClearObserver = this.onClearObservable.add(callback);
  26724. },
  26725. enumerable: true,
  26726. configurable: true
  26727. });
  26728. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  26729. this._currentRefreshId = -1;
  26730. };
  26731. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  26732. get: function () {
  26733. return this._refreshRate;
  26734. },
  26735. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  26736. set: function (value) {
  26737. this._refreshRate = value;
  26738. this.resetRefreshCounter();
  26739. },
  26740. enumerable: true,
  26741. configurable: true
  26742. });
  26743. RenderTargetTexture.prototype._shouldRender = function () {
  26744. if (this._currentRefreshId === -1) {
  26745. this._currentRefreshId = 1;
  26746. return true;
  26747. }
  26748. if (this.refreshRate === this._currentRefreshId) {
  26749. this._currentRefreshId = 1;
  26750. return true;
  26751. }
  26752. this._currentRefreshId++;
  26753. return false;
  26754. };
  26755. RenderTargetTexture.prototype.isReady = function () {
  26756. if (!this.getScene().renderTargetsEnabled) {
  26757. return false;
  26758. }
  26759. return _super.prototype.isReady.call(this);
  26760. };
  26761. RenderTargetTexture.prototype.getRenderSize = function () {
  26762. return this._size;
  26763. };
  26764. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  26765. get: function () {
  26766. return true;
  26767. },
  26768. enumerable: true,
  26769. configurable: true
  26770. });
  26771. RenderTargetTexture.prototype.scale = function (ratio) {
  26772. var newSize = this._size * ratio;
  26773. this.resize(newSize);
  26774. };
  26775. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  26776. if (this.isCube) {
  26777. return this._textureMatrix;
  26778. }
  26779. return _super.prototype.getReflectionTextureMatrix.call(this);
  26780. };
  26781. RenderTargetTexture.prototype.resize = function (size) {
  26782. this.releaseInternalTexture();
  26783. if (this.isCube) {
  26784. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  26785. }
  26786. else {
  26787. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  26788. }
  26789. };
  26790. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  26791. var scene = this.getScene();
  26792. var engine = scene.getEngine();
  26793. if (this.useCameraPostProcesses !== undefined) {
  26794. useCameraPostProcess = this.useCameraPostProcesses;
  26795. }
  26796. if (this._waitingRenderList) {
  26797. this.renderList = [];
  26798. for (var index = 0; index < this._waitingRenderList.length; index++) {
  26799. var id = this._waitingRenderList[index];
  26800. this.renderList.push(scene.getMeshByID(id));
  26801. }
  26802. delete this._waitingRenderList;
  26803. }
  26804. // Is predicate defined?
  26805. if (this.renderListPredicate) {
  26806. this.renderList.splice(0); // Clear previous renderList
  26807. var sceneMeshes = this.getScene().meshes;
  26808. for (var index = 0; index < sceneMeshes.length; index++) {
  26809. var mesh = sceneMeshes[index];
  26810. if (this.renderListPredicate(mesh)) {
  26811. this.renderList.push(mesh);
  26812. }
  26813. }
  26814. }
  26815. if (this.renderList && this.renderList.length === 0) {
  26816. return;
  26817. }
  26818. // Set custom projection.
  26819. // Needs to be before binding to prevent changing the aspect ratio.
  26820. if (this.activeCamera) {
  26821. engine.setViewport(this.activeCamera.viewport);
  26822. if (this.activeCamera !== scene.activeCamera) {
  26823. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  26824. }
  26825. }
  26826. else {
  26827. engine.setViewport(scene.activeCamera.viewport);
  26828. }
  26829. // Prepare renderingManager
  26830. this._renderingManager.reset();
  26831. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  26832. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  26833. var sceneRenderId = scene.getRenderId();
  26834. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  26835. var mesh = currentRenderList[meshIndex];
  26836. if (mesh) {
  26837. if (!mesh.isReady()) {
  26838. // Reset _currentRefreshId
  26839. this.resetRefreshCounter();
  26840. continue;
  26841. }
  26842. mesh._preActivateForIntermediateRendering(sceneRenderId);
  26843. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  26844. mesh._activate(sceneRenderId);
  26845. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26846. var subMesh = mesh.subMeshes[subIndex];
  26847. scene._activeIndices.addCount(subMesh.indexCount, false);
  26848. this._renderingManager.dispatch(subMesh);
  26849. }
  26850. }
  26851. }
  26852. }
  26853. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  26854. var particleSystem = scene.particleSystems[particleIndex];
  26855. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  26856. continue;
  26857. }
  26858. if (this.renderList.indexOf(particleSystem.emitter) >= 0) {
  26859. this._renderingManager.dispatchParticles(particleSystem);
  26860. }
  26861. }
  26862. if (this.isCube) {
  26863. for (var face = 0; face < 6; face++) {
  26864. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26865. scene.incrementRenderId();
  26866. scene.resetCachedMaterial();
  26867. }
  26868. }
  26869. else {
  26870. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26871. }
  26872. this.onAfterUnbindObservable.notifyObservers(this);
  26873. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  26874. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  26875. }
  26876. engine.setViewport(scene.activeCamera.viewport);
  26877. scene.resetCachedMaterial();
  26878. };
  26879. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  26880. var scene = this.getScene();
  26881. var engine = scene.getEngine();
  26882. // Bind
  26883. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  26884. if (this.isCube) {
  26885. engine.bindFramebuffer(this._texture, faceIndex);
  26886. }
  26887. else {
  26888. engine.bindFramebuffer(this._texture);
  26889. }
  26890. }
  26891. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  26892. // Clear
  26893. if (this.onClearObservable.hasObservers()) {
  26894. this.onClearObservable.notifyObservers(engine);
  26895. }
  26896. else {
  26897. engine.clear(scene.clearColor, true, true, true);
  26898. }
  26899. if (!this._doNotChangeAspectRatio) {
  26900. scene.updateTransformMatrix(true);
  26901. }
  26902. // Render
  26903. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  26904. if (useCameraPostProcess) {
  26905. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  26906. }
  26907. if (!this._doNotChangeAspectRatio) {
  26908. scene.updateTransformMatrix(true);
  26909. }
  26910. this.onAfterRenderObservable.notifyObservers(faceIndex);
  26911. // Dump ?
  26912. if (dumpForDebug) {
  26913. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  26914. }
  26915. // Unbind
  26916. if (!this.isCube || faceIndex === 5) {
  26917. if (this.isCube) {
  26918. if (faceIndex === 5) {
  26919. engine.generateMipMapsForCubemap(this._texture);
  26920. }
  26921. }
  26922. engine.unBindFramebuffer(this._texture, this.isCube);
  26923. }
  26924. };
  26925. /**
  26926. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  26927. * This allowed control for front to back rendering or reversly depending of the special needs.
  26928. *
  26929. * @param renderingGroupId The rendering group id corresponding to its index
  26930. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  26931. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  26932. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  26933. */
  26934. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  26935. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  26936. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  26937. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  26938. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  26939. };
  26940. /**
  26941. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  26942. *
  26943. * @param renderingGroupId The rendering group id corresponding to its index
  26944. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  26945. */
  26946. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  26947. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  26948. };
  26949. RenderTargetTexture.prototype.clone = function () {
  26950. var textureSize = this.getSize();
  26951. 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);
  26952. // Base texture
  26953. newTexture.hasAlpha = this.hasAlpha;
  26954. newTexture.level = this.level;
  26955. // RenderTarget Texture
  26956. newTexture.coordinatesMode = this.coordinatesMode;
  26957. newTexture.renderList = this.renderList.slice(0);
  26958. return newTexture;
  26959. };
  26960. RenderTargetTexture.prototype.serialize = function () {
  26961. if (!this.name) {
  26962. return null;
  26963. }
  26964. var serializationObject = _super.prototype.serialize.call(this);
  26965. serializationObject.renderTargetSize = this.getRenderSize();
  26966. serializationObject.renderList = [];
  26967. for (var index = 0; index < this.renderList.length; index++) {
  26968. serializationObject.renderList.push(this.renderList[index].id);
  26969. }
  26970. return serializationObject;
  26971. };
  26972. return RenderTargetTexture;
  26973. }(BABYLON.Texture));
  26974. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  26975. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  26976. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  26977. BABYLON.RenderTargetTexture = RenderTargetTexture;
  26978. })(BABYLON || (BABYLON = {}));
  26979. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  26980. var BABYLON;
  26981. (function (BABYLON) {
  26982. var ProceduralTexture = (function (_super) {
  26983. __extends(ProceduralTexture, _super);
  26984. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  26985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26986. if (isCube === void 0) { isCube = false; }
  26987. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  26988. _this.isCube = isCube;
  26989. _this.isEnabled = true;
  26990. _this._currentRefreshId = -1;
  26991. _this._refreshRate = 1;
  26992. _this._vertexBuffers = {};
  26993. _this._uniforms = new Array();
  26994. _this._samplers = new Array();
  26995. _this._textures = new Array();
  26996. _this._floats = new Array();
  26997. _this._floatsArrays = {};
  26998. _this._colors3 = new Array();
  26999. _this._colors4 = new Array();
  27000. _this._vectors2 = new Array();
  27001. _this._vectors3 = new Array();
  27002. _this._matrices = new Array();
  27003. _this._fallbackTextureUsed = false;
  27004. scene._proceduralTextures.push(_this);
  27005. _this.name = name;
  27006. _this.isRenderTarget = true;
  27007. _this._size = size;
  27008. _this._generateMipMaps = generateMipMaps;
  27009. _this.setFragment(fragment);
  27010. _this._fallbackTexture = fallbackTexture;
  27011. var engine = scene.getEngine();
  27012. if (isCube) {
  27013. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27014. _this.setFloat("face", 0);
  27015. }
  27016. else {
  27017. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27018. }
  27019. // VBO
  27020. var vertices = [];
  27021. vertices.push(1, 1);
  27022. vertices.push(-1, 1);
  27023. vertices.push(-1, -1);
  27024. vertices.push(1, -1);
  27025. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27026. // Indices
  27027. var indices = [];
  27028. indices.push(0);
  27029. indices.push(1);
  27030. indices.push(2);
  27031. indices.push(0);
  27032. indices.push(2);
  27033. indices.push(3);
  27034. _this._indexBuffer = engine.createIndexBuffer(indices);
  27035. return _this;
  27036. }
  27037. ProceduralTexture.prototype.reset = function () {
  27038. if (this._effect === undefined) {
  27039. return;
  27040. }
  27041. var engine = this.getScene().getEngine();
  27042. engine._releaseEffect(this._effect);
  27043. };
  27044. ProceduralTexture.prototype.isReady = function () {
  27045. var _this = this;
  27046. var engine = this.getScene().getEngine();
  27047. var shaders;
  27048. if (!this._fragment) {
  27049. return false;
  27050. }
  27051. if (this._fallbackTextureUsed) {
  27052. return true;
  27053. }
  27054. if (this._fragment.fragmentElement !== undefined) {
  27055. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27056. }
  27057. else {
  27058. shaders = { vertex: "procedural", fragment: this._fragment };
  27059. }
  27060. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27061. _this.releaseInternalTexture();
  27062. if (_this._fallbackTexture) {
  27063. _this._texture = _this._fallbackTexture._texture;
  27064. _this._texture.references++;
  27065. }
  27066. _this._fallbackTextureUsed = true;
  27067. });
  27068. return this._effect.isReady();
  27069. };
  27070. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27071. this._currentRefreshId = -1;
  27072. };
  27073. ProceduralTexture.prototype.setFragment = function (fragment) {
  27074. this._fragment = fragment;
  27075. };
  27076. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27077. get: function () {
  27078. return this._refreshRate;
  27079. },
  27080. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27081. set: function (value) {
  27082. this._refreshRate = value;
  27083. this.resetRefreshCounter();
  27084. },
  27085. enumerable: true,
  27086. configurable: true
  27087. });
  27088. ProceduralTexture.prototype._shouldRender = function () {
  27089. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27090. return false;
  27091. }
  27092. if (this._fallbackTextureUsed) {
  27093. return false;
  27094. }
  27095. if (this._currentRefreshId === -1) {
  27096. this._currentRefreshId = 1;
  27097. return true;
  27098. }
  27099. if (this.refreshRate === this._currentRefreshId) {
  27100. this._currentRefreshId = 1;
  27101. return true;
  27102. }
  27103. this._currentRefreshId++;
  27104. return false;
  27105. };
  27106. ProceduralTexture.prototype.getRenderSize = function () {
  27107. return this._size;
  27108. };
  27109. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27110. if (this._fallbackTextureUsed) {
  27111. return;
  27112. }
  27113. this.releaseInternalTexture();
  27114. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27115. };
  27116. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27117. if (this._uniforms.indexOf(uniformName) === -1) {
  27118. this._uniforms.push(uniformName);
  27119. }
  27120. };
  27121. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27122. if (this._samplers.indexOf(name) === -1) {
  27123. this._samplers.push(name);
  27124. }
  27125. this._textures[name] = texture;
  27126. return this;
  27127. };
  27128. ProceduralTexture.prototype.setFloat = function (name, value) {
  27129. this._checkUniform(name);
  27130. this._floats[name] = value;
  27131. return this;
  27132. };
  27133. ProceduralTexture.prototype.setFloats = function (name, value) {
  27134. this._checkUniform(name);
  27135. this._floatsArrays[name] = value;
  27136. return this;
  27137. };
  27138. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27139. this._checkUniform(name);
  27140. this._colors3[name] = value;
  27141. return this;
  27142. };
  27143. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27144. this._checkUniform(name);
  27145. this._colors4[name] = value;
  27146. return this;
  27147. };
  27148. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27149. this._checkUniform(name);
  27150. this._vectors2[name] = value;
  27151. return this;
  27152. };
  27153. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27154. this._checkUniform(name);
  27155. this._vectors3[name] = value;
  27156. return this;
  27157. };
  27158. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27159. this._checkUniform(name);
  27160. this._matrices[name] = value;
  27161. return this;
  27162. };
  27163. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27164. var scene = this.getScene();
  27165. var engine = scene.getEngine();
  27166. // Render
  27167. engine.enableEffect(this._effect);
  27168. engine.setState(false);
  27169. // Texture
  27170. for (var name in this._textures) {
  27171. this._effect.setTexture(name, this._textures[name]);
  27172. }
  27173. // Float
  27174. for (name in this._floats) {
  27175. this._effect.setFloat(name, this._floats[name]);
  27176. }
  27177. // Floats
  27178. for (name in this._floatsArrays) {
  27179. this._effect.setArray(name, this._floatsArrays[name]);
  27180. }
  27181. // Color3
  27182. for (name in this._colors3) {
  27183. this._effect.setColor3(name, this._colors3[name]);
  27184. }
  27185. // Color4
  27186. for (name in this._colors4) {
  27187. var color = this._colors4[name];
  27188. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27189. }
  27190. // Vector2
  27191. for (name in this._vectors2) {
  27192. this._effect.setVector2(name, this._vectors2[name]);
  27193. }
  27194. // Vector3
  27195. for (name in this._vectors3) {
  27196. this._effect.setVector3(name, this._vectors3[name]);
  27197. }
  27198. // Matrix
  27199. for (name in this._matrices) {
  27200. this._effect.setMatrix(name, this._matrices[name]);
  27201. }
  27202. if (this.isCube) {
  27203. for (var face = 0; face < 6; face++) {
  27204. engine.bindFramebuffer(this._texture, face);
  27205. // VBOs
  27206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27207. this._effect.setFloat("face", face);
  27208. // Clear
  27209. engine.clear(scene.clearColor, true, true, true);
  27210. // Draw order
  27211. engine.draw(true, 0, 6);
  27212. // Mipmaps
  27213. if (face === 5) {
  27214. engine.generateMipMapsForCubemap(this._texture);
  27215. }
  27216. }
  27217. }
  27218. else {
  27219. engine.bindFramebuffer(this._texture);
  27220. // VBOs
  27221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27222. // Clear
  27223. engine.clear(scene.clearColor, true, true, true);
  27224. // Draw order
  27225. engine.draw(true, 0, 6);
  27226. }
  27227. // Unbind
  27228. engine.unBindFramebuffer(this._texture, this.isCube);
  27229. if (this.onGenerated) {
  27230. this.onGenerated();
  27231. }
  27232. };
  27233. ProceduralTexture.prototype.clone = function () {
  27234. var textureSize = this.getSize();
  27235. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27236. // Base texture
  27237. newTexture.hasAlpha = this.hasAlpha;
  27238. newTexture.level = this.level;
  27239. // RenderTarget Texture
  27240. newTexture.coordinatesMode = this.coordinatesMode;
  27241. return newTexture;
  27242. };
  27243. ProceduralTexture.prototype.dispose = function () {
  27244. var index = this.getScene()._proceduralTextures.indexOf(this);
  27245. if (index >= 0) {
  27246. this.getScene()._proceduralTextures.splice(index, 1);
  27247. }
  27248. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27249. if (vertexBuffer) {
  27250. vertexBuffer.dispose();
  27251. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27252. }
  27253. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  27254. this._indexBuffer = null;
  27255. }
  27256. _super.prototype.dispose.call(this);
  27257. };
  27258. return ProceduralTexture;
  27259. }(BABYLON.Texture));
  27260. BABYLON.ProceduralTexture = ProceduralTexture;
  27261. })(BABYLON || (BABYLON = {}));
  27262. //# sourceMappingURL=babylon.proceduralTexture.js.map
  27263. /// <reference path="babylon.renderTargetTexture.ts" />
  27264. var BABYLON;
  27265. (function (BABYLON) {
  27266. var MirrorTexture = (function (_super) {
  27267. __extends(MirrorTexture, _super);
  27268. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  27269. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27271. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27272. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  27273. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  27274. _this._transformMatrix = BABYLON.Matrix.Zero();
  27275. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  27276. _this.onBeforeRenderObservable.add(function () {
  27277. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  27278. _this._savedViewMatrix = scene.getViewMatrix();
  27279. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  27280. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  27281. scene.clipPlane = _this.mirrorPlane;
  27282. scene.getEngine().cullBackFaces = false;
  27283. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  27284. });
  27285. _this.onAfterRenderObservable.add(function () {
  27286. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  27287. scene.getEngine().cullBackFaces = true;
  27288. scene._mirroredCameraPosition = null;
  27289. delete scene.clipPlane;
  27290. });
  27291. return _this;
  27292. }
  27293. MirrorTexture.prototype.clone = function () {
  27294. var textureSize = this.getSize();
  27295. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  27296. // Base texture
  27297. newTexture.hasAlpha = this.hasAlpha;
  27298. newTexture.level = this.level;
  27299. // Mirror Texture
  27300. newTexture.mirrorPlane = this.mirrorPlane.clone();
  27301. newTexture.renderList = this.renderList.slice(0);
  27302. return newTexture;
  27303. };
  27304. MirrorTexture.prototype.serialize = function () {
  27305. if (!this.name) {
  27306. return null;
  27307. }
  27308. var serializationObject = _super.prototype.serialize.call(this);
  27309. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  27310. return serializationObject;
  27311. };
  27312. return MirrorTexture;
  27313. }(BABYLON.RenderTargetTexture));
  27314. BABYLON.MirrorTexture = MirrorTexture;
  27315. })(BABYLON || (BABYLON = {}));
  27316. //# sourceMappingURL=babylon.mirrorTexture.js.map
  27317. /// <reference path="babylon.renderTargetTexture.ts" />
  27318. var BABYLON;
  27319. (function (BABYLON) {
  27320. /**
  27321. * Creates a refraction texture used by refraction channel of the standard material.
  27322. * @param name the texture name
  27323. * @param size size of the underlying texture
  27324. * @param scene root scene
  27325. */
  27326. var RefractionTexture = (function (_super) {
  27327. __extends(RefractionTexture, _super);
  27328. function RefractionTexture(name, size, scene, generateMipMaps) {
  27329. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  27330. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  27331. _this.depth = 2.0;
  27332. _this.onBeforeRenderObservable.add(function () {
  27333. scene.clipPlane = _this.refractionPlane;
  27334. });
  27335. _this.onAfterRenderObservable.add(function () {
  27336. delete scene.clipPlane;
  27337. });
  27338. return _this;
  27339. }
  27340. RefractionTexture.prototype.clone = function () {
  27341. var textureSize = this.getSize();
  27342. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  27343. // Base texture
  27344. newTexture.hasAlpha = this.hasAlpha;
  27345. newTexture.level = this.level;
  27346. // Refraction Texture
  27347. newTexture.refractionPlane = this.refractionPlane.clone();
  27348. newTexture.renderList = this.renderList.slice(0);
  27349. newTexture.depth = this.depth;
  27350. return newTexture;
  27351. };
  27352. RefractionTexture.prototype.serialize = function () {
  27353. if (!this.name) {
  27354. return null;
  27355. }
  27356. var serializationObject = _super.prototype.serialize.call(this);
  27357. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  27358. serializationObject.depth = this.depth;
  27359. return serializationObject;
  27360. };
  27361. return RefractionTexture;
  27362. }(BABYLON.RenderTargetTexture));
  27363. BABYLON.RefractionTexture = RefractionTexture;
  27364. })(BABYLON || (BABYLON = {}));
  27365. //# sourceMappingURL=babylon.refractionTexture.js.map
  27366. /// <reference path="babylon.texture.ts" />
  27367. var BABYLON;
  27368. (function (BABYLON) {
  27369. var DynamicTexture = (function (_super) {
  27370. __extends(DynamicTexture, _super);
  27371. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  27372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27373. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27374. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  27375. _this.name = name;
  27376. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27377. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27378. _this._generateMipMaps = generateMipMaps;
  27379. if (options.getContext) {
  27380. _this._canvas = options;
  27381. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27382. }
  27383. else {
  27384. _this._canvas = document.createElement("canvas");
  27385. if (options.width) {
  27386. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27387. }
  27388. else {
  27389. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  27390. }
  27391. }
  27392. var textureSize = _this.getSize();
  27393. _this._canvas.width = textureSize.width;
  27394. _this._canvas.height = textureSize.height;
  27395. _this._context = _this._canvas.getContext("2d");
  27396. return _this;
  27397. }
  27398. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  27399. get: function () {
  27400. return true;
  27401. },
  27402. enumerable: true,
  27403. configurable: true
  27404. });
  27405. DynamicTexture.prototype.scale = function (ratio) {
  27406. var textureSize = this.getSize();
  27407. textureSize.width *= ratio;
  27408. textureSize.height *= ratio;
  27409. this._canvas.width = textureSize.width;
  27410. this._canvas.height = textureSize.height;
  27411. this.releaseInternalTexture();
  27412. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  27413. };
  27414. DynamicTexture.prototype.getContext = function () {
  27415. return this._context;
  27416. };
  27417. DynamicTexture.prototype.clear = function () {
  27418. var size = this.getSize();
  27419. this._context.fillRect(0, 0, size.width, size.height);
  27420. };
  27421. DynamicTexture.prototype.update = function (invertY) {
  27422. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  27423. };
  27424. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  27425. if (update === void 0) { update = true; }
  27426. var size = this.getSize();
  27427. if (clearColor) {
  27428. this._context.fillStyle = clearColor;
  27429. this._context.fillRect(0, 0, size.width, size.height);
  27430. }
  27431. this._context.font = font;
  27432. if (x === null) {
  27433. var textSize = this._context.measureText(text);
  27434. x = (size.width - textSize.width) / 2;
  27435. }
  27436. this._context.fillStyle = color;
  27437. this._context.fillText(text, x, y);
  27438. if (update) {
  27439. this.update(invertY);
  27440. }
  27441. };
  27442. DynamicTexture.prototype.clone = function () {
  27443. var textureSize = this.getSize();
  27444. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  27445. // Base texture
  27446. newTexture.hasAlpha = this.hasAlpha;
  27447. newTexture.level = this.level;
  27448. // Dynamic Texture
  27449. newTexture.wrapU = this.wrapU;
  27450. newTexture.wrapV = this.wrapV;
  27451. return newTexture;
  27452. };
  27453. return DynamicTexture;
  27454. }(BABYLON.Texture));
  27455. BABYLON.DynamicTexture = DynamicTexture;
  27456. })(BABYLON || (BABYLON = {}));
  27457. //# sourceMappingURL=babylon.dynamicTexture.js.map
  27458. var BABYLON;
  27459. (function (BABYLON) {
  27460. var VideoTexture = (function (_super) {
  27461. __extends(VideoTexture, _super);
  27462. /**
  27463. * Creates a video texture.
  27464. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  27465. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  27466. * @param {BABYLON.Scene} scene is obviously the current scene.
  27467. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  27468. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  27469. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  27470. */
  27471. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  27472. if (generateMipMaps === void 0) { generateMipMaps = false; }
  27473. if (invertY === void 0) { invertY = false; }
  27474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27475. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  27476. _this._autoLaunch = true;
  27477. var urls;
  27478. _this.name = name;
  27479. if (urlsOrVideo instanceof HTMLVideoElement) {
  27480. _this.video = urlsOrVideo;
  27481. }
  27482. else {
  27483. urls = urlsOrVideo;
  27484. _this.video = document.createElement("video");
  27485. _this.video.autoplay = false;
  27486. _this.video.loop = true;
  27487. }
  27488. _this._generateMipMaps = generateMipMaps;
  27489. _this._samplingMode = samplingMode;
  27490. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  27491. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27492. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27493. }
  27494. else {
  27495. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27496. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27497. _this._generateMipMaps = false;
  27498. }
  27499. if (urls) {
  27500. _this.video.addEventListener("canplaythrough", function () {
  27501. _this._createTexture();
  27502. });
  27503. urls.forEach(function (url) {
  27504. var source = document.createElement("source");
  27505. source.src = url;
  27506. _this.video.appendChild(source);
  27507. });
  27508. }
  27509. else {
  27510. _this._createTexture();
  27511. }
  27512. _this._lastUpdate = BABYLON.Tools.Now;
  27513. return _this;
  27514. }
  27515. VideoTexture.prototype._createTexture = function () {
  27516. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  27517. this._texture.isReady = true;
  27518. };
  27519. VideoTexture.prototype.update = function () {
  27520. if (this._autoLaunch) {
  27521. this._autoLaunch = false;
  27522. this.video.play();
  27523. }
  27524. var now = BABYLON.Tools.Now;
  27525. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  27526. return false;
  27527. }
  27528. this._lastUpdate = now;
  27529. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  27530. return true;
  27531. };
  27532. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  27533. var video = document.createElement("video");
  27534. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  27535. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  27536. if (navigator.getUserMedia) {
  27537. navigator.getUserMedia({
  27538. video: {
  27539. width: {
  27540. min: (constraints && constraints.minWidth) || 256,
  27541. max: (constraints && constraints.maxWidth) || 640
  27542. },
  27543. height: {
  27544. min: (constraints && constraints.minHeight) || 256,
  27545. max: (constraints && constraints.maxHeight) || 480
  27546. }
  27547. }
  27548. }, function (stream) {
  27549. if (video.mozSrcObject !== undefined) {
  27550. video.mozSrcObject = stream;
  27551. }
  27552. else {
  27553. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  27554. }
  27555. video.play();
  27556. if (onReady) {
  27557. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  27558. }
  27559. }, function (e) {
  27560. BABYLON.Tools.Error(e.name);
  27561. });
  27562. }
  27563. };
  27564. return VideoTexture;
  27565. }(BABYLON.Texture));
  27566. BABYLON.VideoTexture = VideoTexture;
  27567. })(BABYLON || (BABYLON = {}));
  27568. //# sourceMappingURL=babylon.videoTexture.js.map
  27569. /// <reference path="babylon.proceduralTexture.ts" />
  27570. var BABYLON;
  27571. (function (BABYLON) {
  27572. var CustomProceduralTexture = (function (_super) {
  27573. __extends(CustomProceduralTexture, _super);
  27574. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  27575. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  27576. _this._animate = true;
  27577. _this._time = 0;
  27578. _this._texturePath = texturePath;
  27579. //Try to load json
  27580. _this.loadJson(texturePath);
  27581. _this.refreshRate = 1;
  27582. return _this;
  27583. }
  27584. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  27585. var _this = this;
  27586. var that = this;
  27587. function noConfigFile() {
  27588. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  27589. try {
  27590. that.setFragment(that._texturePath);
  27591. }
  27592. catch (ex) {
  27593. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  27594. }
  27595. }
  27596. var configFileUrl = jsonUrl + "/config.json";
  27597. var xhr = new XMLHttpRequest();
  27598. xhr.open("GET", configFileUrl, true);
  27599. xhr.addEventListener("load", function () {
  27600. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  27601. try {
  27602. _this._config = JSON.parse(xhr.response);
  27603. _this.updateShaderUniforms();
  27604. _this.updateTextures();
  27605. _this.setFragment(_this._texturePath + "/custom");
  27606. _this._animate = _this._config.animate;
  27607. _this.refreshRate = _this._config.refreshrate;
  27608. }
  27609. catch (ex) {
  27610. noConfigFile();
  27611. }
  27612. }
  27613. else {
  27614. noConfigFile();
  27615. }
  27616. }, false);
  27617. xhr.addEventListener("error", function () {
  27618. noConfigFile();
  27619. }, false);
  27620. try {
  27621. xhr.send();
  27622. }
  27623. catch (ex) {
  27624. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  27625. }
  27626. };
  27627. CustomProceduralTexture.prototype.isReady = function () {
  27628. if (!_super.prototype.isReady.call(this)) {
  27629. return false;
  27630. }
  27631. for (var name in this._textures) {
  27632. var texture = this._textures[name];
  27633. if (!texture.isReady()) {
  27634. return false;
  27635. }
  27636. }
  27637. return true;
  27638. };
  27639. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27640. if (this._animate) {
  27641. this._time += this.getScene().getAnimationRatio() * 0.03;
  27642. this.updateShaderUniforms();
  27643. }
  27644. _super.prototype.render.call(this, useCameraPostProcess);
  27645. };
  27646. CustomProceduralTexture.prototype.updateTextures = function () {
  27647. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  27648. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  27649. }
  27650. };
  27651. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  27652. if (this._config) {
  27653. for (var j = 0; j < this._config.uniforms.length; j++) {
  27654. var uniform = this._config.uniforms[j];
  27655. switch (uniform.type) {
  27656. case "float":
  27657. this.setFloat(uniform.name, uniform.value);
  27658. break;
  27659. case "color3":
  27660. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  27661. break;
  27662. case "color4":
  27663. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  27664. break;
  27665. case "vector2":
  27666. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  27667. break;
  27668. case "vector3":
  27669. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  27670. break;
  27671. }
  27672. }
  27673. }
  27674. this.setFloat("time", this._time);
  27675. };
  27676. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  27677. get: function () {
  27678. return this._animate;
  27679. },
  27680. set: function (value) {
  27681. this._animate = value;
  27682. },
  27683. enumerable: true,
  27684. configurable: true
  27685. });
  27686. return CustomProceduralTexture;
  27687. }(BABYLON.ProceduralTexture));
  27688. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  27689. })(BABYLON || (BABYLON = {}));
  27690. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  27691. var BABYLON;
  27692. (function (BABYLON) {
  27693. var EffectFallbacks = (function () {
  27694. function EffectFallbacks() {
  27695. this._defines = {};
  27696. this._currentRank = 32;
  27697. this._maxRank = -1;
  27698. }
  27699. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27700. if (!this._defines[rank]) {
  27701. if (rank < this._currentRank) {
  27702. this._currentRank = rank;
  27703. }
  27704. if (rank > this._maxRank) {
  27705. this._maxRank = rank;
  27706. }
  27707. this._defines[rank] = new Array();
  27708. }
  27709. this._defines[rank].push(define);
  27710. };
  27711. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27712. this._meshRank = rank;
  27713. this._mesh = mesh;
  27714. if (rank > this._maxRank) {
  27715. this._maxRank = rank;
  27716. }
  27717. };
  27718. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  27719. get: function () {
  27720. return this._currentRank <= this._maxRank;
  27721. },
  27722. enumerable: true,
  27723. configurable: true
  27724. });
  27725. EffectFallbacks.prototype.reduce = function (currentDefines) {
  27726. var currentFallbacks = this._defines[this._currentRank];
  27727. for (var index = 0; index < currentFallbacks.length; index++) {
  27728. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  27729. }
  27730. if (this._mesh && this._currentRank === this._meshRank) {
  27731. this._mesh.computeBonesUsingShaders = false;
  27732. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  27733. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  27734. }
  27735. this._currentRank++;
  27736. return currentDefines;
  27737. };
  27738. return EffectFallbacks;
  27739. }());
  27740. BABYLON.EffectFallbacks = EffectFallbacks;
  27741. var Effect = (function () {
  27742. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  27743. var _this = this;
  27744. this.uniqueId = 0;
  27745. this._isReady = false;
  27746. this._compilationError = "";
  27747. this._valueCache = {};
  27748. this._engine = engine;
  27749. this.name = baseName;
  27750. this.defines = defines;
  27751. this._uniformsNames = uniformsNames.concat(samplers);
  27752. this._samplers = samplers;
  27753. this._attributesNames = attributesNames;
  27754. this.onError = onError;
  27755. this.onCompiled = onCompiled;
  27756. this._indexParameters = indexParameters;
  27757. this.uniqueId = Effect._uniqueIdSeed++;
  27758. var vertexSource;
  27759. var fragmentSource;
  27760. if (baseName.vertexElement) {
  27761. vertexSource = document.getElementById(baseName.vertexElement);
  27762. if (!vertexSource) {
  27763. vertexSource = baseName.vertexElement;
  27764. }
  27765. }
  27766. else {
  27767. vertexSource = baseName.vertex || baseName;
  27768. }
  27769. if (baseName.fragmentElement) {
  27770. fragmentSource = document.getElementById(baseName.fragmentElement);
  27771. if (!fragmentSource) {
  27772. fragmentSource = baseName.fragmentElement;
  27773. }
  27774. }
  27775. else {
  27776. fragmentSource = baseName.fragment || baseName;
  27777. }
  27778. this._loadVertexShader(vertexSource, function (vertexCode) {
  27779. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  27780. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  27781. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  27782. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  27783. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  27784. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  27785. });
  27786. });
  27787. });
  27788. });
  27789. });
  27790. });
  27791. }
  27792. Object.defineProperty(Effect.prototype, "key", {
  27793. get: function () {
  27794. return this._key;
  27795. },
  27796. enumerable: true,
  27797. configurable: true
  27798. });
  27799. // Properties
  27800. Effect.prototype.isReady = function () {
  27801. return this._isReady;
  27802. };
  27803. Effect.prototype.getProgram = function () {
  27804. return this._program;
  27805. };
  27806. Effect.prototype.getAttributesNames = function () {
  27807. return this._attributesNames;
  27808. };
  27809. Effect.prototype.getAttributeLocation = function (index) {
  27810. return this._attributes[index];
  27811. };
  27812. Effect.prototype.getAttributeLocationByName = function (name) {
  27813. var index = this._attributesNames.indexOf(name);
  27814. return this._attributes[index];
  27815. };
  27816. Effect.prototype.getAttributesCount = function () {
  27817. return this._attributes.length;
  27818. };
  27819. Effect.prototype.getUniformIndex = function (uniformName) {
  27820. return this._uniformsNames.indexOf(uniformName);
  27821. };
  27822. Effect.prototype.getUniform = function (uniformName) {
  27823. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  27824. };
  27825. Effect.prototype.getSamplers = function () {
  27826. return this._samplers;
  27827. };
  27828. Effect.prototype.getCompilationError = function () {
  27829. return this._compilationError;
  27830. };
  27831. Effect.prototype.getVertexShaderSource = function () {
  27832. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  27833. };
  27834. Effect.prototype.getFragmentShaderSource = function () {
  27835. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  27836. };
  27837. // Methods
  27838. Effect.prototype._loadVertexShader = function (vertex, callback) {
  27839. // DOM element ?
  27840. if (vertex instanceof HTMLElement) {
  27841. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  27842. callback(vertexCode);
  27843. return;
  27844. }
  27845. // Base64 encoded ?
  27846. if (vertex.substr(0, 7) === "base64:") {
  27847. var vertexBinary = window.atob(vertex.substr(7));
  27848. callback(vertexBinary);
  27849. return;
  27850. }
  27851. // Is in local store ?
  27852. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  27853. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  27854. return;
  27855. }
  27856. var vertexShaderUrl;
  27857. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  27858. vertexShaderUrl = vertex;
  27859. }
  27860. else {
  27861. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  27862. }
  27863. // Vertex shader
  27864. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  27865. };
  27866. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  27867. // DOM element ?
  27868. if (fragment instanceof HTMLElement) {
  27869. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  27870. callback(fragmentCode);
  27871. return;
  27872. }
  27873. // Base64 encoded ?
  27874. if (fragment.substr(0, 7) === "base64:") {
  27875. var fragmentBinary = window.atob(fragment.substr(7));
  27876. callback(fragmentBinary);
  27877. return;
  27878. }
  27879. // Is in local store ?
  27880. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  27881. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  27882. return;
  27883. }
  27884. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  27885. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  27886. return;
  27887. }
  27888. var fragmentShaderUrl;
  27889. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  27890. fragmentShaderUrl = fragment;
  27891. }
  27892. else {
  27893. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  27894. }
  27895. // Fragment shader
  27896. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  27897. };
  27898. Effect.prototype._dumpShadersName = function () {
  27899. if (this.name.vertexElement) {
  27900. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  27901. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  27902. }
  27903. else if (this.name.vertex) {
  27904. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  27905. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  27906. }
  27907. else {
  27908. BABYLON.Tools.Error("Vertex shader:" + this.name);
  27909. BABYLON.Tools.Error("Fragment shader:" + this.name);
  27910. }
  27911. };
  27912. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  27913. var preparedSourceCode = this._processPrecision(sourceCode);
  27914. if (this._engine.webGLVersion == 1) {
  27915. callback(preparedSourceCode);
  27916. return;
  27917. }
  27918. // Already converted
  27919. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  27920. callback(preparedSourceCode);
  27921. return;
  27922. }
  27923. // Remove extensions
  27924. // #extension GL_OES_standard_derivatives : enable
  27925. // #extension GL_EXT_shader_texture_lod : enable
  27926. // #extension GL_EXT_frag_depth : enable
  27927. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  27928. var result = preparedSourceCode.replace(regex, "");
  27929. // Migrate to GLSL v300
  27930. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  27931. result = result.replace(/attribute[ \t]/g, "in ");
  27932. result = result.replace(/[ \t]attribute/g, " in");
  27933. if (isFragment) {
  27934. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  27935. result = result.replace(/texture2D\(/g, "texture(");
  27936. result = result.replace(/textureCube\(/g, "texture(");
  27937. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  27938. result = result.replace(/gl_FragColor/g, "glFragColor");
  27939. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  27940. }
  27941. callback(result);
  27942. };
  27943. Effect.prototype._processIncludes = function (sourceCode, callback) {
  27944. var _this = this;
  27945. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  27946. var match = regex.exec(sourceCode);
  27947. var returnValue = new String(sourceCode);
  27948. while (match != null) {
  27949. var includeFile = match[1];
  27950. if (Effect.IncludesShadersStore[includeFile]) {
  27951. // Substitution
  27952. var includeContent = Effect.IncludesShadersStore[includeFile];
  27953. if (match[2]) {
  27954. var splits = match[3].split(",");
  27955. for (var index = 0; index < splits.length; index += 2) {
  27956. var source = new RegExp(splits[index], "g");
  27957. var dest = splits[index + 1];
  27958. includeContent = includeContent.replace(source, dest);
  27959. }
  27960. }
  27961. if (match[4]) {
  27962. var indexString = match[5];
  27963. if (indexString.indexOf("..") !== -1) {
  27964. var indexSplits = indexString.split("..");
  27965. var minIndex = parseInt(indexSplits[0]);
  27966. var maxIndex = parseInt(indexSplits[1]);
  27967. var sourceIncludeContent = includeContent.slice(0);
  27968. includeContent = "";
  27969. if (isNaN(maxIndex)) {
  27970. maxIndex = this._indexParameters[indexSplits[1]];
  27971. }
  27972. for (var i = minIndex; i <= maxIndex; i++) {
  27973. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  27974. }
  27975. }
  27976. else {
  27977. includeContent = includeContent.replace(/\{X\}/g, indexString);
  27978. }
  27979. }
  27980. // Replace
  27981. returnValue = returnValue.replace(match[0], includeContent);
  27982. }
  27983. else {
  27984. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  27985. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  27986. Effect.IncludesShadersStore[includeFile] = fileContent;
  27987. _this._processIncludes(returnValue, callback);
  27988. });
  27989. return;
  27990. }
  27991. match = regex.exec(sourceCode);
  27992. }
  27993. callback(returnValue);
  27994. };
  27995. Effect.prototype._processPrecision = function (source) {
  27996. if (source.indexOf("precision highp float") === -1) {
  27997. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  27998. source = "precision mediump float;\n" + source;
  27999. }
  28000. else {
  28001. source = "precision highp float;\n" + source;
  28002. }
  28003. }
  28004. else {
  28005. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28006. source = source.replace("precision highp float", "precision mediump float");
  28007. }
  28008. }
  28009. return source;
  28010. };
  28011. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28012. try {
  28013. var engine = this._engine;
  28014. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28015. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28016. this._attributes = engine.getAttributes(this._program, attributesNames);
  28017. var index;
  28018. for (index = 0; index < this._samplers.length; index++) {
  28019. var sampler = this.getUniform(this._samplers[index]);
  28020. if (sampler == null) {
  28021. this._samplers.splice(index, 1);
  28022. index--;
  28023. }
  28024. }
  28025. engine.bindSamplers(this);
  28026. this._compilationError = "";
  28027. this._isReady = true;
  28028. if (this.onCompiled) {
  28029. this.onCompiled(this);
  28030. }
  28031. }
  28032. catch (e) {
  28033. this._compilationError = e.message;
  28034. // Let's go through fallbacks then
  28035. BABYLON.Tools.Error("Unable to compile effect: ");
  28036. BABYLON.Tools.Error("Defines: " + defines);
  28037. BABYLON.Tools.Error("Error: " + this._compilationError);
  28038. this._dumpShadersName();
  28039. if (fallbacks && fallbacks.isMoreFallbacks) {
  28040. BABYLON.Tools.Error("Trying next fallback.");
  28041. defines = fallbacks.reduce(defines);
  28042. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28043. }
  28044. else {
  28045. if (this.onError) {
  28046. this.onError(this, this._compilationError);
  28047. }
  28048. }
  28049. }
  28050. };
  28051. Object.defineProperty(Effect.prototype, "isSupported", {
  28052. get: function () {
  28053. return this._compilationError === "";
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Effect.prototype._bindTexture = function (channel, texture) {
  28059. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28060. };
  28061. Effect.prototype.setTexture = function (channel, texture) {
  28062. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28063. };
  28064. Effect.prototype.setTextureArray = function (channel, textures) {
  28065. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28066. var initialPos = this._samplers.indexOf(channel);
  28067. for (var index = 1; index < textures.length; index++) {
  28068. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28069. }
  28070. }
  28071. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28072. };
  28073. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28074. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28075. };
  28076. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28077. var changed = false;
  28078. var cache = this._valueCache[uniformName];
  28079. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28080. changed = true;
  28081. cache = new BABYLON.Matrix();
  28082. }
  28083. var tm = cache.m;
  28084. var om = matrix.m;
  28085. for (var index = 0; index < 16; index++) {
  28086. if (tm[index] !== om[index]) {
  28087. tm[index] = om[index];
  28088. changed = true;
  28089. }
  28090. }
  28091. this._valueCache[uniformName] = cache;
  28092. return changed;
  28093. };
  28094. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28095. var cache = this._valueCache[uniformName];
  28096. if (!cache) {
  28097. cache = [x, y];
  28098. this._valueCache[uniformName] = cache;
  28099. return true;
  28100. }
  28101. var changed = false;
  28102. if (cache[0] !== x) {
  28103. cache[0] = x;
  28104. changed = true;
  28105. }
  28106. if (cache[1] !== y) {
  28107. cache[1] = y;
  28108. changed = true;
  28109. }
  28110. return changed;
  28111. };
  28112. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28113. var cache = this._valueCache[uniformName];
  28114. if (!cache) {
  28115. cache = [x, y, z];
  28116. this._valueCache[uniformName] = cache;
  28117. return true;
  28118. }
  28119. var changed = false;
  28120. if (cache[0] !== x) {
  28121. cache[0] = x;
  28122. changed = true;
  28123. }
  28124. if (cache[1] !== y) {
  28125. cache[1] = y;
  28126. changed = true;
  28127. }
  28128. if (cache[2] !== z) {
  28129. cache[2] = z;
  28130. changed = true;
  28131. }
  28132. return changed;
  28133. };
  28134. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28135. var cache = this._valueCache[uniformName];
  28136. if (!cache) {
  28137. cache = [x, y, z, w];
  28138. this._valueCache[uniformName] = cache;
  28139. return true;
  28140. }
  28141. var changed = false;
  28142. if (cache[0] !== x) {
  28143. cache[0] = x;
  28144. changed = true;
  28145. }
  28146. if (cache[1] !== y) {
  28147. cache[1] = y;
  28148. changed = true;
  28149. }
  28150. if (cache[2] !== z) {
  28151. cache[2] = z;
  28152. changed = true;
  28153. }
  28154. if (cache[3] !== w) {
  28155. cache[3] = w;
  28156. changed = true;
  28157. }
  28158. return changed;
  28159. };
  28160. Effect.prototype.setIntArray = function (uniformName, array) {
  28161. this._valueCache[uniformName] = null;
  28162. this._engine.setIntArray(this.getUniform(uniformName), array);
  28163. return this;
  28164. };
  28165. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28166. this._valueCache[uniformName] = null;
  28167. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28168. return this;
  28169. };
  28170. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28171. this._valueCache[uniformName] = null;
  28172. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28173. return this;
  28174. };
  28175. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28176. this._valueCache[uniformName] = null;
  28177. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28178. return this;
  28179. };
  28180. Effect.prototype.setFloatArray = function (uniformName, array) {
  28181. this._valueCache[uniformName] = null;
  28182. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28183. return this;
  28184. };
  28185. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28186. this._valueCache[uniformName] = null;
  28187. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28188. return this;
  28189. };
  28190. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28191. this._valueCache[uniformName] = null;
  28192. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28193. return this;
  28194. };
  28195. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28196. this._valueCache[uniformName] = null;
  28197. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28198. return this;
  28199. };
  28200. Effect.prototype.setArray = function (uniformName, array) {
  28201. this._valueCache[uniformName] = null;
  28202. this._engine.setArray(this.getUniform(uniformName), array);
  28203. return this;
  28204. };
  28205. Effect.prototype.setArray2 = function (uniformName, array) {
  28206. this._valueCache[uniformName] = null;
  28207. this._engine.setArray2(this.getUniform(uniformName), array);
  28208. return this;
  28209. };
  28210. Effect.prototype.setArray3 = function (uniformName, array) {
  28211. this._valueCache[uniformName] = null;
  28212. this._engine.setArray3(this.getUniform(uniformName), array);
  28213. return this;
  28214. };
  28215. Effect.prototype.setArray4 = function (uniformName, array) {
  28216. this._valueCache[uniformName] = null;
  28217. this._engine.setArray4(this.getUniform(uniformName), array);
  28218. return this;
  28219. };
  28220. Effect.prototype.setMatrices = function (uniformName, matrices) {
  28221. this._valueCache[uniformName] = null;
  28222. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  28223. return this;
  28224. };
  28225. Effect.prototype.setMatrix = function (uniformName, matrix) {
  28226. if (this._cacheMatrix(uniformName, matrix)) {
  28227. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  28228. }
  28229. return this;
  28230. };
  28231. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  28232. this._valueCache[uniformName] = null;
  28233. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  28234. return this;
  28235. };
  28236. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  28237. this._valueCache[uniformName] = null;
  28238. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  28239. return this;
  28240. };
  28241. Effect.prototype.setFloat = function (uniformName, value) {
  28242. var cache = this._valueCache[uniformName];
  28243. if (cache !== undefined && cache === value)
  28244. return this;
  28245. this._valueCache[uniformName] = value;
  28246. this._engine.setFloat(this.getUniform(uniformName), value);
  28247. return this;
  28248. };
  28249. Effect.prototype.setBool = function (uniformName, bool) {
  28250. var cache = this._valueCache[uniformName];
  28251. if (cache !== undefined && cache === bool)
  28252. return this;
  28253. this._valueCache[uniformName] = bool;
  28254. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  28255. return this;
  28256. };
  28257. Effect.prototype.setVector2 = function (uniformName, vector2) {
  28258. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  28259. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  28260. }
  28261. return this;
  28262. };
  28263. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  28264. if (this._cacheFloat2(uniformName, x, y)) {
  28265. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  28266. }
  28267. return this;
  28268. };
  28269. Effect.prototype.setVector3 = function (uniformName, vector3) {
  28270. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  28271. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  28272. }
  28273. return this;
  28274. };
  28275. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  28276. if (this._cacheFloat3(uniformName, x, y, z)) {
  28277. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  28278. }
  28279. return this;
  28280. };
  28281. Effect.prototype.setVector4 = function (uniformName, vector4) {
  28282. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  28283. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  28284. }
  28285. return this;
  28286. };
  28287. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  28288. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  28289. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  28290. }
  28291. return this;
  28292. };
  28293. Effect.prototype.setColor3 = function (uniformName, color3) {
  28294. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  28295. this._engine.setColor3(this.getUniform(uniformName), color3);
  28296. }
  28297. return this;
  28298. };
  28299. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  28300. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  28301. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  28302. }
  28303. return this;
  28304. };
  28305. Effect.prototype._recombineShader = function (node) {
  28306. if (node.define) {
  28307. if (node.condition) {
  28308. var defineIndex = this.defines.indexOf("#define " + node.define);
  28309. if (defineIndex === -1) {
  28310. return null;
  28311. }
  28312. var nextComma = this.defines.indexOf("\n", defineIndex);
  28313. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  28314. var condition = defineValue + node.condition;
  28315. if (!eval(condition)) {
  28316. return null;
  28317. }
  28318. }
  28319. else if (node.ndef) {
  28320. if (this.defines.indexOf("#define " + node.define) !== -1) {
  28321. return null;
  28322. }
  28323. }
  28324. else if (this.defines.indexOf("#define " + node.define) === -1) {
  28325. return null;
  28326. }
  28327. }
  28328. var result = "";
  28329. for (var index = 0; index < node.children.length; index++) {
  28330. var line = node.children[index];
  28331. if (line.children) {
  28332. var combined = this._recombineShader(line);
  28333. if (combined !== null) {
  28334. result += combined + "\r\n";
  28335. }
  28336. continue;
  28337. }
  28338. if (line.length > 0) {
  28339. result += line + "\r\n";
  28340. }
  28341. }
  28342. return result;
  28343. };
  28344. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  28345. var root = {
  28346. children: []
  28347. };
  28348. var currentNode = root;
  28349. var lines = shaderString.split("\n");
  28350. for (var index = 0; index < lines.length; index++) {
  28351. var line = lines[index].trim();
  28352. // #ifdef
  28353. var pos = line.indexOf("#ifdef ");
  28354. if (pos !== -1) {
  28355. var define = line.substr(pos + 7);
  28356. var newNode = {
  28357. condition: null,
  28358. ndef: false,
  28359. define: define,
  28360. children: [],
  28361. parent: currentNode
  28362. };
  28363. currentNode.children.push(newNode);
  28364. currentNode = newNode;
  28365. continue;
  28366. }
  28367. // #ifndef
  28368. var pos = line.indexOf("#ifndef ");
  28369. if (pos !== -1) {
  28370. var define = line.substr(pos + 8);
  28371. newNode = {
  28372. condition: null,
  28373. define: define,
  28374. ndef: true,
  28375. children: [],
  28376. parent: currentNode
  28377. };
  28378. currentNode.children.push(newNode);
  28379. currentNode = newNode;
  28380. continue;
  28381. }
  28382. // #if
  28383. var pos = line.indexOf("#if ");
  28384. if (pos !== -1) {
  28385. var define = line.substr(pos + 4).trim();
  28386. var conditionPos = define.indexOf(" ");
  28387. newNode = {
  28388. condition: define.substr(conditionPos + 1),
  28389. define: define.substr(0, conditionPos),
  28390. ndef: false,
  28391. children: [],
  28392. parent: currentNode
  28393. };
  28394. currentNode.children.push(newNode);
  28395. currentNode = newNode;
  28396. continue;
  28397. }
  28398. // #endif
  28399. pos = line.indexOf("#endif");
  28400. if (pos !== -1) {
  28401. currentNode = currentNode.parent;
  28402. continue;
  28403. }
  28404. currentNode.children.push(line);
  28405. }
  28406. // Recombine
  28407. return this._recombineShader(root);
  28408. };
  28409. return Effect;
  28410. }());
  28411. Effect._uniqueIdSeed = 0;
  28412. // Statics
  28413. Effect.ShadersStore = {};
  28414. Effect.IncludesShadersStore = {};
  28415. BABYLON.Effect = Effect;
  28416. })(BABYLON || (BABYLON = {}));
  28417. //# sourceMappingURL=babylon.effect.js.map
  28418. var BABYLON;
  28419. (function (BABYLON) {
  28420. var MaterialHelper = (function () {
  28421. function MaterialHelper() {
  28422. }
  28423. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  28424. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28425. var lightIndex = 0;
  28426. var needNormals = false;
  28427. var needRebuild = false;
  28428. var needShadows = false;
  28429. var lightmapMode = false;
  28430. for (var index = 0; index < scene.lights.length; index++) {
  28431. var light = scene.lights[index];
  28432. if (!light.isEnabled()) {
  28433. continue;
  28434. }
  28435. // Excluded check
  28436. if (light._excludedMeshesIds.length > 0) {
  28437. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  28438. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  28439. if (excludedMesh) {
  28440. light.excludedMeshes.push(excludedMesh);
  28441. }
  28442. }
  28443. light._excludedMeshesIds = [];
  28444. }
  28445. // Included check
  28446. if (light._includedOnlyMeshesIds.length > 0) {
  28447. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  28448. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  28449. if (includedOnlyMesh) {
  28450. light.includedOnlyMeshes.push(includedOnlyMesh);
  28451. }
  28452. }
  28453. light._includedOnlyMeshesIds = [];
  28454. }
  28455. if (!light.canAffectMesh(mesh)) {
  28456. continue;
  28457. }
  28458. needNormals = true;
  28459. if (defines["LIGHT" + lightIndex] === undefined) {
  28460. needRebuild = true;
  28461. }
  28462. defines["LIGHT" + lightIndex] = true;
  28463. var type;
  28464. if (light instanceof BABYLON.SpotLight) {
  28465. type = "SPOTLIGHT" + lightIndex;
  28466. }
  28467. else if (light instanceof BABYLON.HemisphericLight) {
  28468. type = "HEMILIGHT" + lightIndex;
  28469. }
  28470. else if (light instanceof BABYLON.PointLight) {
  28471. type = "POINTLIGHT" + lightIndex;
  28472. }
  28473. else {
  28474. type = "DIRLIGHT" + lightIndex;
  28475. }
  28476. if (defines[type] === undefined) {
  28477. needRebuild = true;
  28478. }
  28479. defines[type] = true;
  28480. // Specular
  28481. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  28482. defines["SPECULARTERM"] = true;
  28483. }
  28484. // Shadows
  28485. if (scene.shadowsEnabled) {
  28486. var shadowGenerator = light.getShadowGenerator();
  28487. if (mesh && mesh.receiveShadows && shadowGenerator) {
  28488. if (defines["SHADOW" + lightIndex] === undefined) {
  28489. needRebuild = true;
  28490. }
  28491. defines["SHADOW" + lightIndex] = true;
  28492. defines["SHADOWS"] = true;
  28493. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  28494. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  28495. needRebuild = true;
  28496. }
  28497. defines["SHADOWVSM" + lightIndex] = true;
  28498. }
  28499. if (shadowGenerator.usePoissonSampling) {
  28500. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  28501. needRebuild = true;
  28502. }
  28503. defines["SHADOWPCF" + lightIndex] = true;
  28504. }
  28505. needShadows = true;
  28506. }
  28507. }
  28508. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  28509. lightmapMode = true;
  28510. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  28511. needRebuild = true;
  28512. }
  28513. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  28514. needRebuild = true;
  28515. }
  28516. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  28517. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  28518. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  28519. }
  28520. }
  28521. lightIndex++;
  28522. if (lightIndex === maxSimultaneousLights)
  28523. break;
  28524. }
  28525. var caps = scene.getEngine().getCaps();
  28526. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  28527. if (defines["SHADOWFULLFLOAT"] === undefined) {
  28528. needRebuild = true;
  28529. }
  28530. defines["SHADOWFULLFLOAT"] = true;
  28531. }
  28532. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  28533. needRebuild = true;
  28534. }
  28535. if (lightmapMode) {
  28536. defines["LIGHTMAPEXCLUDED"] = true;
  28537. }
  28538. if (needRebuild) {
  28539. defines.rebuild();
  28540. }
  28541. return needNormals;
  28542. };
  28543. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  28544. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28545. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28546. if (!defines["LIGHT" + lightIndex]) {
  28547. break;
  28548. }
  28549. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  28550. samplersList.push("shadowSampler" + lightIndex);
  28551. }
  28552. };
  28553. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  28554. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28555. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28556. if (!defines["LIGHT" + lightIndex]) {
  28557. break;
  28558. }
  28559. if (lightIndex > 0) {
  28560. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  28561. }
  28562. if (defines["SHADOW" + lightIndex]) {
  28563. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  28564. }
  28565. if (defines["SHADOWPCF" + lightIndex]) {
  28566. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  28567. }
  28568. if (defines["SHADOWVSM" + lightIndex]) {
  28569. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  28570. }
  28571. }
  28572. };
  28573. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  28574. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  28575. fallbacks.addCPUSkinningFallback(0, mesh);
  28576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28578. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  28579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28581. }
  28582. }
  28583. };
  28584. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  28585. if (defines["INSTANCES"]) {
  28586. attribs.push("world0");
  28587. attribs.push("world1");
  28588. attribs.push("world2");
  28589. attribs.push("world3");
  28590. }
  28591. };
  28592. // Bindings
  28593. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  28594. var shadowGenerator = light.getShadowGenerator();
  28595. if (mesh.receiveShadows && shadowGenerator) {
  28596. if (!light.needCube()) {
  28597. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  28598. }
  28599. else {
  28600. if (!depthValuesAlreadySet) {
  28601. depthValuesAlreadySet = true;
  28602. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  28603. }
  28604. }
  28605. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  28606. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  28607. }
  28608. return depthValuesAlreadySet;
  28609. };
  28610. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  28611. if (light instanceof BABYLON.PointLight) {
  28612. // Point Light
  28613. light.transferToEffect(effect, "vLightData" + lightIndex);
  28614. }
  28615. else if (light instanceof BABYLON.DirectionalLight) {
  28616. // Directional Light
  28617. light.transferToEffect(effect, "vLightData" + lightIndex);
  28618. }
  28619. else if (light instanceof BABYLON.SpotLight) {
  28620. // Spot Light
  28621. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  28622. }
  28623. else if (light instanceof BABYLON.HemisphericLight) {
  28624. // Hemispheric Light
  28625. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  28626. }
  28627. };
  28628. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  28629. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28630. var lightIndex = 0;
  28631. var depthValuesAlreadySet = false;
  28632. for (var index = 0; index < scene.lights.length; index++) {
  28633. var light = scene.lights[index];
  28634. if (!light.isEnabled()) {
  28635. continue;
  28636. }
  28637. if (!light.canAffectMesh(mesh)) {
  28638. continue;
  28639. }
  28640. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28641. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  28642. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  28643. if (defines["SPECULARTERM"]) {
  28644. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  28645. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  28646. }
  28647. // Shadows
  28648. if (scene.shadowsEnabled) {
  28649. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  28650. }
  28651. lightIndex++;
  28652. if (lightIndex === maxSimultaneousLights)
  28653. break;
  28654. }
  28655. };
  28656. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  28657. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  28658. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  28659. effect.setColor3("vFogColor", scene.fogColor);
  28660. }
  28661. };
  28662. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  28663. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28664. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  28665. if (matrices) {
  28666. effect.setMatrices("mBones", matrices);
  28667. }
  28668. }
  28669. };
  28670. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  28671. if (defines["LOGARITHMICDEPTH"]) {
  28672. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  28673. }
  28674. };
  28675. MaterialHelper.BindClipPlane = function (effect, scene) {
  28676. if (scene.clipPlane) {
  28677. var clipPlane = scene.clipPlane;
  28678. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28679. }
  28680. };
  28681. return MaterialHelper;
  28682. }());
  28683. BABYLON.MaterialHelper = MaterialHelper;
  28684. })(BABYLON || (BABYLON = {}));
  28685. //# sourceMappingURL=babylon.materialHelper.js.map
  28686. var BABYLON;
  28687. (function (BABYLON) {
  28688. var FresnelParameters = (function () {
  28689. function FresnelParameters() {
  28690. this.isEnabled = true;
  28691. this.leftColor = BABYLON.Color3.White();
  28692. this.rightColor = BABYLON.Color3.Black();
  28693. this.bias = 0;
  28694. this.power = 1;
  28695. }
  28696. FresnelParameters.prototype.clone = function () {
  28697. var newFresnelParameters = new FresnelParameters();
  28698. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  28699. return newFresnelParameters;
  28700. };
  28701. FresnelParameters.prototype.serialize = function () {
  28702. var serializationObject = {};
  28703. serializationObject.isEnabled = this.isEnabled;
  28704. serializationObject.leftColor = this.leftColor;
  28705. serializationObject.rightColor = this.rightColor;
  28706. serializationObject.bias = this.bias;
  28707. serializationObject.power = this.power;
  28708. return serializationObject;
  28709. };
  28710. FresnelParameters.Parse = function (parsedFresnelParameters) {
  28711. var fresnelParameters = new FresnelParameters();
  28712. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  28713. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  28714. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  28715. fresnelParameters.bias = parsedFresnelParameters.bias;
  28716. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  28717. return fresnelParameters;
  28718. };
  28719. return FresnelParameters;
  28720. }());
  28721. BABYLON.FresnelParameters = FresnelParameters;
  28722. })(BABYLON || (BABYLON = {}));
  28723. //# sourceMappingURL=babylon.fresnelParameters.js.map
  28724. var BABYLON;
  28725. (function (BABYLON) {
  28726. var MaterialDefines = (function () {
  28727. function MaterialDefines() {
  28728. }
  28729. MaterialDefines.prototype.rebuild = function () {
  28730. if (this._keys) {
  28731. delete this._keys;
  28732. }
  28733. this._keys = Object.keys(this);
  28734. };
  28735. MaterialDefines.prototype.isEqual = function (other) {
  28736. if (this._keys.length !== other._keys.length) {
  28737. return false;
  28738. }
  28739. for (var index = 0; index < this._keys.length; index++) {
  28740. var prop = this._keys[index];
  28741. if (this[prop] !== other[prop]) {
  28742. return false;
  28743. }
  28744. }
  28745. return true;
  28746. };
  28747. MaterialDefines.prototype.cloneTo = function (other) {
  28748. if (this._keys.length !== other._keys.length) {
  28749. other._keys = this._keys.slice(0);
  28750. }
  28751. for (var index = 0; index < this._keys.length; index++) {
  28752. var prop = this._keys[index];
  28753. other[prop] = this[prop];
  28754. }
  28755. };
  28756. MaterialDefines.prototype.reset = function () {
  28757. for (var index = 0; index < this._keys.length; index++) {
  28758. var prop = this._keys[index];
  28759. if (typeof (this[prop]) === "number") {
  28760. this[prop] = 0;
  28761. }
  28762. else {
  28763. this[prop] = false;
  28764. }
  28765. }
  28766. };
  28767. MaterialDefines.prototype.toString = function () {
  28768. var result = "";
  28769. for (var index = 0; index < this._keys.length; index++) {
  28770. var prop = this._keys[index];
  28771. if (typeof (this[prop]) === "number") {
  28772. result += "#define " + prop + " " + this[prop] + "\n";
  28773. }
  28774. else if (this[prop]) {
  28775. result += "#define " + prop + "\n";
  28776. }
  28777. }
  28778. return result;
  28779. };
  28780. return MaterialDefines;
  28781. }());
  28782. BABYLON.MaterialDefines = MaterialDefines;
  28783. var Material = (function () {
  28784. function Material(name, scene, doNotAdd) {
  28785. this.checkReadyOnEveryCall = false;
  28786. this.checkReadyOnlyOnce = false;
  28787. this.state = "";
  28788. this.alpha = 1.0;
  28789. this.backFaceCulling = true;
  28790. this.doNotSerialize = false;
  28791. /**
  28792. * An event triggered when the material is disposed.
  28793. * @type {BABYLON.Observable}
  28794. */
  28795. this.onDisposeObservable = new BABYLON.Observable();
  28796. /**
  28797. * An event triggered when the material is bound.
  28798. * @type {BABYLON.Observable}
  28799. */
  28800. this.onBindObservable = new BABYLON.Observable();
  28801. /**
  28802. * An event triggered when the material is unbound.
  28803. * @type {BABYLON.Observable}
  28804. */
  28805. this.onUnBindObservable = new BABYLON.Observable();
  28806. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28807. this.disableDepthWrite = false;
  28808. this.fogEnabled = true;
  28809. this.pointSize = 1.0;
  28810. this.zOffset = 0;
  28811. this._wasPreviouslyReady = false;
  28812. this._fillMode = Material.TriangleFillMode;
  28813. this.name = name;
  28814. this.id = name;
  28815. this._scene = scene;
  28816. if (scene.useRightHandedSystem) {
  28817. this.sideOrientation = Material.ClockWiseSideOrientation;
  28818. }
  28819. else {
  28820. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28821. }
  28822. if (!doNotAdd) {
  28823. scene.materials.push(this);
  28824. }
  28825. }
  28826. Object.defineProperty(Material, "TriangleFillMode", {
  28827. get: function () {
  28828. return Material._TriangleFillMode;
  28829. },
  28830. enumerable: true,
  28831. configurable: true
  28832. });
  28833. Object.defineProperty(Material, "WireFrameFillMode", {
  28834. get: function () {
  28835. return Material._WireFrameFillMode;
  28836. },
  28837. enumerable: true,
  28838. configurable: true
  28839. });
  28840. Object.defineProperty(Material, "PointFillMode", {
  28841. get: function () {
  28842. return Material._PointFillMode;
  28843. },
  28844. enumerable: true,
  28845. configurable: true
  28846. });
  28847. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28848. get: function () {
  28849. return Material._ClockWiseSideOrientation;
  28850. },
  28851. enumerable: true,
  28852. configurable: true
  28853. });
  28854. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28855. get: function () {
  28856. return Material._CounterClockWiseSideOrientation;
  28857. },
  28858. enumerable: true,
  28859. configurable: true
  28860. });
  28861. Object.defineProperty(Material.prototype, "onDispose", {
  28862. set: function (callback) {
  28863. if (this._onDisposeObserver) {
  28864. this.onDisposeObservable.remove(this._onDisposeObserver);
  28865. }
  28866. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28867. },
  28868. enumerable: true,
  28869. configurable: true
  28870. });
  28871. Object.defineProperty(Material.prototype, "onBind", {
  28872. set: function (callback) {
  28873. if (this._onBindObserver) {
  28874. this.onBindObservable.remove(this._onBindObserver);
  28875. }
  28876. this._onBindObserver = this.onBindObservable.add(callback);
  28877. },
  28878. enumerable: true,
  28879. configurable: true
  28880. });
  28881. Object.defineProperty(Material.prototype, "wireframe", {
  28882. get: function () {
  28883. return this._fillMode === Material.WireFrameFillMode;
  28884. },
  28885. set: function (value) {
  28886. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28887. },
  28888. enumerable: true,
  28889. configurable: true
  28890. });
  28891. Object.defineProperty(Material.prototype, "pointsCloud", {
  28892. get: function () {
  28893. return this._fillMode === Material.PointFillMode;
  28894. },
  28895. set: function (value) {
  28896. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28897. },
  28898. enumerable: true,
  28899. configurable: true
  28900. });
  28901. Object.defineProperty(Material.prototype, "fillMode", {
  28902. get: function () {
  28903. return this._fillMode;
  28904. },
  28905. set: function (value) {
  28906. this._fillMode = value;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. /**
  28912. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28913. * subclasses should override adding information pertainent to themselves
  28914. */
  28915. Material.prototype.toString = function (fullDetails) {
  28916. var ret = "Name: " + this.name;
  28917. if (fullDetails) {
  28918. }
  28919. return ret;
  28920. };
  28921. Material.prototype.getClassName = function () {
  28922. return "Material";
  28923. };
  28924. Object.defineProperty(Material.prototype, "isFrozen", {
  28925. get: function () {
  28926. return this.checkReadyOnlyOnce;
  28927. },
  28928. enumerable: true,
  28929. configurable: true
  28930. });
  28931. Material.prototype.freeze = function () {
  28932. this.checkReadyOnlyOnce = true;
  28933. };
  28934. Material.prototype.unfreeze = function () {
  28935. this.checkReadyOnlyOnce = false;
  28936. };
  28937. Material.prototype.isReady = function (mesh, useInstances) {
  28938. return true;
  28939. };
  28940. Material.prototype.getEffect = function () {
  28941. return this._effect;
  28942. };
  28943. Material.prototype.getScene = function () {
  28944. return this._scene;
  28945. };
  28946. Material.prototype.needAlphaBlending = function () {
  28947. return (this.alpha < 1.0);
  28948. };
  28949. Material.prototype.needAlphaTesting = function () {
  28950. return false;
  28951. };
  28952. Material.prototype.getAlphaTestTexture = function () {
  28953. return null;
  28954. };
  28955. Material.prototype.markDirty = function () {
  28956. this._wasPreviouslyReady = false;
  28957. };
  28958. Material.prototype._preBind = function () {
  28959. var engine = this._scene.getEngine();
  28960. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  28961. engine.enableEffect(this._effect);
  28962. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28963. };
  28964. Material.prototype.bind = function (world, mesh) {
  28965. this._scene._cachedMaterial = this;
  28966. this.onBindObservable.notifyObservers(mesh);
  28967. if (this.disableDepthWrite) {
  28968. var engine = this._scene.getEngine();
  28969. this._cachedDepthWriteState = engine.getDepthWrite();
  28970. engine.setDepthWrite(false);
  28971. }
  28972. };
  28973. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28974. };
  28975. Material.prototype.unbind = function () {
  28976. this.onUnBindObservable.notifyObservers(this);
  28977. if (this.disableDepthWrite) {
  28978. var engine = this._scene.getEngine();
  28979. engine.setDepthWrite(this._cachedDepthWriteState);
  28980. }
  28981. };
  28982. Material.prototype.clone = function (name) {
  28983. return null;
  28984. };
  28985. Material.prototype.getBindedMeshes = function () {
  28986. var result = new Array();
  28987. for (var index = 0; index < this._scene.meshes.length; index++) {
  28988. var mesh = this._scene.meshes[index];
  28989. if (mesh.material === this) {
  28990. result.push(mesh);
  28991. }
  28992. }
  28993. return result;
  28994. };
  28995. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28996. // Animations
  28997. this.getScene().stopAnimation(this);
  28998. // Remove from scene
  28999. var index = this._scene.materials.indexOf(this);
  29000. if (index >= 0) {
  29001. this._scene.materials.splice(index, 1);
  29002. }
  29003. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29004. if (forceDisposeEffect && this._effect) {
  29005. this._scene.getEngine()._releaseEffect(this._effect);
  29006. this._effect = null;
  29007. }
  29008. // Remove from meshes
  29009. for (index = 0; index < this._scene.meshes.length; index++) {
  29010. var mesh = this._scene.meshes[index];
  29011. if (mesh.material === this) {
  29012. mesh.material = null;
  29013. }
  29014. }
  29015. // Callback
  29016. this.onDisposeObservable.notifyObservers(this);
  29017. this.onDisposeObservable.clear();
  29018. this.onBindObservable.clear();
  29019. this.onUnBindObservable.clear();
  29020. };
  29021. Material.prototype.serialize = function () {
  29022. return BABYLON.SerializationHelper.Serialize(this);
  29023. };
  29024. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29025. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29026. multiMaterial.id = parsedMultiMaterial.id;
  29027. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29028. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29029. var subMatId = parsedMultiMaterial.materials[matIndex];
  29030. if (subMatId) {
  29031. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29032. }
  29033. else {
  29034. multiMaterial.subMaterials.push(null);
  29035. }
  29036. }
  29037. return multiMaterial;
  29038. };
  29039. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29040. if (!parsedMaterial.customType) {
  29041. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29042. }
  29043. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29044. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29045. ;
  29046. };
  29047. return Material;
  29048. }());
  29049. Material._TriangleFillMode = 0;
  29050. Material._WireFrameFillMode = 1;
  29051. Material._PointFillMode = 2;
  29052. Material._ClockWiseSideOrientation = 0;
  29053. Material._CounterClockWiseSideOrientation = 1;
  29054. __decorate([
  29055. BABYLON.serialize()
  29056. ], Material.prototype, "id", void 0);
  29057. __decorate([
  29058. BABYLON.serialize()
  29059. ], Material.prototype, "name", void 0);
  29060. __decorate([
  29061. BABYLON.serialize()
  29062. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29063. __decorate([
  29064. BABYLON.serialize()
  29065. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29066. __decorate([
  29067. BABYLON.serialize()
  29068. ], Material.prototype, "state", void 0);
  29069. __decorate([
  29070. BABYLON.serialize()
  29071. ], Material.prototype, "alpha", void 0);
  29072. __decorate([
  29073. BABYLON.serialize()
  29074. ], Material.prototype, "backFaceCulling", void 0);
  29075. __decorate([
  29076. BABYLON.serialize()
  29077. ], Material.prototype, "sideOrientation", void 0);
  29078. __decorate([
  29079. BABYLON.serialize()
  29080. ], Material.prototype, "alphaMode", void 0);
  29081. __decorate([
  29082. BABYLON.serialize()
  29083. ], Material.prototype, "disableDepthWrite", void 0);
  29084. __decorate([
  29085. BABYLON.serialize()
  29086. ], Material.prototype, "fogEnabled", void 0);
  29087. __decorate([
  29088. BABYLON.serialize()
  29089. ], Material.prototype, "pointSize", void 0);
  29090. __decorate([
  29091. BABYLON.serialize()
  29092. ], Material.prototype, "zOffset", void 0);
  29093. __decorate([
  29094. BABYLON.serialize()
  29095. ], Material.prototype, "wireframe", null);
  29096. __decorate([
  29097. BABYLON.serialize()
  29098. ], Material.prototype, "pointsCloud", null);
  29099. __decorate([
  29100. BABYLON.serialize()
  29101. ], Material.prototype, "fillMode", null);
  29102. BABYLON.Material = Material;
  29103. })(BABYLON || (BABYLON = {}));
  29104. //# sourceMappingURL=babylon.material.js.map
  29105. var BABYLON;
  29106. (function (BABYLON) {
  29107. var StandardMaterialDefines = (function (_super) {
  29108. __extends(StandardMaterialDefines, _super);
  29109. function StandardMaterialDefines() {
  29110. var _this = _super.call(this) || this;
  29111. _this.DIFFUSE = false;
  29112. _this.AMBIENT = false;
  29113. _this.OPACITY = false;
  29114. _this.OPACITYRGB = false;
  29115. _this.REFLECTION = false;
  29116. _this.EMISSIVE = false;
  29117. _this.SPECULAR = false;
  29118. _this.BUMP = false;
  29119. _this.PARALLAX = false;
  29120. _this.PARALLAXOCCLUSION = false;
  29121. _this.SPECULAROVERALPHA = false;
  29122. _this.CLIPPLANE = false;
  29123. _this.ALPHATEST = false;
  29124. _this.ALPHAFROMDIFFUSE = false;
  29125. _this.POINTSIZE = false;
  29126. _this.FOG = false;
  29127. _this.SPECULARTERM = false;
  29128. _this.DIFFUSEFRESNEL = false;
  29129. _this.OPACITYFRESNEL = false;
  29130. _this.REFLECTIONFRESNEL = false;
  29131. _this.REFRACTIONFRESNEL = false;
  29132. _this.EMISSIVEFRESNEL = false;
  29133. _this.FRESNEL = false;
  29134. _this.NORMAL = false;
  29135. _this.UV1 = false;
  29136. _this.UV2 = false;
  29137. _this.VERTEXCOLOR = false;
  29138. _this.VERTEXALPHA = false;
  29139. _this.NUM_BONE_INFLUENCERS = 0;
  29140. _this.BonesPerMesh = 0;
  29141. _this.INSTANCES = false;
  29142. _this.GLOSSINESS = false;
  29143. _this.ROUGHNESS = false;
  29144. _this.EMISSIVEASILLUMINATION = false;
  29145. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29146. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29147. _this.LIGHTMAP = false;
  29148. _this.USELIGHTMAPASSHADOWMAP = false;
  29149. _this.REFLECTIONMAP_3D = false;
  29150. _this.REFLECTIONMAP_SPHERICAL = false;
  29151. _this.REFLECTIONMAP_PLANAR = false;
  29152. _this.REFLECTIONMAP_CUBIC = false;
  29153. _this.REFLECTIONMAP_PROJECTION = false;
  29154. _this.REFLECTIONMAP_SKYBOX = false;
  29155. _this.REFLECTIONMAP_EXPLICIT = false;
  29156. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29157. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29158. _this.INVERTCUBICMAP = false;
  29159. _this.LOGARITHMICDEPTH = false;
  29160. _this.REFRACTION = false;
  29161. _this.REFRACTIONMAP_3D = false;
  29162. _this.REFLECTIONOVERALPHA = false;
  29163. _this.INVERTNORMALMAPX = false;
  29164. _this.INVERTNORMALMAPY = false;
  29165. _this.SHADOWFULLFLOAT = false;
  29166. _this.CAMERACOLORGRADING = false;
  29167. _this.CAMERACOLORCURVES = false;
  29168. _this.rebuild();
  29169. return _this;
  29170. }
  29171. return StandardMaterialDefines;
  29172. }(BABYLON.MaterialDefines));
  29173. var StandardMaterial = (function (_super) {
  29174. __extends(StandardMaterial, _super);
  29175. function StandardMaterial(name, scene) {
  29176. var _this = _super.call(this, name, scene) || this;
  29177. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29178. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29179. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29180. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29181. _this.specularPower = 64;
  29182. _this.useAlphaFromDiffuseTexture = false;
  29183. _this.useEmissiveAsIllumination = false;
  29184. _this.linkEmissiveWithDiffuse = false;
  29185. _this.useReflectionFresnelFromSpecular = false;
  29186. _this.useSpecularOverAlpha = false;
  29187. _this.useReflectionOverAlpha = false;
  29188. _this.disableLighting = false;
  29189. _this.useParallax = false;
  29190. _this.useParallaxOcclusion = false;
  29191. _this.parallaxScaleBias = 0.05;
  29192. _this.roughness = 0;
  29193. _this.indexOfRefraction = 0.98;
  29194. _this.invertRefractionY = true;
  29195. _this.useLightmapAsShadowmap = false;
  29196. _this.useGlossinessFromSpecularMapAlpha = false;
  29197. _this.maxSimultaneousLights = 4;
  29198. /**
  29199. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29200. */
  29201. _this.invertNormalMapX = false;
  29202. /**
  29203. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29204. */
  29205. _this.invertNormalMapY = false;
  29206. /**
  29207. * Color Grading 2D Lookup Texture.
  29208. * This allows special effects like sepia, black and white to sixties rendering style.
  29209. */
  29210. _this.cameraColorGradingTexture = null;
  29211. /**
  29212. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29213. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29214. * 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;
  29215. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29216. */
  29217. _this.cameraColorCurves = null;
  29218. _this._renderTargets = new BABYLON.SmartArray(16);
  29219. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29220. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29221. _this._defines = new StandardMaterialDefines();
  29222. _this._cachedDefines = new StandardMaterialDefines();
  29223. _this._cachedDefines.BonesPerMesh = -1;
  29224. _this.getRenderTargetTextures = function () {
  29225. _this._renderTargets.reset();
  29226. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  29227. _this._renderTargets.push(_this.reflectionTexture);
  29228. }
  29229. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  29230. _this._renderTargets.push(_this.refractionTexture);
  29231. }
  29232. return _this._renderTargets;
  29233. };
  29234. return _this;
  29235. }
  29236. StandardMaterial.prototype.getClassName = function () {
  29237. return "StandardMaterial";
  29238. };
  29239. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29240. get: function () {
  29241. return this._useLogarithmicDepth;
  29242. },
  29243. set: function (value) {
  29244. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29245. },
  29246. enumerable: true,
  29247. configurable: true
  29248. });
  29249. StandardMaterial.prototype.needAlphaBlending = function () {
  29250. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  29251. };
  29252. StandardMaterial.prototype.needAlphaTesting = function () {
  29253. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  29254. };
  29255. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29256. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  29257. };
  29258. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29259. return this.diffuseTexture;
  29260. };
  29261. // Methods
  29262. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29263. if (!mesh) {
  29264. return true;
  29265. }
  29266. if (this._defines.INSTANCES !== useInstances) {
  29267. return false;
  29268. }
  29269. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  29270. return true;
  29271. }
  29272. return false;
  29273. };
  29274. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  29275. if (this.isFrozen) {
  29276. if (this._wasPreviouslyReady) {
  29277. return true;
  29278. }
  29279. }
  29280. var scene = this.getScene();
  29281. var engine = scene.getEngine();
  29282. var needUVs = false;
  29283. var needNormals = false;
  29284. this._defines.reset();
  29285. // Lights
  29286. if (scene.lightsEnabled && !this.disableLighting) {
  29287. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  29288. }
  29289. if (!this.checkReadyOnEveryCall) {
  29290. if (this._renderId === scene.getRenderId()) {
  29291. if (this._checkCache(scene, mesh, useInstances)) {
  29292. return true;
  29293. }
  29294. }
  29295. }
  29296. // Textures
  29297. if (scene.texturesEnabled) {
  29298. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29299. if (!this.diffuseTexture.isReady()) {
  29300. return false;
  29301. }
  29302. else {
  29303. needUVs = true;
  29304. this._defines.DIFFUSE = true;
  29305. }
  29306. }
  29307. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29308. if (!this.ambientTexture.isReady()) {
  29309. return false;
  29310. }
  29311. else {
  29312. needUVs = true;
  29313. this._defines.AMBIENT = true;
  29314. }
  29315. }
  29316. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29317. if (!this.opacityTexture.isReady()) {
  29318. return false;
  29319. }
  29320. else {
  29321. needUVs = true;
  29322. this._defines.OPACITY = true;
  29323. if (this.opacityTexture.getAlphaFromRGB) {
  29324. this._defines.OPACITYRGB = true;
  29325. }
  29326. }
  29327. }
  29328. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29329. if (!this.reflectionTexture.isReady()) {
  29330. return false;
  29331. }
  29332. else {
  29333. needNormals = true;
  29334. this._defines.REFLECTION = true;
  29335. if (this.roughness > 0) {
  29336. this._defines.ROUGHNESS = true;
  29337. }
  29338. if (this.useReflectionOverAlpha) {
  29339. this._defines.REFLECTIONOVERALPHA = true;
  29340. }
  29341. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29342. this._defines.INVERTCUBICMAP = true;
  29343. }
  29344. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  29345. switch (this.reflectionTexture.coordinatesMode) {
  29346. case BABYLON.Texture.CUBIC_MODE:
  29347. case BABYLON.Texture.INVCUBIC_MODE:
  29348. this._defines.REFLECTIONMAP_CUBIC = true;
  29349. break;
  29350. case BABYLON.Texture.EXPLICIT_MODE:
  29351. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29352. break;
  29353. case BABYLON.Texture.PLANAR_MODE:
  29354. this._defines.REFLECTIONMAP_PLANAR = true;
  29355. break;
  29356. case BABYLON.Texture.PROJECTION_MODE:
  29357. this._defines.REFLECTIONMAP_PROJECTION = true;
  29358. break;
  29359. case BABYLON.Texture.SKYBOX_MODE:
  29360. this._defines.REFLECTIONMAP_SKYBOX = true;
  29361. break;
  29362. case BABYLON.Texture.SPHERICAL_MODE:
  29363. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29364. break;
  29365. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29366. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29367. break;
  29368. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29369. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29370. break;
  29371. }
  29372. }
  29373. }
  29374. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29375. if (!this.emissiveTexture.isReady()) {
  29376. return false;
  29377. }
  29378. else {
  29379. needUVs = true;
  29380. this._defines.EMISSIVE = true;
  29381. }
  29382. }
  29383. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29384. if (!this.lightmapTexture.isReady()) {
  29385. return false;
  29386. }
  29387. else {
  29388. needUVs = true;
  29389. this._defines.LIGHTMAP = true;
  29390. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  29391. }
  29392. }
  29393. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29394. if (!this.specularTexture.isReady()) {
  29395. return false;
  29396. }
  29397. else {
  29398. needUVs = true;
  29399. this._defines.SPECULAR = true;
  29400. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  29401. }
  29402. }
  29403. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29404. if (!this.bumpTexture.isReady()) {
  29405. return false;
  29406. }
  29407. else {
  29408. needUVs = true;
  29409. this._defines.BUMP = true;
  29410. if (this.useParallax) {
  29411. this._defines.PARALLAX = true;
  29412. if (this.useParallaxOcclusion) {
  29413. this._defines.PARALLAXOCCLUSION = true;
  29414. }
  29415. }
  29416. if (this.invertNormalMapX) {
  29417. this._defines.INVERTNORMALMAPX = true;
  29418. }
  29419. if (this.invertNormalMapY) {
  29420. this._defines.INVERTNORMALMAPY = true;
  29421. }
  29422. if (scene._mirroredCameraPosition) {
  29423. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29424. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29425. }
  29426. }
  29427. }
  29428. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29429. if (!this.refractionTexture.isReady()) {
  29430. return false;
  29431. }
  29432. else {
  29433. needUVs = true;
  29434. this._defines.REFRACTION = true;
  29435. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29436. }
  29437. }
  29438. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29439. if (!this.cameraColorGradingTexture.isReady()) {
  29440. return false;
  29441. }
  29442. else {
  29443. this._defines.CAMERACOLORGRADING = true;
  29444. }
  29445. }
  29446. }
  29447. // Effect
  29448. if (scene.clipPlane) {
  29449. this._defines.CLIPPLANE = true;
  29450. }
  29451. if (engine.getAlphaTesting()) {
  29452. this._defines.ALPHATEST = true;
  29453. }
  29454. if (this._shouldUseAlphaFromDiffuseTexture()) {
  29455. this._defines.ALPHAFROMDIFFUSE = true;
  29456. }
  29457. if (this.useEmissiveAsIllumination) {
  29458. this._defines.EMISSIVEASILLUMINATION = true;
  29459. }
  29460. if (this.linkEmissiveWithDiffuse) {
  29461. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  29462. }
  29463. if (this.useLogarithmicDepth) {
  29464. this._defines.LOGARITHMICDEPTH = true;
  29465. }
  29466. if (this.cameraColorCurves) {
  29467. this._defines.CAMERACOLORCURVES = true;
  29468. }
  29469. // Point size
  29470. if (this.pointsCloud || scene.forcePointsCloud) {
  29471. this._defines.POINTSIZE = true;
  29472. }
  29473. // Fog
  29474. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29475. this._defines.FOG = true;
  29476. }
  29477. if (StandardMaterial.FresnelEnabled) {
  29478. // Fresnel
  29479. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  29480. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29481. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  29482. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  29483. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29484. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29485. this._defines.DIFFUSEFRESNEL = true;
  29486. }
  29487. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29488. this._defines.OPACITYFRESNEL = true;
  29489. }
  29490. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29491. this._defines.REFLECTIONFRESNEL = true;
  29492. if (this.useReflectionFresnelFromSpecular) {
  29493. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  29494. }
  29495. }
  29496. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29497. this._defines.REFRACTIONFRESNEL = true;
  29498. }
  29499. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29500. this._defines.EMISSIVEFRESNEL = true;
  29501. }
  29502. needNormals = true;
  29503. this._defines.FRESNEL = true;
  29504. }
  29505. }
  29506. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29507. this._defines.SPECULAROVERALPHA = true;
  29508. }
  29509. // Attribs
  29510. if (mesh) {
  29511. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29512. this._defines.NORMAL = true;
  29513. }
  29514. if (needUVs) {
  29515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29516. this._defines.UV1 = true;
  29517. }
  29518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29519. this._defines.UV2 = true;
  29520. }
  29521. }
  29522. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29523. this._defines.VERTEXCOLOR = true;
  29524. if (mesh.hasVertexAlpha) {
  29525. this._defines.VERTEXALPHA = true;
  29526. }
  29527. }
  29528. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29529. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29530. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29531. }
  29532. // Instances
  29533. if (useInstances) {
  29534. this._defines.INSTANCES = true;
  29535. }
  29536. }
  29537. // Get correct effect
  29538. if (!this._defines.isEqual(this._cachedDefines)) {
  29539. this._defines.cloneTo(this._cachedDefines);
  29540. scene.resetCachedMaterial();
  29541. // Fallbacks
  29542. var fallbacks = new BABYLON.EffectFallbacks();
  29543. if (this._defines.REFLECTION) {
  29544. fallbacks.addFallback(0, "REFLECTION");
  29545. }
  29546. if (this._defines.SPECULAR) {
  29547. fallbacks.addFallback(0, "SPECULAR");
  29548. }
  29549. if (this._defines.BUMP) {
  29550. fallbacks.addFallback(0, "BUMP");
  29551. }
  29552. if (this._defines.PARALLAX) {
  29553. fallbacks.addFallback(1, "PARALLAX");
  29554. }
  29555. if (this._defines.PARALLAXOCCLUSION) {
  29556. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29557. }
  29558. if (this._defines.SPECULAROVERALPHA) {
  29559. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29560. }
  29561. if (this._defines.FOG) {
  29562. fallbacks.addFallback(1, "FOG");
  29563. }
  29564. if (this._defines.POINTSIZE) {
  29565. fallbacks.addFallback(0, "POINTSIZE");
  29566. }
  29567. if (this._defines.LOGARITHMICDEPTH) {
  29568. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29569. }
  29570. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29571. if (this._defines.SPECULARTERM) {
  29572. fallbacks.addFallback(0, "SPECULARTERM");
  29573. }
  29574. if (this._defines.DIFFUSEFRESNEL) {
  29575. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29576. }
  29577. if (this._defines.OPACITYFRESNEL) {
  29578. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29579. }
  29580. if (this._defines.REFLECTIONFRESNEL) {
  29581. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29582. }
  29583. if (this._defines.EMISSIVEFRESNEL) {
  29584. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29585. }
  29586. if (this._defines.FRESNEL) {
  29587. fallbacks.addFallback(4, "FRESNEL");
  29588. }
  29589. //Attributes
  29590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29591. if (this._defines.NORMAL) {
  29592. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29593. }
  29594. if (this._defines.UV1) {
  29595. attribs.push(BABYLON.VertexBuffer.UVKind);
  29596. }
  29597. if (this._defines.UV2) {
  29598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29599. }
  29600. if (this._defines.VERTEXCOLOR) {
  29601. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29602. }
  29603. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29604. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29605. var shaderName = "default";
  29606. var join = this._defines.toString();
  29607. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29608. "vFogInfos", "vFogColor", "pointSize",
  29609. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29610. "mBones",
  29611. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29612. "depthValues",
  29613. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29614. "logarithmicDepthConstant"
  29615. ];
  29616. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29617. if (this._defines.CAMERACOLORCURVES) {
  29618. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29619. }
  29620. if (this._defines.CAMERACOLORGRADING) {
  29621. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29622. }
  29623. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  29624. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  29625. }
  29626. if (!this._effect.isReady()) {
  29627. return false;
  29628. }
  29629. this._renderId = scene.getRenderId();
  29630. this._wasPreviouslyReady = true;
  29631. if (mesh) {
  29632. if (!mesh._materialDefines) {
  29633. mesh._materialDefines = new StandardMaterialDefines();
  29634. }
  29635. this._defines.cloneTo(mesh._materialDefines);
  29636. }
  29637. return true;
  29638. };
  29639. StandardMaterial.prototype.unbind = function () {
  29640. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29641. this._effect.setTexture("reflection2DSampler", null);
  29642. }
  29643. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29644. this._effect.setTexture("refraction2DSampler", null);
  29645. }
  29646. _super.prototype.unbind.call(this);
  29647. };
  29648. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29649. this._effect.setMatrix("world", world);
  29650. };
  29651. StandardMaterial.prototype.bind = function (world, mesh) {
  29652. var scene = this.getScene();
  29653. // Matrices
  29654. this.bindOnlyWorldMatrix(world);
  29655. // Bones
  29656. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29657. if (scene.getCachedMaterial() !== this) {
  29658. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29659. if (StandardMaterial.FresnelEnabled) {
  29660. // Fresnel
  29661. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29662. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29663. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29664. }
  29665. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29666. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29667. }
  29668. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29669. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29670. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29671. }
  29672. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29673. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29674. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29675. }
  29676. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29677. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29678. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29679. }
  29680. }
  29681. // Textures
  29682. if (scene.texturesEnabled) {
  29683. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29684. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  29685. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  29686. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  29687. }
  29688. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29689. this._effect.setTexture("ambientSampler", this.ambientTexture);
  29690. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  29691. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29692. }
  29693. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29694. this._effect.setTexture("opacitySampler", this.opacityTexture);
  29695. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29696. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29697. }
  29698. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29699. if (this.reflectionTexture.isCube) {
  29700. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29701. }
  29702. else {
  29703. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  29704. }
  29705. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29706. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  29707. }
  29708. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29709. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  29710. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29711. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29712. }
  29713. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29714. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  29715. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29716. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29717. }
  29718. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29719. this._effect.setTexture("specularSampler", this.specularTexture);
  29720. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  29721. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  29722. }
  29723. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29724. this._effect.setTexture("bumpSampler", this.bumpTexture);
  29725. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29726. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29727. }
  29728. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29729. var depth = 1.0;
  29730. if (this.refractionTexture.isCube) {
  29731. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  29732. }
  29733. else {
  29734. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  29735. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29736. if (this.refractionTexture.depth) {
  29737. depth = this.refractionTexture.depth;
  29738. }
  29739. }
  29740. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29741. }
  29742. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29743. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29744. }
  29745. }
  29746. // Clip plane
  29747. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  29748. // Point size
  29749. if (this.pointsCloud) {
  29750. this._effect.setFloat("pointSize", this.pointSize);
  29751. }
  29752. // Colors
  29753. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29754. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29755. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29756. if (this._defines.SPECULARTERM) {
  29757. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  29758. }
  29759. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  29760. }
  29761. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  29762. // Diffuse
  29763. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29764. // Lights
  29765. if (scene.lightsEnabled && !this.disableLighting) {
  29766. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  29767. }
  29768. // View
  29769. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  29770. this._effect.setMatrix("view", scene.getViewMatrix());
  29771. }
  29772. // Fog
  29773. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  29774. // Log. depth
  29775. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  29776. // Color Curves
  29777. if (this.cameraColorCurves) {
  29778. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29779. }
  29780. }
  29781. _super.prototype.bind.call(this, world, mesh);
  29782. };
  29783. StandardMaterial.prototype.getAnimatables = function () {
  29784. var results = [];
  29785. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  29786. results.push(this.diffuseTexture);
  29787. }
  29788. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29789. results.push(this.ambientTexture);
  29790. }
  29791. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29792. results.push(this.opacityTexture);
  29793. }
  29794. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29795. results.push(this.reflectionTexture);
  29796. }
  29797. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29798. results.push(this.emissiveTexture);
  29799. }
  29800. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  29801. results.push(this.specularTexture);
  29802. }
  29803. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29804. results.push(this.bumpTexture);
  29805. }
  29806. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29807. results.push(this.lightmapTexture);
  29808. }
  29809. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29810. results.push(this.refractionTexture);
  29811. }
  29812. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29813. results.push(this.cameraColorGradingTexture);
  29814. }
  29815. return results;
  29816. };
  29817. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29818. if (forceDisposeTextures) {
  29819. if (this.diffuseTexture) {
  29820. this.diffuseTexture.dispose();
  29821. }
  29822. if (this.ambientTexture) {
  29823. this.ambientTexture.dispose();
  29824. }
  29825. if (this.opacityTexture) {
  29826. this.opacityTexture.dispose();
  29827. }
  29828. if (this.reflectionTexture) {
  29829. this.reflectionTexture.dispose();
  29830. }
  29831. if (this.emissiveTexture) {
  29832. this.emissiveTexture.dispose();
  29833. }
  29834. if (this.specularTexture) {
  29835. this.specularTexture.dispose();
  29836. }
  29837. if (this.bumpTexture) {
  29838. this.bumpTexture.dispose();
  29839. }
  29840. if (this.lightmapTexture) {
  29841. this.lightmapTexture.dispose();
  29842. }
  29843. if (this.refractionTexture) {
  29844. this.refractionTexture.dispose();
  29845. }
  29846. if (this.cameraColorGradingTexture) {
  29847. this.cameraColorGradingTexture.dispose();
  29848. }
  29849. }
  29850. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29851. };
  29852. StandardMaterial.prototype.clone = function (name) {
  29853. var _this = this;
  29854. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29855. };
  29856. StandardMaterial.prototype.serialize = function () {
  29857. return BABYLON.SerializationHelper.Serialize(this);
  29858. };
  29859. // Statics
  29860. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29861. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29862. };
  29863. return StandardMaterial;
  29864. }(BABYLON.Material));
  29865. // Flags used to enable or disable a type of texture for all Standard Materials
  29866. StandardMaterial.DiffuseTextureEnabled = true;
  29867. StandardMaterial.AmbientTextureEnabled = true;
  29868. StandardMaterial.OpacityTextureEnabled = true;
  29869. StandardMaterial.ReflectionTextureEnabled = true;
  29870. StandardMaterial.EmissiveTextureEnabled = true;
  29871. StandardMaterial.SpecularTextureEnabled = true;
  29872. StandardMaterial.BumpTextureEnabled = true;
  29873. StandardMaterial.FresnelEnabled = true;
  29874. StandardMaterial.LightmapTextureEnabled = true;
  29875. StandardMaterial.RefractionTextureEnabled = true;
  29876. StandardMaterial.ColorGradingTextureEnabled = true;
  29877. __decorate([
  29878. BABYLON.serializeAsTexture()
  29879. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29880. __decorate([
  29881. BABYLON.serializeAsTexture()
  29882. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29883. __decorate([
  29884. BABYLON.serializeAsTexture()
  29885. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29886. __decorate([
  29887. BABYLON.serializeAsTexture()
  29888. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29889. __decorate([
  29890. BABYLON.serializeAsTexture()
  29891. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29892. __decorate([
  29893. BABYLON.serializeAsTexture()
  29894. ], StandardMaterial.prototype, "specularTexture", void 0);
  29895. __decorate([
  29896. BABYLON.serializeAsTexture()
  29897. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29898. __decorate([
  29899. BABYLON.serializeAsTexture()
  29900. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29901. __decorate([
  29902. BABYLON.serializeAsTexture()
  29903. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29904. __decorate([
  29905. BABYLON.serializeAsColor3("ambient")
  29906. ], StandardMaterial.prototype, "ambientColor", void 0);
  29907. __decorate([
  29908. BABYLON.serializeAsColor3("diffuse")
  29909. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29910. __decorate([
  29911. BABYLON.serializeAsColor3("specular")
  29912. ], StandardMaterial.prototype, "specularColor", void 0);
  29913. __decorate([
  29914. BABYLON.serializeAsColor3("emissive")
  29915. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29916. __decorate([
  29917. BABYLON.serialize()
  29918. ], StandardMaterial.prototype, "specularPower", void 0);
  29919. __decorate([
  29920. BABYLON.serialize()
  29921. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29922. __decorate([
  29923. BABYLON.serialize()
  29924. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29925. __decorate([
  29926. BABYLON.serialize()
  29927. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29928. __decorate([
  29929. BABYLON.serialize()
  29930. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29931. __decorate([
  29932. BABYLON.serialize()
  29933. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29934. __decorate([
  29935. BABYLON.serialize()
  29936. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29937. __decorate([
  29938. BABYLON.serialize()
  29939. ], StandardMaterial.prototype, "disableLighting", void 0);
  29940. __decorate([
  29941. BABYLON.serialize()
  29942. ], StandardMaterial.prototype, "useParallax", void 0);
  29943. __decorate([
  29944. BABYLON.serialize()
  29945. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29946. __decorate([
  29947. BABYLON.serialize()
  29948. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29949. __decorate([
  29950. BABYLON.serialize()
  29951. ], StandardMaterial.prototype, "roughness", void 0);
  29952. __decorate([
  29953. BABYLON.serialize()
  29954. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29955. __decorate([
  29956. BABYLON.serialize()
  29957. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29958. __decorate([
  29959. BABYLON.serialize()
  29960. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29961. __decorate([
  29962. BABYLON.serializeAsFresnelParameters()
  29963. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29964. __decorate([
  29965. BABYLON.serializeAsFresnelParameters()
  29966. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29967. __decorate([
  29968. BABYLON.serializeAsFresnelParameters()
  29969. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29970. __decorate([
  29971. BABYLON.serializeAsFresnelParameters()
  29972. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29973. __decorate([
  29974. BABYLON.serializeAsFresnelParameters()
  29975. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29976. __decorate([
  29977. BABYLON.serialize()
  29978. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29979. __decorate([
  29980. BABYLON.serialize()
  29981. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29982. __decorate([
  29983. BABYLON.serialize()
  29984. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29985. __decorate([
  29986. BABYLON.serialize()
  29987. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29988. __decorate([
  29989. BABYLON.serializeAsTexture()
  29990. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  29991. __decorate([
  29992. BABYLON.serializeAsColorCurves()
  29993. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  29994. __decorate([
  29995. BABYLON.serialize()
  29996. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29997. BABYLON.StandardMaterial = StandardMaterial;
  29998. })(BABYLON || (BABYLON = {}));
  29999. //# sourceMappingURL=babylon.standardMaterial.js.map
  30000. var BABYLON;
  30001. (function (BABYLON) {
  30002. var MultiMaterial = (function (_super) {
  30003. __extends(MultiMaterial, _super);
  30004. function MultiMaterial(name, scene) {
  30005. var _this = _super.call(this, name, scene, true) || this;
  30006. _this.subMaterials = new Array();
  30007. scene.multiMaterials.push(_this);
  30008. return _this;
  30009. }
  30010. // Properties
  30011. MultiMaterial.prototype.getSubMaterial = function (index) {
  30012. if (index < 0 || index >= this.subMaterials.length) {
  30013. return this.getScene().defaultMaterial;
  30014. }
  30015. return this.subMaterials[index];
  30016. };
  30017. // Methods
  30018. MultiMaterial.prototype.getClassName = function () {
  30019. return "MultiMaterial";
  30020. };
  30021. MultiMaterial.prototype.isReady = function (mesh) {
  30022. for (var index = 0; index < this.subMaterials.length; index++) {
  30023. var subMaterial = this.subMaterials[index];
  30024. if (subMaterial) {
  30025. if (!this.subMaterials[index].isReady(mesh)) {
  30026. return false;
  30027. }
  30028. }
  30029. }
  30030. return true;
  30031. };
  30032. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30033. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30034. for (var index = 0; index < this.subMaterials.length; index++) {
  30035. var subMaterial = null;
  30036. if (cloneChildren) {
  30037. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30038. }
  30039. else {
  30040. subMaterial = this.subMaterials[index];
  30041. }
  30042. newMultiMaterial.subMaterials.push(subMaterial);
  30043. }
  30044. return newMultiMaterial;
  30045. };
  30046. MultiMaterial.prototype.serialize = function () {
  30047. var serializationObject = {};
  30048. serializationObject.name = this.name;
  30049. serializationObject.id = this.id;
  30050. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30051. serializationObject.materials = [];
  30052. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30053. var subMat = this.subMaterials[matIndex];
  30054. if (subMat) {
  30055. serializationObject.materials.push(subMat.id);
  30056. }
  30057. else {
  30058. serializationObject.materials.push(null);
  30059. }
  30060. }
  30061. return serializationObject;
  30062. };
  30063. return MultiMaterial;
  30064. }(BABYLON.Material));
  30065. BABYLON.MultiMaterial = MultiMaterial;
  30066. })(BABYLON || (BABYLON = {}));
  30067. //# sourceMappingURL=babylon.multiMaterial.js.map
  30068. var BABYLON;
  30069. (function (BABYLON) {
  30070. var SceneLoader = (function () {
  30071. function SceneLoader() {
  30072. }
  30073. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30074. get: function () {
  30075. return 0;
  30076. },
  30077. enumerable: true,
  30078. configurable: true
  30079. });
  30080. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30081. get: function () {
  30082. return 1;
  30083. },
  30084. enumerable: true,
  30085. configurable: true
  30086. });
  30087. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30088. get: function () {
  30089. return 2;
  30090. },
  30091. enumerable: true,
  30092. configurable: true
  30093. });
  30094. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30095. get: function () {
  30096. return 3;
  30097. },
  30098. enumerable: true,
  30099. configurable: true
  30100. });
  30101. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30102. get: function () {
  30103. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30104. },
  30105. set: function (value) {
  30106. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30107. },
  30108. enumerable: true,
  30109. configurable: true
  30110. });
  30111. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30112. get: function () {
  30113. return SceneLoader._ShowLoadingScreen;
  30114. },
  30115. set: function (value) {
  30116. SceneLoader._ShowLoadingScreen = value;
  30117. },
  30118. enumerable: true,
  30119. configurable: true
  30120. });
  30121. Object.defineProperty(SceneLoader, "loggingLevel", {
  30122. get: function () {
  30123. return SceneLoader._loggingLevel;
  30124. },
  30125. set: function (value) {
  30126. SceneLoader._loggingLevel = value;
  30127. },
  30128. enumerable: true,
  30129. configurable: true
  30130. });
  30131. SceneLoader._getDefaultPlugin = function () {
  30132. return SceneLoader._registeredPlugins[".babylon"];
  30133. };
  30134. SceneLoader._getPluginForExtension = function (extension) {
  30135. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30136. if (registeredPlugin) {
  30137. return registeredPlugin;
  30138. }
  30139. return SceneLoader._getDefaultPlugin();
  30140. };
  30141. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30142. if (sceneFilename.name) {
  30143. sceneFilename = sceneFilename.name;
  30144. }
  30145. var dotPosition = sceneFilename.lastIndexOf(".");
  30146. var queryStringPosition = sceneFilename.indexOf("?");
  30147. if (queryStringPosition === -1) {
  30148. queryStringPosition = sceneFilename.length;
  30149. }
  30150. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30151. return SceneLoader._getPluginForExtension(extension);
  30152. };
  30153. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30154. SceneLoader._getDirectLoad = function (sceneFilename) {
  30155. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30156. return sceneFilename.substr(5);
  30157. }
  30158. return null;
  30159. };
  30160. // Public functions
  30161. SceneLoader.GetPluginForExtension = function (extension) {
  30162. return SceneLoader._getPluginForExtension(extension).plugin;
  30163. };
  30164. SceneLoader.RegisterPlugin = function (plugin) {
  30165. if (typeof plugin.extensions === "string") {
  30166. var extension = plugin.extensions;
  30167. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30168. plugin: plugin,
  30169. isBinary: false
  30170. };
  30171. }
  30172. else {
  30173. var extensions = plugin.extensions;
  30174. Object.keys(extensions).forEach(function (extension) {
  30175. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30176. plugin: plugin,
  30177. isBinary: extensions[extension].isBinary
  30178. };
  30179. });
  30180. }
  30181. };
  30182. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30183. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30184. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30185. return;
  30186. }
  30187. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30188. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30189. return;
  30190. }
  30191. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30192. var loadingToken = {};
  30193. scene._addPendingData(loadingToken);
  30194. var manifestChecked = function (success) {
  30195. scene.database = database;
  30196. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30197. var plugin = registeredPlugin.plugin;
  30198. var useArrayBuffer = registeredPlugin.isBinary;
  30199. var importMeshFromData = function (data) {
  30200. var meshes = [];
  30201. var particleSystems = [];
  30202. var skeletons = [];
  30203. try {
  30204. if (plugin.importMesh) {
  30205. var syncedPlugin = plugin;
  30206. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  30207. if (onerror) {
  30208. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30209. }
  30210. scene._removePendingData(loadingToken);
  30211. return;
  30212. }
  30213. if (onsuccess) {
  30214. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30215. onsuccess(meshes, particleSystems, skeletons);
  30216. scene._removePendingData(loadingToken);
  30217. }
  30218. }
  30219. else {
  30220. var asyncedPlugin = plugin;
  30221. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  30222. if (onsuccess) {
  30223. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30224. onsuccess(meshes, particleSystems, skeletons);
  30225. scene._removePendingData(loadingToken);
  30226. }
  30227. }, function () {
  30228. if (onerror) {
  30229. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30230. }
  30231. scene._removePendingData(loadingToken);
  30232. });
  30233. }
  30234. }
  30235. catch (e) {
  30236. if (onerror) {
  30237. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  30238. }
  30239. scene._removePendingData(loadingToken);
  30240. }
  30241. };
  30242. if (directLoad) {
  30243. importMeshFromData(directLoad);
  30244. return;
  30245. }
  30246. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  30247. importMeshFromData(data);
  30248. }, progressCallBack, database, useArrayBuffer);
  30249. };
  30250. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  30251. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30252. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30253. }
  30254. else {
  30255. // If the scene is a data stream or offline support is not enabled, it's a direct load
  30256. manifestChecked(true);
  30257. }
  30258. };
  30259. /**
  30260. * Load a scene
  30261. * @param rootUrl a string that defines the root url for scene and resources
  30262. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30263. * @param engine is the instance of BABYLON.Engine to use to create the scene
  30264. */
  30265. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  30266. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  30267. };
  30268. /**
  30269. * Append a scene
  30270. * @param rootUrl a string that defines the root url for scene and resources
  30271. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30272. * @param scene is the instance of BABYLON.Scene to append to
  30273. */
  30274. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30275. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30276. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30277. return;
  30278. }
  30279. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30280. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30281. var plugin = registeredPlugin.plugin;
  30282. var useArrayBuffer = registeredPlugin.isBinary;
  30283. var database;
  30284. var loadingToken = {};
  30285. scene._addPendingData(loadingToken);
  30286. if (SceneLoader.ShowLoadingScreen) {
  30287. scene.getEngine().displayLoadingUI();
  30288. }
  30289. var loadSceneFromData = function (data) {
  30290. scene.database = database;
  30291. if (plugin.load) {
  30292. var syncedPlugin = plugin;
  30293. if (!syncedPlugin.load(scene, data, rootUrl)) {
  30294. if (onerror) {
  30295. onerror(scene);
  30296. }
  30297. scene._removePendingData(loadingToken);
  30298. scene.getEngine().hideLoadingUI();
  30299. return;
  30300. }
  30301. if (onsuccess) {
  30302. onsuccess(scene);
  30303. }
  30304. scene._removePendingData(loadingToken);
  30305. }
  30306. else {
  30307. var asyncedPlugin = plugin;
  30308. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  30309. if (onsuccess) {
  30310. onsuccess(scene);
  30311. }
  30312. scene._removePendingData(loadingToken);
  30313. }, function () {
  30314. if (onerror) {
  30315. onerror(scene);
  30316. }
  30317. scene._removePendingData(loadingToken);
  30318. scene.getEngine().hideLoadingUI();
  30319. });
  30320. }
  30321. if (SceneLoader.ShowLoadingScreen) {
  30322. scene.executeWhenReady(function () {
  30323. scene.getEngine().hideLoadingUI();
  30324. });
  30325. }
  30326. };
  30327. var manifestChecked = function (success) {
  30328. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  30329. };
  30330. if (directLoad) {
  30331. loadSceneFromData(directLoad);
  30332. return;
  30333. }
  30334. if (rootUrl.indexOf("file:") === -1) {
  30335. if (scene.getEngine().enableOfflineSupport) {
  30336. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30337. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30338. }
  30339. else {
  30340. manifestChecked(true);
  30341. }
  30342. }
  30343. else {
  30344. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  30345. }
  30346. };
  30347. return SceneLoader;
  30348. }());
  30349. // Flags
  30350. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  30351. SceneLoader._ShowLoadingScreen = true;
  30352. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  30353. // Members
  30354. SceneLoader._registeredPlugins = {};
  30355. BABYLON.SceneLoader = SceneLoader;
  30356. ;
  30357. })(BABYLON || (BABYLON = {}));
  30358. //# sourceMappingURL=babylon.sceneLoader.js.map
  30359. var BABYLON;
  30360. (function (BABYLON) {
  30361. var Internals;
  30362. (function (Internals) {
  30363. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  30364. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30365. var parsedMaterial = parsedData.materials[index];
  30366. if (parsedMaterial.id === id) {
  30367. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30368. }
  30369. }
  30370. return null;
  30371. };
  30372. var isDescendantOf = function (mesh, names, hierarchyIds) {
  30373. names = (names instanceof Array) ? names : [names];
  30374. for (var i in names) {
  30375. if (mesh.name === names[i]) {
  30376. hierarchyIds.push(mesh.id);
  30377. return true;
  30378. }
  30379. }
  30380. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  30381. hierarchyIds.push(mesh.id);
  30382. return true;
  30383. }
  30384. return false;
  30385. };
  30386. var logOperation = function (operation, producer) {
  30387. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  30388. };
  30389. BABYLON.SceneLoader.RegisterPlugin({
  30390. extensions: ".babylon",
  30391. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  30392. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30393. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30394. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30395. // and avoid problems with multiple concurrent .babylon loads.
  30396. var log = "importMesh has failed JSON parse";
  30397. try {
  30398. var parsedData = JSON.parse(data);
  30399. log = "";
  30400. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30401. var loadedSkeletonsIds = [];
  30402. var loadedMaterialsIds = [];
  30403. var hierarchyIds = [];
  30404. var index;
  30405. var cache;
  30406. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30407. var parsedMesh = parsedData.meshes[index];
  30408. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  30409. if (meshesNames instanceof Array) {
  30410. // Remove found mesh name from list.
  30411. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  30412. }
  30413. //Geometry?
  30414. if (parsedMesh.geometryId) {
  30415. //does the file contain geometries?
  30416. if (parsedData.geometries) {
  30417. //find the correct geometry and add it to the scene
  30418. var found = false;
  30419. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  30420. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  30421. return;
  30422. }
  30423. else {
  30424. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  30425. if (parsedGeometryData.id === parsedMesh.geometryId) {
  30426. switch (geometryType) {
  30427. case "boxes":
  30428. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  30429. break;
  30430. case "spheres":
  30431. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  30432. break;
  30433. case "cylinders":
  30434. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  30435. break;
  30436. case "toruses":
  30437. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  30438. break;
  30439. case "grounds":
  30440. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  30441. break;
  30442. case "planes":
  30443. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  30444. break;
  30445. case "torusKnots":
  30446. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  30447. break;
  30448. case "vertexData":
  30449. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  30450. break;
  30451. }
  30452. found = true;
  30453. }
  30454. });
  30455. }
  30456. });
  30457. if (!found) {
  30458. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  30459. }
  30460. }
  30461. }
  30462. // Material ?
  30463. if (parsedMesh.materialId) {
  30464. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  30465. if (!materialFound && parsedData.multiMaterials) {
  30466. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  30467. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  30468. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  30469. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  30470. var subMatId = parsedMultiMaterial.materials[matIndex];
  30471. loadedMaterialsIds.push(subMatId);
  30472. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  30473. log += "\n\tMaterial " + mat.toString(fullDetails);
  30474. }
  30475. loadedMaterialsIds.push(parsedMultiMaterial.id);
  30476. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30477. materialFound = true;
  30478. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  30479. break;
  30480. }
  30481. }
  30482. }
  30483. if (!materialFound) {
  30484. loadedMaterialsIds.push(parsedMesh.materialId);
  30485. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  30486. if (!mat) {
  30487. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  30488. }
  30489. else {
  30490. log += "\n\tMaterial " + mat.toString(fullDetails);
  30491. }
  30492. }
  30493. }
  30494. // Skeleton ?
  30495. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  30496. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  30497. if (!skeletonAlreadyLoaded) {
  30498. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  30499. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  30500. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  30501. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30502. skeletons.push(skeleton);
  30503. loadedSkeletonsIds.push(parsedSkeleton.id);
  30504. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  30505. }
  30506. }
  30507. }
  30508. }
  30509. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30510. meshes.push(mesh);
  30511. log += "\n\tMesh " + mesh.toString(fullDetails);
  30512. }
  30513. }
  30514. // Connecting parents
  30515. var currentMesh;
  30516. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30517. currentMesh = scene.meshes[index];
  30518. if (currentMesh._waitingParentId) {
  30519. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  30520. currentMesh._waitingParentId = undefined;
  30521. }
  30522. }
  30523. // freeze and compute world matrix application
  30524. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30525. currentMesh = scene.meshes[index];
  30526. if (currentMesh._waitingFreezeWorldMatrix) {
  30527. currentMesh.freezeWorldMatrix();
  30528. currentMesh._waitingFreezeWorldMatrix = undefined;
  30529. }
  30530. else {
  30531. currentMesh.computeWorldMatrix(true);
  30532. }
  30533. }
  30534. // Particles
  30535. if (parsedData.particleSystems) {
  30536. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30537. var parsedParticleSystem = parsedData.particleSystems[index];
  30538. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  30539. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  30540. }
  30541. }
  30542. }
  30543. return true;
  30544. }
  30545. catch (err) {
  30546. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  30547. log = null;
  30548. throw err;
  30549. }
  30550. finally {
  30551. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30552. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30553. }
  30554. }
  30555. },
  30556. load: function (scene, data, rootUrl) {
  30557. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30558. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30559. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30560. // and avoid problems with multiple concurrent .babylon loads.
  30561. var log = "importScene has failed JSON parse";
  30562. try {
  30563. var parsedData = JSON.parse(data);
  30564. log = "";
  30565. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30566. // Scene
  30567. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  30568. scene.autoClear = parsedData.autoClear;
  30569. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  30570. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  30571. if (parsedData.gravity) {
  30572. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  30573. }
  30574. // Fog
  30575. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  30576. scene.fogMode = parsedData.fogMode;
  30577. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  30578. scene.fogStart = parsedData.fogStart;
  30579. scene.fogEnd = parsedData.fogEnd;
  30580. scene.fogDensity = parsedData.fogDensity;
  30581. log += "\tFog mode for scene: ";
  30582. switch (scene.fogMode) {
  30583. // getters not compiling, so using hardcoded
  30584. case 1:
  30585. log += "exp\n";
  30586. break;
  30587. case 2:
  30588. log += "exp2\n";
  30589. break;
  30590. case 3:
  30591. log += "linear\n";
  30592. break;
  30593. }
  30594. }
  30595. //Physics
  30596. if (parsedData.physicsEnabled) {
  30597. var physicsPlugin;
  30598. if (parsedData.physicsEngine === "cannon") {
  30599. physicsPlugin = new BABYLON.CannonJSPlugin();
  30600. }
  30601. else if (parsedData.physicsEngine === "oimo") {
  30602. physicsPlugin = new BABYLON.OimoJSPlugin();
  30603. }
  30604. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  30605. //else - default engine, which is currently oimo
  30606. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  30607. scene.enablePhysics(physicsGravity, physicsPlugin);
  30608. }
  30609. // Metadata
  30610. if (parsedData.metadata !== undefined) {
  30611. scene.metadata = parsedData.metadata;
  30612. }
  30613. //collisions, if defined. otherwise, default is true
  30614. if (parsedData.collisionsEnabled != undefined) {
  30615. scene.collisionsEnabled = parsedData.collisionsEnabled;
  30616. }
  30617. scene.workerCollisions = !!parsedData.workerCollisions;
  30618. var index;
  30619. var cache;
  30620. // Lights
  30621. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  30622. var parsedLight = parsedData.lights[index];
  30623. var light = BABYLON.Light.Parse(parsedLight, scene);
  30624. log += (index === 0 ? "\n\tLights:" : "");
  30625. log += "\n\t\t" + light.toString(fullDetails);
  30626. }
  30627. // Animations
  30628. if (parsedData.animations) {
  30629. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  30630. var parsedAnimation = parsedData.animations[index];
  30631. var animation = BABYLON.Animation.Parse(parsedAnimation);
  30632. scene.animations.push(animation);
  30633. log += (index === 0 ? "\n\tAnimations:" : "");
  30634. log += "\n\t\t" + animation.toString(fullDetails);
  30635. }
  30636. }
  30637. if (parsedData.autoAnimate) {
  30638. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  30639. }
  30640. // Materials
  30641. if (parsedData.materials) {
  30642. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30643. var parsedMaterial = parsedData.materials[index];
  30644. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30645. log += (index === 0 ? "\n\tMaterials:" : "");
  30646. log += "\n\t\t" + mat.toString(fullDetails);
  30647. }
  30648. }
  30649. if (parsedData.multiMaterials) {
  30650. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  30651. var parsedMultiMaterial = parsedData.multiMaterials[index];
  30652. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30653. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  30654. log += "\n\t\t" + mmat.toString(fullDetails);
  30655. }
  30656. }
  30657. // Skeletons
  30658. if (parsedData.skeletons) {
  30659. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  30660. var parsedSkeleton = parsedData.skeletons[index];
  30661. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30662. log += (index === 0 ? "\n\tSkeletons:" : "");
  30663. log += "\n\t\t" + skeleton.toString(fullDetails);
  30664. }
  30665. }
  30666. // Geometries
  30667. var geometries = parsedData.geometries;
  30668. if (geometries) {
  30669. // Boxes
  30670. var boxes = geometries.boxes;
  30671. if (boxes) {
  30672. for (index = 0, cache = boxes.length; index < cache; index++) {
  30673. var parsedBox = boxes[index];
  30674. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  30675. }
  30676. }
  30677. // Spheres
  30678. var spheres = geometries.spheres;
  30679. if (spheres) {
  30680. for (index = 0, cache = spheres.length; index < cache; index++) {
  30681. var parsedSphere = spheres[index];
  30682. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  30683. }
  30684. }
  30685. // Cylinders
  30686. var cylinders = geometries.cylinders;
  30687. if (cylinders) {
  30688. for (index = 0, cache = cylinders.length; index < cache; index++) {
  30689. var parsedCylinder = cylinders[index];
  30690. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  30691. }
  30692. }
  30693. // Toruses
  30694. var toruses = geometries.toruses;
  30695. if (toruses) {
  30696. for (index = 0, cache = toruses.length; index < cache; index++) {
  30697. var parsedTorus = toruses[index];
  30698. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  30699. }
  30700. }
  30701. // Grounds
  30702. var grounds = geometries.grounds;
  30703. if (grounds) {
  30704. for (index = 0, cache = grounds.length; index < cache; index++) {
  30705. var parsedGround = grounds[index];
  30706. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  30707. }
  30708. }
  30709. // Planes
  30710. var planes = geometries.planes;
  30711. if (planes) {
  30712. for (index = 0, cache = planes.length; index < cache; index++) {
  30713. var parsedPlane = planes[index];
  30714. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  30715. }
  30716. }
  30717. // TorusKnots
  30718. var torusKnots = geometries.torusKnots;
  30719. if (torusKnots) {
  30720. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  30721. var parsedTorusKnot = torusKnots[index];
  30722. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  30723. }
  30724. }
  30725. // VertexData
  30726. var vertexData = geometries.vertexData;
  30727. if (vertexData) {
  30728. for (index = 0, cache = vertexData.length; index < cache; index++) {
  30729. var parsedVertexData = vertexData[index];
  30730. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  30731. }
  30732. }
  30733. }
  30734. // Meshes
  30735. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30736. var parsedMesh = parsedData.meshes[index];
  30737. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30738. log += (index === 0 ? "\n\tMeshes:" : "");
  30739. log += "\n\t\t" + mesh.toString(fullDetails);
  30740. }
  30741. // Cameras
  30742. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  30743. var parsedCamera = parsedData.cameras[index];
  30744. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  30745. log += (index === 0 ? "\n\tCameras:" : "");
  30746. log += "\n\t\t" + camera.toString(fullDetails);
  30747. }
  30748. if (parsedData.activeCameraID) {
  30749. scene.setActiveCameraByID(parsedData.activeCameraID);
  30750. }
  30751. // Browsing all the graph to connect the dots
  30752. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  30753. var camera = scene.cameras[index];
  30754. if (camera._waitingParentId) {
  30755. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  30756. camera._waitingParentId = undefined;
  30757. }
  30758. }
  30759. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  30760. var light = scene.lights[index];
  30761. if (light._waitingParentId) {
  30762. light.parent = scene.getLastEntryByID(light._waitingParentId);
  30763. light._waitingParentId = undefined;
  30764. }
  30765. }
  30766. // Sounds
  30767. var loadedSounds = [];
  30768. var loadedSound;
  30769. if (BABYLON.AudioEngine && parsedData.sounds) {
  30770. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  30771. var parsedSound = parsedData.sounds[index];
  30772. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30773. if (!parsedSound.url)
  30774. parsedSound.url = parsedSound.name;
  30775. if (!loadedSounds[parsedSound.url]) {
  30776. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  30777. loadedSounds[parsedSound.url] = loadedSound;
  30778. }
  30779. else {
  30780. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  30781. }
  30782. }
  30783. else {
  30784. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  30785. }
  30786. }
  30787. }
  30788. loadedSounds = [];
  30789. // Connect parents & children and parse actions
  30790. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30791. var mesh = scene.meshes[index];
  30792. if (mesh._waitingParentId) {
  30793. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  30794. mesh._waitingParentId = undefined;
  30795. }
  30796. if (mesh._waitingActions) {
  30797. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  30798. mesh._waitingActions = undefined;
  30799. }
  30800. }
  30801. // freeze world matrix application
  30802. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30803. var currentMesh = scene.meshes[index];
  30804. if (currentMesh._waitingFreezeWorldMatrix) {
  30805. currentMesh.freezeWorldMatrix();
  30806. currentMesh._waitingFreezeWorldMatrix = undefined;
  30807. }
  30808. else {
  30809. currentMesh.computeWorldMatrix(true);
  30810. }
  30811. }
  30812. // Particles Systems
  30813. if (parsedData.particleSystems) {
  30814. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30815. var parsedParticleSystem = parsedData.particleSystems[index];
  30816. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  30817. }
  30818. }
  30819. // Lens flares
  30820. if (parsedData.lensFlareSystems) {
  30821. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  30822. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  30823. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  30824. }
  30825. }
  30826. // Shadows
  30827. if (parsedData.shadowGenerators) {
  30828. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  30829. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  30830. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  30831. }
  30832. }
  30833. // Actions (scene)
  30834. if (parsedData.actions) {
  30835. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  30836. }
  30837. // Finish
  30838. return true;
  30839. }
  30840. catch (err) {
  30841. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  30842. log = null;
  30843. throw err;
  30844. }
  30845. finally {
  30846. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30847. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30848. }
  30849. }
  30850. }
  30851. });
  30852. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30853. })(BABYLON || (BABYLON = {}));
  30854. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  30855. var BABYLON;
  30856. (function (BABYLON) {
  30857. var SpriteManager = (function () {
  30858. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  30859. if (epsilon === void 0) { epsilon = 0.01; }
  30860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30861. this.name = name;
  30862. this.sprites = new Array();
  30863. this.renderingGroupId = 0;
  30864. this.layerMask = 0x0FFFFFFF;
  30865. this.fogEnabled = true;
  30866. this.isPickable = false;
  30867. /**
  30868. * An event triggered when the manager is disposed.
  30869. * @type {BABYLON.Observable}
  30870. */
  30871. this.onDisposeObservable = new BABYLON.Observable();
  30872. this._vertexBuffers = {};
  30873. this._capacity = capacity;
  30874. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  30875. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30876. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30877. if (cellSize.width && cellSize.height) {
  30878. this.cellWidth = cellSize.width;
  30879. this.cellHeight = cellSize.height;
  30880. }
  30881. else if (cellSize !== undefined) {
  30882. this.cellWidth = cellSize;
  30883. this.cellHeight = cellSize;
  30884. }
  30885. else {
  30886. return;
  30887. }
  30888. this._epsilon = epsilon;
  30889. this._scene = scene;
  30890. this._scene.spriteManagers.push(this);
  30891. var indices = [];
  30892. var index = 0;
  30893. for (var count = 0; count < capacity; count++) {
  30894. indices.push(index);
  30895. indices.push(index + 1);
  30896. indices.push(index + 2);
  30897. indices.push(index);
  30898. indices.push(index + 2);
  30899. indices.push(index + 3);
  30900. index += 4;
  30901. }
  30902. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  30903. // VBO
  30904. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  30905. this._vertexData = new Float32Array(capacity * 16 * 4);
  30906. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  30907. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  30908. var options = this._buffer.createVertexBuffer("options", 4, 4);
  30909. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  30910. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  30911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  30912. this._vertexBuffers["options"] = options;
  30913. this._vertexBuffers["cellInfo"] = cellInfo;
  30914. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  30915. // Effects
  30916. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  30917. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  30918. }
  30919. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  30920. set: function (callback) {
  30921. if (this._onDisposeObserver) {
  30922. this.onDisposeObservable.remove(this._onDisposeObserver);
  30923. }
  30924. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(SpriteManager.prototype, "texture", {
  30930. get: function () {
  30931. return this._spriteTexture;
  30932. },
  30933. set: function (value) {
  30934. this._spriteTexture = value;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  30940. var arrayOffset = index * 16;
  30941. if (offsetX === 0)
  30942. offsetX = this._epsilon;
  30943. else if (offsetX === 1)
  30944. offsetX = 1 - this._epsilon;
  30945. if (offsetY === 0)
  30946. offsetY = this._epsilon;
  30947. else if (offsetY === 1)
  30948. offsetY = 1 - this._epsilon;
  30949. this._vertexData[arrayOffset] = sprite.position.x;
  30950. this._vertexData[arrayOffset + 1] = sprite.position.y;
  30951. this._vertexData[arrayOffset + 2] = sprite.position.z;
  30952. this._vertexData[arrayOffset + 3] = sprite.angle;
  30953. this._vertexData[arrayOffset + 4] = sprite.width;
  30954. this._vertexData[arrayOffset + 5] = sprite.height;
  30955. this._vertexData[arrayOffset + 6] = offsetX;
  30956. this._vertexData[arrayOffset + 7] = offsetY;
  30957. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  30958. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  30959. var offset = (sprite.cellIndex / rowSize) >> 0;
  30960. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  30961. this._vertexData[arrayOffset + 11] = offset;
  30962. // Color
  30963. this._vertexData[arrayOffset + 12] = sprite.color.r;
  30964. this._vertexData[arrayOffset + 13] = sprite.color.g;
  30965. this._vertexData[arrayOffset + 14] = sprite.color.b;
  30966. this._vertexData[arrayOffset + 15] = sprite.color.a;
  30967. };
  30968. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  30969. var count = Math.min(this._capacity, this.sprites.length);
  30970. var min = BABYLON.Vector3.Zero();
  30971. var max = BABYLON.Vector3.Zero();
  30972. var distance = Number.MAX_VALUE;
  30973. var currentSprite;
  30974. var cameraSpacePosition = BABYLON.Vector3.Zero();
  30975. var cameraView = camera.getViewMatrix();
  30976. for (var index = 0; index < count; index++) {
  30977. var sprite = this.sprites[index];
  30978. if (!sprite) {
  30979. continue;
  30980. }
  30981. if (predicate) {
  30982. if (!predicate(sprite)) {
  30983. continue;
  30984. }
  30985. }
  30986. else if (!sprite.isPickable) {
  30987. continue;
  30988. }
  30989. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  30990. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  30991. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  30992. if (ray.intersectsBoxMinMax(min, max)) {
  30993. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  30994. if (distance > currentDistance) {
  30995. distance = currentDistance;
  30996. currentSprite = sprite;
  30997. if (fastCheck) {
  30998. break;
  30999. }
  31000. }
  31001. }
  31002. }
  31003. if (currentSprite) {
  31004. var result = new BABYLON.PickingInfo();
  31005. result.hit = true;
  31006. result.pickedSprite = currentSprite;
  31007. result.distance = distance;
  31008. return result;
  31009. }
  31010. return null;
  31011. };
  31012. SpriteManager.prototype.render = function () {
  31013. // Check
  31014. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31015. return;
  31016. var engine = this._scene.getEngine();
  31017. var baseSize = this._spriteTexture.getBaseSize();
  31018. // Sprites
  31019. var deltaTime = engine.getDeltaTime();
  31020. var max = Math.min(this._capacity, this.sprites.length);
  31021. var rowSize = baseSize.width / this.cellWidth;
  31022. var offset = 0;
  31023. for (var index = 0; index < max; index++) {
  31024. var sprite = this.sprites[index];
  31025. if (!sprite) {
  31026. continue;
  31027. }
  31028. sprite._animate(deltaTime);
  31029. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31030. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31031. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31032. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31033. }
  31034. this._buffer.update(this._vertexData);
  31035. // Render
  31036. var effect = this._effectBase;
  31037. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31038. effect = this._effectFog;
  31039. }
  31040. engine.enableEffect(effect);
  31041. var viewMatrix = this._scene.getViewMatrix();
  31042. effect.setTexture("diffuseSampler", this._spriteTexture);
  31043. effect.setMatrix("view", viewMatrix);
  31044. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31045. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31046. // Fog
  31047. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31048. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31049. effect.setColor3("vFogColor", this._scene.fogColor);
  31050. }
  31051. // VBOs
  31052. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31053. // Draw order
  31054. engine.setDepthFunctionToLessOrEqual();
  31055. effect.setBool("alphaTest", true);
  31056. engine.setColorWrite(false);
  31057. engine.draw(true, 0, max * 6);
  31058. engine.setColorWrite(true);
  31059. effect.setBool("alphaTest", false);
  31060. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31061. engine.draw(true, 0, max * 6);
  31062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31063. };
  31064. SpriteManager.prototype.dispose = function () {
  31065. if (this._buffer) {
  31066. this._buffer.dispose();
  31067. this._buffer = null;
  31068. }
  31069. if (this._indexBuffer) {
  31070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31071. this._indexBuffer = null;
  31072. }
  31073. if (this._spriteTexture) {
  31074. this._spriteTexture.dispose();
  31075. this._spriteTexture = null;
  31076. }
  31077. // Remove from scene
  31078. var index = this._scene.spriteManagers.indexOf(this);
  31079. this._scene.spriteManagers.splice(index, 1);
  31080. // Callback
  31081. this.onDisposeObservable.notifyObservers(this);
  31082. this.onDisposeObservable.clear();
  31083. };
  31084. return SpriteManager;
  31085. }());
  31086. BABYLON.SpriteManager = SpriteManager;
  31087. })(BABYLON || (BABYLON = {}));
  31088. //# sourceMappingURL=babylon.spriteManager.js.map
  31089. var BABYLON;
  31090. (function (BABYLON) {
  31091. var Sprite = (function () {
  31092. function Sprite(name, manager) {
  31093. this.name = name;
  31094. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31095. this.width = 1.0;
  31096. this.height = 1.0;
  31097. this.angle = 0;
  31098. this.cellIndex = 0;
  31099. this.invertU = 0;
  31100. this.invertV = 0;
  31101. this.animations = new Array();
  31102. this.isPickable = false;
  31103. this._animationStarted = false;
  31104. this._loopAnimation = false;
  31105. this._fromIndex = 0;
  31106. this._toIndex = 0;
  31107. this._delay = 0;
  31108. this._direction = 1;
  31109. this._frameCount = 0;
  31110. this._time = 0;
  31111. this._manager = manager;
  31112. this._manager.sprites.push(this);
  31113. this.position = BABYLON.Vector3.Zero();
  31114. }
  31115. Object.defineProperty(Sprite.prototype, "size", {
  31116. get: function () {
  31117. return this.width;
  31118. },
  31119. set: function (value) {
  31120. this.width = value;
  31121. this.height = value;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31127. this._fromIndex = from;
  31128. this._toIndex = to;
  31129. this._loopAnimation = loop;
  31130. this._delay = delay;
  31131. this._animationStarted = true;
  31132. this._direction = from < to ? 1 : -1;
  31133. this.cellIndex = from;
  31134. this._time = 0;
  31135. this._onAnimationEnd = onAnimationEnd;
  31136. };
  31137. Sprite.prototype.stopAnimation = function () {
  31138. this._animationStarted = false;
  31139. };
  31140. Sprite.prototype._animate = function (deltaTime) {
  31141. if (!this._animationStarted)
  31142. return;
  31143. this._time += deltaTime;
  31144. if (this._time > this._delay) {
  31145. this._time = this._time % this._delay;
  31146. this.cellIndex += this._direction;
  31147. if (this.cellIndex === this._toIndex) {
  31148. if (this._loopAnimation) {
  31149. this.cellIndex = this._fromIndex;
  31150. }
  31151. else {
  31152. this._animationStarted = false;
  31153. if (this._onAnimationEnd) {
  31154. this._onAnimationEnd();
  31155. }
  31156. if (this.disposeWhenFinishedAnimating) {
  31157. this.dispose();
  31158. }
  31159. }
  31160. }
  31161. }
  31162. };
  31163. Sprite.prototype.dispose = function () {
  31164. for (var i = 0; i < this._manager.sprites.length; i++) {
  31165. if (this._manager.sprites[i] == this) {
  31166. this._manager.sprites.splice(i, 1);
  31167. }
  31168. }
  31169. };
  31170. return Sprite;
  31171. }());
  31172. BABYLON.Sprite = Sprite;
  31173. })(BABYLON || (BABYLON = {}));
  31174. //# sourceMappingURL=babylon.sprite.js.map
  31175. var BABYLON;
  31176. (function (BABYLON) {
  31177. var Layer = (function () {
  31178. function Layer(name, imgUrl, scene, isBackground, color) {
  31179. this.name = name;
  31180. this.scale = new BABYLON.Vector2(1, 1);
  31181. this.offset = new BABYLON.Vector2(0, 0);
  31182. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31183. this._vertexBuffers = {};
  31184. // Events
  31185. /**
  31186. * An event triggered when the layer is disposed.
  31187. * @type {BABYLON.Observable}
  31188. */
  31189. this.onDisposeObservable = new BABYLON.Observable();
  31190. /**
  31191. * An event triggered before rendering the scene
  31192. * @type {BABYLON.Observable}
  31193. */
  31194. this.onBeforeRenderObservable = new BABYLON.Observable();
  31195. /**
  31196. * An event triggered after rendering the scene
  31197. * @type {BABYLON.Observable}
  31198. */
  31199. this.onAfterRenderObservable = new BABYLON.Observable();
  31200. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  31201. this.isBackground = isBackground === undefined ? true : isBackground;
  31202. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  31203. this._scene = scene;
  31204. this._scene.layers.push(this);
  31205. var engine = scene.getEngine();
  31206. // VBO
  31207. var vertices = [];
  31208. vertices.push(1, 1);
  31209. vertices.push(-1, 1);
  31210. vertices.push(-1, -1);
  31211. vertices.push(1, -1);
  31212. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31213. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  31214. // Indices
  31215. var indices = [];
  31216. indices.push(0);
  31217. indices.push(1);
  31218. indices.push(2);
  31219. indices.push(0);
  31220. indices.push(2);
  31221. indices.push(3);
  31222. this._indexBuffer = engine.createIndexBuffer(indices);
  31223. // Effects
  31224. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  31225. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  31226. }
  31227. Object.defineProperty(Layer.prototype, "onDispose", {
  31228. set: function (callback) {
  31229. if (this._onDisposeObserver) {
  31230. this.onDisposeObservable.remove(this._onDisposeObserver);
  31231. }
  31232. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  31238. set: function (callback) {
  31239. if (this._onBeforeRenderObserver) {
  31240. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31241. }
  31242. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31243. },
  31244. enumerable: true,
  31245. configurable: true
  31246. });
  31247. Object.defineProperty(Layer.prototype, "onAfterRender", {
  31248. set: function (callback) {
  31249. if (this._onAfterRenderObserver) {
  31250. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31251. }
  31252. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31253. },
  31254. enumerable: true,
  31255. configurable: true
  31256. });
  31257. Layer.prototype.render = function () {
  31258. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  31259. // Check
  31260. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  31261. return;
  31262. var engine = this._scene.getEngine();
  31263. this.onBeforeRenderObservable.notifyObservers(this);
  31264. // Render
  31265. engine.enableEffect(currentEffect);
  31266. engine.setState(false);
  31267. // Texture
  31268. currentEffect.setTexture("textureSampler", this.texture);
  31269. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  31270. // Color
  31271. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  31272. // Scale / offset
  31273. currentEffect.setVector2("offset", this.offset);
  31274. currentEffect.setVector2("scale", this.scale);
  31275. // VBOs
  31276. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  31277. // Draw order
  31278. if (!this.alphaTest) {
  31279. engine.setAlphaMode(this.alphaBlendingMode);
  31280. engine.draw(true, 0, 6);
  31281. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31282. }
  31283. else {
  31284. engine.draw(true, 0, 6);
  31285. }
  31286. this.onAfterRenderObservable.notifyObservers(this);
  31287. };
  31288. Layer.prototype.dispose = function () {
  31289. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31290. if (vertexBuffer) {
  31291. vertexBuffer.dispose();
  31292. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31293. }
  31294. if (this._indexBuffer) {
  31295. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31296. this._indexBuffer = null;
  31297. }
  31298. if (this.texture) {
  31299. this.texture.dispose();
  31300. this.texture = null;
  31301. }
  31302. // Remove from scene
  31303. var index = this._scene.layers.indexOf(this);
  31304. this._scene.layers.splice(index, 1);
  31305. // Callback
  31306. this.onDisposeObservable.notifyObservers(this);
  31307. this.onDisposeObservable.clear();
  31308. this.onAfterRenderObservable.clear();
  31309. this.onBeforeRenderObservable.clear();
  31310. };
  31311. return Layer;
  31312. }());
  31313. BABYLON.Layer = Layer;
  31314. })(BABYLON || (BABYLON = {}));
  31315. //# sourceMappingURL=babylon.layer.js.map
  31316. var BABYLON;
  31317. (function (BABYLON) {
  31318. var Particle = (function () {
  31319. function Particle() {
  31320. this.position = BABYLON.Vector3.Zero();
  31321. this.direction = BABYLON.Vector3.Zero();
  31322. this.color = new BABYLON.Color4(0, 0, 0, 0);
  31323. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  31324. this.lifeTime = 1.0;
  31325. this.age = 0;
  31326. this.size = 0;
  31327. this.angle = 0;
  31328. this.angularSpeed = 0;
  31329. }
  31330. Particle.prototype.copyTo = function (other) {
  31331. other.position.copyFrom(this.position);
  31332. other.direction.copyFrom(this.direction);
  31333. other.color.copyFrom(this.color);
  31334. other.colorStep.copyFrom(this.colorStep);
  31335. other.lifeTime = this.lifeTime;
  31336. other.age = this.age;
  31337. other.size = this.size;
  31338. other.angle = this.angle;
  31339. other.angularSpeed = this.angularSpeed;
  31340. };
  31341. return Particle;
  31342. }());
  31343. BABYLON.Particle = Particle;
  31344. })(BABYLON || (BABYLON = {}));
  31345. //# sourceMappingURL=babylon.particle.js.map
  31346. var BABYLON;
  31347. (function (BABYLON) {
  31348. var randomNumber = function (min, max) {
  31349. if (min === max) {
  31350. return (min);
  31351. }
  31352. var random = Math.random();
  31353. return ((random * (max - min)) + min);
  31354. };
  31355. var ParticleSystem = (function () {
  31356. function ParticleSystem(name, capacity, scene, customEffect) {
  31357. var _this = this;
  31358. this.name = name;
  31359. // Members
  31360. this.animations = [];
  31361. this.renderingGroupId = 0;
  31362. this.emitter = null;
  31363. this.emitRate = 10;
  31364. this.manualEmitCount = -1;
  31365. this.updateSpeed = 0.01;
  31366. this.targetStopDuration = 0;
  31367. this.disposeOnStop = false;
  31368. this.minEmitPower = 1;
  31369. this.maxEmitPower = 1;
  31370. this.minLifeTime = 1;
  31371. this.maxLifeTime = 1;
  31372. this.minSize = 1;
  31373. this.maxSize = 1;
  31374. this.minAngularSpeed = 0;
  31375. this.maxAngularSpeed = 0;
  31376. this.layerMask = 0x0FFFFFFF;
  31377. this.customShader = null;
  31378. this.preventAutoStart = false;
  31379. /**
  31380. * An event triggered when the system is disposed.
  31381. * @type {BABYLON.Observable}
  31382. */
  31383. this.onDisposeObservable = new BABYLON.Observable();
  31384. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  31385. this.forceDepthWrite = false;
  31386. this.gravity = BABYLON.Vector3.Zero();
  31387. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  31388. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  31389. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  31390. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31391. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31392. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31393. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  31394. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31395. this.particles = new Array();
  31396. this._stockParticles = new Array();
  31397. this._newPartsExcess = 0;
  31398. this._vertexBuffers = {};
  31399. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  31400. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  31401. this._scaledDirection = BABYLON.Vector3.Zero();
  31402. this._scaledGravity = BABYLON.Vector3.Zero();
  31403. this._currentRenderId = -1;
  31404. this._started = false;
  31405. this._stopped = false;
  31406. this._actualFrame = 0;
  31407. this.id = name;
  31408. this._capacity = capacity;
  31409. this._scene = scene;
  31410. this._customEffect = customEffect;
  31411. scene.particleSystems.push(this);
  31412. var indices = [];
  31413. var index = 0;
  31414. for (var count = 0; count < capacity; count++) {
  31415. indices.push(index);
  31416. indices.push(index + 1);
  31417. indices.push(index + 2);
  31418. indices.push(index);
  31419. indices.push(index + 2);
  31420. indices.push(index + 3);
  31421. index += 4;
  31422. }
  31423. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31424. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  31425. this._vertexData = new Float32Array(capacity * 11 * 4);
  31426. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  31427. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  31428. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  31429. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  31430. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31431. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31432. this._vertexBuffers["options"] = options;
  31433. // Default behaviors
  31434. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  31435. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  31436. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  31437. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  31438. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  31439. };
  31440. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  31441. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  31442. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  31443. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  31444. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  31445. };
  31446. this.updateFunction = function (particles) {
  31447. for (var index = 0; index < particles.length; index++) {
  31448. var particle = particles[index];
  31449. particle.age += _this._scaledUpdateSpeed;
  31450. if (particle.age >= particle.lifeTime) {
  31451. _this.recycleParticle(particle);
  31452. index--;
  31453. continue;
  31454. }
  31455. else {
  31456. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  31457. particle.color.addInPlace(_this._scaledColorStep);
  31458. if (particle.color.a < 0)
  31459. particle.color.a = 0;
  31460. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  31461. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  31462. particle.position.addInPlace(_this._scaledDirection);
  31463. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  31464. particle.direction.addInPlace(_this._scaledGravity);
  31465. }
  31466. }
  31467. };
  31468. }
  31469. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  31470. set: function (callback) {
  31471. if (this._onDisposeObserver) {
  31472. this.onDisposeObservable.remove(this._onDisposeObserver);
  31473. }
  31474. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31475. },
  31476. enumerable: true,
  31477. configurable: true
  31478. });
  31479. ParticleSystem.prototype.recycleParticle = function (particle) {
  31480. var lastParticle = this.particles.pop();
  31481. if (lastParticle !== particle) {
  31482. lastParticle.copyTo(particle);
  31483. this._stockParticles.push(lastParticle);
  31484. }
  31485. };
  31486. ParticleSystem.prototype.getCapacity = function () {
  31487. return this._capacity;
  31488. };
  31489. ParticleSystem.prototype.isAlive = function () {
  31490. return this._alive;
  31491. };
  31492. ParticleSystem.prototype.isStarted = function () {
  31493. return this._started;
  31494. };
  31495. ParticleSystem.prototype.start = function () {
  31496. this._started = true;
  31497. this._stopped = false;
  31498. this._actualFrame = 0;
  31499. };
  31500. ParticleSystem.prototype.stop = function () {
  31501. this._stopped = true;
  31502. };
  31503. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  31504. var offset = index * 11;
  31505. this._vertexData[offset] = particle.position.x;
  31506. this._vertexData[offset + 1] = particle.position.y;
  31507. this._vertexData[offset + 2] = particle.position.z;
  31508. this._vertexData[offset + 3] = particle.color.r;
  31509. this._vertexData[offset + 4] = particle.color.g;
  31510. this._vertexData[offset + 5] = particle.color.b;
  31511. this._vertexData[offset + 6] = particle.color.a;
  31512. this._vertexData[offset + 7] = particle.angle;
  31513. this._vertexData[offset + 8] = particle.size;
  31514. this._vertexData[offset + 9] = offsetX;
  31515. this._vertexData[offset + 10] = offsetY;
  31516. };
  31517. ParticleSystem.prototype._update = function (newParticles) {
  31518. // Update current
  31519. this._alive = this.particles.length > 0;
  31520. this.updateFunction(this.particles);
  31521. // Add new ones
  31522. var worldMatrix;
  31523. if (this.emitter.position) {
  31524. worldMatrix = this.emitter.getWorldMatrix();
  31525. }
  31526. else {
  31527. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  31528. }
  31529. var particle;
  31530. for (var index = 0; index < newParticles; index++) {
  31531. if (this.particles.length === this._capacity) {
  31532. break;
  31533. }
  31534. if (this._stockParticles.length !== 0) {
  31535. particle = this._stockParticles.pop();
  31536. particle.age = 0;
  31537. }
  31538. else {
  31539. particle = new BABYLON.Particle();
  31540. }
  31541. this.particles.push(particle);
  31542. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  31543. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  31544. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  31545. particle.size = randomNumber(this.minSize, this.maxSize);
  31546. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  31547. this.startPositionFunction(worldMatrix, particle.position, particle);
  31548. var step = randomNumber(0, 1.0);
  31549. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  31550. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  31551. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  31552. }
  31553. };
  31554. ParticleSystem.prototype._getEffect = function () {
  31555. if (this._customEffect) {
  31556. return this._customEffect;
  31557. }
  31558. ;
  31559. var defines = [];
  31560. if (this._scene.clipPlane) {
  31561. defines.push("#define CLIPPLANE");
  31562. }
  31563. // Effect
  31564. var join = defines.join("\n");
  31565. if (this._cachedDefines !== join) {
  31566. this._cachedDefines = join;
  31567. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  31568. }
  31569. return this._effect;
  31570. };
  31571. ParticleSystem.prototype.animate = function () {
  31572. if (!this._started)
  31573. return;
  31574. var effect = this._getEffect();
  31575. // Check
  31576. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  31577. return;
  31578. if (this._currentRenderId === this._scene.getRenderId()) {
  31579. return;
  31580. }
  31581. this._currentRenderId = this._scene.getRenderId();
  31582. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  31583. // determine the number of particles we need to create
  31584. var newParticles;
  31585. if (this.manualEmitCount > -1) {
  31586. newParticles = this.manualEmitCount;
  31587. this._newPartsExcess = 0;
  31588. this.manualEmitCount = 0;
  31589. }
  31590. else {
  31591. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  31592. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  31593. }
  31594. if (this._newPartsExcess > 1.0) {
  31595. newParticles += this._newPartsExcess >> 0;
  31596. this._newPartsExcess -= this._newPartsExcess >> 0;
  31597. }
  31598. this._alive = false;
  31599. if (!this._stopped) {
  31600. this._actualFrame += this._scaledUpdateSpeed;
  31601. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  31602. this.stop();
  31603. }
  31604. else {
  31605. newParticles = 0;
  31606. }
  31607. this._update(newParticles);
  31608. // Stopped?
  31609. if (this._stopped) {
  31610. if (!this._alive) {
  31611. this._started = false;
  31612. if (this.disposeOnStop) {
  31613. this._scene._toBeDisposed.push(this);
  31614. }
  31615. }
  31616. }
  31617. // Update VBO
  31618. var offset = 0;
  31619. for (var index = 0; index < this.particles.length; index++) {
  31620. var particle = this.particles[index];
  31621. this._appendParticleVertex(offset++, particle, 0, 0);
  31622. this._appendParticleVertex(offset++, particle, 1, 0);
  31623. this._appendParticleVertex(offset++, particle, 1, 1);
  31624. this._appendParticleVertex(offset++, particle, 0, 1);
  31625. }
  31626. this._vertexBuffer.update(this._vertexData);
  31627. };
  31628. ParticleSystem.prototype.render = function () {
  31629. var effect = this._getEffect();
  31630. // Check
  31631. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  31632. return 0;
  31633. var engine = this._scene.getEngine();
  31634. // Render
  31635. engine.enableEffect(effect);
  31636. engine.setState(false);
  31637. var viewMatrix = this._scene.getViewMatrix();
  31638. effect.setTexture("diffuseSampler", this.particleTexture);
  31639. effect.setMatrix("view", viewMatrix);
  31640. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31641. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  31642. if (this._scene.clipPlane) {
  31643. var clipPlane = this._scene.clipPlane;
  31644. var invView = viewMatrix.clone();
  31645. invView.invert();
  31646. effect.setMatrix("invView", invView);
  31647. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  31648. }
  31649. // VBOs
  31650. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31651. // Draw order
  31652. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  31653. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  31654. }
  31655. else {
  31656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31657. }
  31658. if (this.forceDepthWrite) {
  31659. engine.setDepthWrite(true);
  31660. }
  31661. engine.draw(true, 0, this.particles.length * 6);
  31662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31663. return this.particles.length;
  31664. };
  31665. ParticleSystem.prototype.dispose = function () {
  31666. if (this._vertexBuffer) {
  31667. this._vertexBuffer.dispose();
  31668. this._vertexBuffer = null;
  31669. }
  31670. if (this._indexBuffer) {
  31671. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31672. this._indexBuffer = null;
  31673. }
  31674. if (this.particleTexture) {
  31675. this.particleTexture.dispose();
  31676. this.particleTexture = null;
  31677. }
  31678. // Remove from scene
  31679. var index = this._scene.particleSystems.indexOf(this);
  31680. this._scene.particleSystems.splice(index, 1);
  31681. // Callback
  31682. this.onDisposeObservable.notifyObservers(this);
  31683. this.onDisposeObservable.clear();
  31684. };
  31685. // Clone
  31686. ParticleSystem.prototype.clone = function (name, newEmitter) {
  31687. var custom = null;
  31688. var program = null;
  31689. if (this.customShader != null) {
  31690. program = this.customShader;
  31691. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31692. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31693. }
  31694. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  31695. result.customShader = program;
  31696. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  31697. if (newEmitter === undefined) {
  31698. newEmitter = this.emitter;
  31699. }
  31700. result.emitter = newEmitter;
  31701. if (this.particleTexture) {
  31702. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  31703. }
  31704. if (!this.preventAutoStart) {
  31705. result.start();
  31706. }
  31707. return result;
  31708. };
  31709. ParticleSystem.prototype.serialize = function () {
  31710. var serializationObject = {};
  31711. serializationObject.name = this.name;
  31712. serializationObject.id = this.id;
  31713. // Emitter
  31714. if (this.emitter.position) {
  31715. serializationObject.emitterId = this.emitter.id;
  31716. }
  31717. else {
  31718. serializationObject.emitter = this.emitter.asArray();
  31719. }
  31720. serializationObject.capacity = this.getCapacity();
  31721. if (this.particleTexture) {
  31722. serializationObject.textureName = this.particleTexture.name;
  31723. }
  31724. // Animations
  31725. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31726. // Particle system
  31727. serializationObject.minAngularSpeed = this.minAngularSpeed;
  31728. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  31729. serializationObject.minSize = this.minSize;
  31730. serializationObject.maxSize = this.maxSize;
  31731. serializationObject.minEmitPower = this.minEmitPower;
  31732. serializationObject.maxEmitPower = this.maxEmitPower;
  31733. serializationObject.minLifeTime = this.minLifeTime;
  31734. serializationObject.maxLifeTime = this.maxLifeTime;
  31735. serializationObject.emitRate = this.emitRate;
  31736. serializationObject.minEmitBox = this.minEmitBox.asArray();
  31737. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  31738. serializationObject.gravity = this.gravity.asArray();
  31739. serializationObject.direction1 = this.direction1.asArray();
  31740. serializationObject.direction2 = this.direction2.asArray();
  31741. serializationObject.color1 = this.color1.asArray();
  31742. serializationObject.color2 = this.color2.asArray();
  31743. serializationObject.colorDead = this.colorDead.asArray();
  31744. serializationObject.updateSpeed = this.updateSpeed;
  31745. serializationObject.targetStopDuration = this.targetStopDuration;
  31746. serializationObject.textureMask = this.textureMask.asArray();
  31747. serializationObject.blendMode = this.blendMode;
  31748. serializationObject.customShader = this.customShader;
  31749. serializationObject.preventAutoStart = this.preventAutoStart;
  31750. return serializationObject;
  31751. };
  31752. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  31753. var name = parsedParticleSystem.name;
  31754. var custom = null;
  31755. var program = null;
  31756. if (parsedParticleSystem.customShader) {
  31757. program = parsedParticleSystem.customShader;
  31758. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31759. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31760. }
  31761. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  31762. particleSystem.customShader = program;
  31763. if (parsedParticleSystem.id) {
  31764. particleSystem.id = parsedParticleSystem.id;
  31765. }
  31766. // Auto start
  31767. if (parsedParticleSystem.preventAutoStart) {
  31768. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  31769. }
  31770. // Texture
  31771. if (parsedParticleSystem.textureName) {
  31772. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  31773. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  31774. }
  31775. // Emitter
  31776. if (parsedParticleSystem.emitterId) {
  31777. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  31778. }
  31779. else {
  31780. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  31781. }
  31782. // Animations
  31783. if (parsedParticleSystem.animations) {
  31784. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  31785. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  31786. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31787. }
  31788. }
  31789. if (parsedParticleSystem.autoAnimate) {
  31790. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  31791. }
  31792. // Particle system
  31793. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  31794. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  31795. particleSystem.minSize = parsedParticleSystem.minSize;
  31796. particleSystem.maxSize = parsedParticleSystem.maxSize;
  31797. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  31798. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  31799. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  31800. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  31801. particleSystem.emitRate = parsedParticleSystem.emitRate;
  31802. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  31803. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  31804. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  31805. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  31806. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  31807. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  31808. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  31809. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  31810. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  31811. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  31812. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  31813. particleSystem.blendMode = parsedParticleSystem.blendMode;
  31814. if (!particleSystem.preventAutoStart) {
  31815. particleSystem.start();
  31816. }
  31817. return particleSystem;
  31818. };
  31819. return ParticleSystem;
  31820. }());
  31821. // Statics
  31822. ParticleSystem.BLENDMODE_ONEONE = 0;
  31823. ParticleSystem.BLENDMODE_STANDARD = 1;
  31824. BABYLON.ParticleSystem = ParticleSystem;
  31825. })(BABYLON || (BABYLON = {}));
  31826. //# sourceMappingURL=babylon.particleSystem.js.map
  31827. var BABYLON;
  31828. (function (BABYLON) {
  31829. var AnimationRange = (function () {
  31830. function AnimationRange(name, from, to) {
  31831. this.name = name;
  31832. this.from = from;
  31833. this.to = to;
  31834. }
  31835. AnimationRange.prototype.clone = function () {
  31836. return new AnimationRange(this.name, this.from, this.to);
  31837. };
  31838. return AnimationRange;
  31839. }());
  31840. BABYLON.AnimationRange = AnimationRange;
  31841. /**
  31842. * Composed of a frame, and an action function
  31843. */
  31844. var AnimationEvent = (function () {
  31845. function AnimationEvent(frame, action, onlyOnce) {
  31846. this.frame = frame;
  31847. this.action = action;
  31848. this.onlyOnce = onlyOnce;
  31849. this.isDone = false;
  31850. }
  31851. return AnimationEvent;
  31852. }());
  31853. BABYLON.AnimationEvent = AnimationEvent;
  31854. var PathCursor = (function () {
  31855. function PathCursor(path) {
  31856. this.path = path;
  31857. this._onchange = new Array();
  31858. this.value = 0;
  31859. this.animations = new Array();
  31860. }
  31861. PathCursor.prototype.getPoint = function () {
  31862. var point = this.path.getPointAtLengthPosition(this.value);
  31863. return new BABYLON.Vector3(point.x, 0, point.y);
  31864. };
  31865. PathCursor.prototype.moveAhead = function (step) {
  31866. if (step === void 0) { step = 0.002; }
  31867. this.move(step);
  31868. return this;
  31869. };
  31870. PathCursor.prototype.moveBack = function (step) {
  31871. if (step === void 0) { step = 0.002; }
  31872. this.move(-step);
  31873. return this;
  31874. };
  31875. PathCursor.prototype.move = function (step) {
  31876. if (Math.abs(step) > 1) {
  31877. throw "step size should be less than 1.";
  31878. }
  31879. this.value += step;
  31880. this.ensureLimits();
  31881. this.raiseOnChange();
  31882. return this;
  31883. };
  31884. PathCursor.prototype.ensureLimits = function () {
  31885. while (this.value > 1) {
  31886. this.value -= 1;
  31887. }
  31888. while (this.value < 0) {
  31889. this.value += 1;
  31890. }
  31891. return this;
  31892. };
  31893. // used by animation engine
  31894. PathCursor.prototype.markAsDirty = function (propertyName) {
  31895. this.ensureLimits();
  31896. this.raiseOnChange();
  31897. return this;
  31898. };
  31899. PathCursor.prototype.raiseOnChange = function () {
  31900. var _this = this;
  31901. this._onchange.forEach(function (f) { return f(_this); });
  31902. return this;
  31903. };
  31904. PathCursor.prototype.onchange = function (f) {
  31905. this._onchange.push(f);
  31906. return this;
  31907. };
  31908. return PathCursor;
  31909. }());
  31910. BABYLON.PathCursor = PathCursor;
  31911. var Animation = (function () {
  31912. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  31913. this.name = name;
  31914. this.targetProperty = targetProperty;
  31915. this.framePerSecond = framePerSecond;
  31916. this.dataType = dataType;
  31917. this.loopMode = loopMode;
  31918. this.enableBlending = enableBlending;
  31919. this._offsetsCache = {};
  31920. this._highLimitsCache = {};
  31921. this._stopped = false;
  31922. this._blendingFactor = 0;
  31923. // The set of event that will be linked to this animation
  31924. this._events = new Array();
  31925. this.allowMatricesInterpolation = false;
  31926. this.blendingSpeed = 0.01;
  31927. this._ranges = {};
  31928. this.targetPropertyPath = targetProperty.split(".");
  31929. this.dataType = dataType;
  31930. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  31931. }
  31932. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  31933. var dataType = undefined;
  31934. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  31935. dataType = Animation.ANIMATIONTYPE_FLOAT;
  31936. }
  31937. else if (from instanceof BABYLON.Quaternion) {
  31938. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  31939. }
  31940. else if (from instanceof BABYLON.Vector3) {
  31941. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  31942. }
  31943. else if (from instanceof BABYLON.Vector2) {
  31944. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  31945. }
  31946. else if (from instanceof BABYLON.Color3) {
  31947. dataType = Animation.ANIMATIONTYPE_COLOR3;
  31948. }
  31949. else if (from instanceof BABYLON.Size) {
  31950. dataType = Animation.ANIMATIONTYPE_SIZE;
  31951. }
  31952. if (dataType == undefined) {
  31953. return null;
  31954. }
  31955. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  31956. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  31957. animation.setKeys(keys);
  31958. if (easingFunction !== undefined) {
  31959. animation.setEasingFunction(easingFunction);
  31960. }
  31961. return animation;
  31962. };
  31963. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31964. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31965. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31966. };
  31967. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31968. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31969. node.animations.push(animation);
  31970. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31971. };
  31972. // Methods
  31973. /**
  31974. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31975. */
  31976. Animation.prototype.toString = function (fullDetails) {
  31977. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  31978. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  31979. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  31980. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31981. if (fullDetails) {
  31982. ret += ", Ranges: {";
  31983. var first = true;
  31984. for (var name in this._ranges) {
  31985. if (first) {
  31986. ret += ", ";
  31987. first = false;
  31988. }
  31989. ret += name;
  31990. }
  31991. ret += "}";
  31992. }
  31993. return ret;
  31994. };
  31995. /**
  31996. * Add an event to this animation.
  31997. */
  31998. Animation.prototype.addEvent = function (event) {
  31999. this._events.push(event);
  32000. };
  32001. /**
  32002. * Remove all events found at the given frame
  32003. * @param frame
  32004. */
  32005. Animation.prototype.removeEvents = function (frame) {
  32006. for (var index = 0; index < this._events.length; index++) {
  32007. if (this._events[index].frame === frame) {
  32008. this._events.splice(index, 1);
  32009. index--;
  32010. }
  32011. }
  32012. };
  32013. Animation.prototype.createRange = function (name, from, to) {
  32014. // check name not already in use; could happen for bones after serialized
  32015. if (!this._ranges[name]) {
  32016. this._ranges[name] = new AnimationRange(name, from, to);
  32017. }
  32018. };
  32019. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32020. if (deleteFrames === void 0) { deleteFrames = true; }
  32021. if (this._ranges[name]) {
  32022. if (deleteFrames) {
  32023. var from = this._ranges[name].from;
  32024. var to = this._ranges[name].to;
  32025. // this loop MUST go high to low for multiple splices to work
  32026. for (var key = this._keys.length - 1; key >= 0; key--) {
  32027. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32028. this._keys.splice(key, 1);
  32029. }
  32030. }
  32031. }
  32032. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32033. }
  32034. };
  32035. Animation.prototype.getRange = function (name) {
  32036. return this._ranges[name];
  32037. };
  32038. Animation.prototype.reset = function () {
  32039. this._offsetsCache = {};
  32040. this._highLimitsCache = {};
  32041. this.currentFrame = 0;
  32042. this._blendingFactor = 0;
  32043. this._originalBlendValue = null;
  32044. };
  32045. Animation.prototype.isStopped = function () {
  32046. return this._stopped;
  32047. };
  32048. Animation.prototype.getKeys = function () {
  32049. return this._keys;
  32050. };
  32051. Animation.prototype.getHighestFrame = function () {
  32052. var ret = 0;
  32053. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32054. if (ret < this._keys[key].frame) {
  32055. ret = this._keys[key].frame;
  32056. }
  32057. }
  32058. return ret;
  32059. };
  32060. Animation.prototype.getEasingFunction = function () {
  32061. return this._easingFunction;
  32062. };
  32063. Animation.prototype.setEasingFunction = function (easingFunction) {
  32064. this._easingFunction = easingFunction;
  32065. };
  32066. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32067. return startValue + (endValue - startValue) * gradient;
  32068. };
  32069. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32070. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32071. };
  32072. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32073. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32074. };
  32075. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32076. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32077. };
  32078. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32079. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32080. };
  32081. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32082. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32083. };
  32084. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32085. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32086. };
  32087. Animation.prototype.clone = function () {
  32088. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32089. clone.enableBlending = this.enableBlending;
  32090. clone.blendingSpeed = this.blendingSpeed;
  32091. if (this._keys) {
  32092. clone.setKeys(this._keys);
  32093. }
  32094. if (this._ranges) {
  32095. clone._ranges = {};
  32096. for (var name in this._ranges) {
  32097. clone._ranges[name] = this._ranges[name].clone();
  32098. }
  32099. }
  32100. return clone;
  32101. };
  32102. Animation.prototype.setKeys = function (values) {
  32103. this._keys = values.slice(0);
  32104. this._offsetsCache = {};
  32105. this._highLimitsCache = {};
  32106. };
  32107. Animation.prototype._getKeyValue = function (value) {
  32108. if (typeof value === "function") {
  32109. return value();
  32110. }
  32111. return value;
  32112. };
  32113. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32114. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32115. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32116. }
  32117. this.currentFrame = currentFrame;
  32118. // Try to get a hash to find the right key
  32119. 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));
  32120. if (this._keys[startKey].frame >= currentFrame) {
  32121. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32122. startKey--;
  32123. }
  32124. }
  32125. for (var key = startKey; key < this._keys.length; key++) {
  32126. if (this._keys[key + 1].frame >= currentFrame) {
  32127. var startValue = this._getKeyValue(this._keys[key].value);
  32128. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32129. // gradient : percent of currentFrame between the frame inf and the frame sup
  32130. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32131. // check for easingFunction and correction of gradient
  32132. if (this._easingFunction != null) {
  32133. gradient = this._easingFunction.ease(gradient);
  32134. }
  32135. switch (this.dataType) {
  32136. // Float
  32137. case Animation.ANIMATIONTYPE_FLOAT:
  32138. switch (loopMode) {
  32139. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32140. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32141. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32142. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32143. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32144. }
  32145. break;
  32146. // Quaternion
  32147. case Animation.ANIMATIONTYPE_QUATERNION:
  32148. var quaternion = null;
  32149. switch (loopMode) {
  32150. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32151. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32152. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32153. break;
  32154. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32155. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32156. break;
  32157. }
  32158. return quaternion;
  32159. // Vector3
  32160. case Animation.ANIMATIONTYPE_VECTOR3:
  32161. switch (loopMode) {
  32162. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32163. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32164. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32165. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32166. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32167. }
  32168. // Vector2
  32169. case Animation.ANIMATIONTYPE_VECTOR2:
  32170. switch (loopMode) {
  32171. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32172. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32173. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32174. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32175. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32176. }
  32177. // Size
  32178. case Animation.ANIMATIONTYPE_SIZE:
  32179. switch (loopMode) {
  32180. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32181. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32182. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32183. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32184. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32185. }
  32186. // Color3
  32187. case Animation.ANIMATIONTYPE_COLOR3:
  32188. switch (loopMode) {
  32189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32191. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32193. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32194. }
  32195. // Matrix
  32196. case Animation.ANIMATIONTYPE_MATRIX:
  32197. switch (loopMode) {
  32198. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32199. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32200. if (this.allowMatricesInterpolation) {
  32201. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32202. }
  32203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32204. return startValue;
  32205. }
  32206. default:
  32207. break;
  32208. }
  32209. break;
  32210. }
  32211. }
  32212. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32213. };
  32214. Animation.prototype.setValue = function (currentValue, blend) {
  32215. if (blend === void 0) { blend = false; }
  32216. // Set value
  32217. var path;
  32218. var destination;
  32219. if (this.targetPropertyPath.length > 1) {
  32220. var property = this._target[this.targetPropertyPath[0]];
  32221. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32222. property = property[this.targetPropertyPath[index]];
  32223. }
  32224. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32225. destination = property;
  32226. }
  32227. else {
  32228. path = this.targetPropertyPath[0];
  32229. destination = this._target;
  32230. }
  32231. // Blending
  32232. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32233. if (!this._originalBlendValue) {
  32234. if (destination[path].clone) {
  32235. this._originalBlendValue = destination[path].clone();
  32236. }
  32237. else {
  32238. this._originalBlendValue = destination[path];
  32239. }
  32240. }
  32241. if (this._originalBlendValue.prototype) {
  32242. if (this._originalBlendValue.prototype.Lerp) {
  32243. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32244. }
  32245. else {
  32246. destination[path] = currentValue;
  32247. }
  32248. }
  32249. else if (this._originalBlendValue.m) {
  32250. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32251. }
  32252. else {
  32253. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32254. }
  32255. this._blendingFactor += this.blendingSpeed;
  32256. }
  32257. else {
  32258. destination[path] = currentValue;
  32259. }
  32260. if (this._target.markAsDirty) {
  32261. this._target.markAsDirty(this.targetProperty);
  32262. }
  32263. };
  32264. Animation.prototype.goToFrame = function (frame) {
  32265. if (frame < this._keys[0].frame) {
  32266. frame = this._keys[0].frame;
  32267. }
  32268. else if (frame > this._keys[this._keys.length - 1].frame) {
  32269. frame = this._keys[this._keys.length - 1].frame;
  32270. }
  32271. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32272. this.setValue(currentValue);
  32273. };
  32274. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32275. if (blend === void 0) { blend = false; }
  32276. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32277. this._stopped = true;
  32278. return false;
  32279. }
  32280. var returnValue = true;
  32281. // Adding a start key at frame 0 if missing
  32282. if (this._keys[0].frame !== 0) {
  32283. var newKey = { frame: 0, value: this._keys[0].value };
  32284. this._keys.splice(0, 0, newKey);
  32285. }
  32286. // Check limits
  32287. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32288. from = this._keys[0].frame;
  32289. }
  32290. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32291. to = this._keys[this._keys.length - 1].frame;
  32292. }
  32293. //to and from cannot be the same key
  32294. if (from === to) {
  32295. from++;
  32296. }
  32297. // Compute ratio
  32298. var range = to - from;
  32299. var offsetValue;
  32300. // ratio represents the frame delta between from and to
  32301. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32302. var highLimitValue = 0;
  32303. if (ratio > range && !loop) {
  32304. returnValue = false;
  32305. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32306. }
  32307. else {
  32308. // Get max value if required
  32309. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32310. var keyOffset = to.toString() + from.toString();
  32311. if (!this._offsetsCache[keyOffset]) {
  32312. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32313. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32314. switch (this.dataType) {
  32315. // Float
  32316. case Animation.ANIMATIONTYPE_FLOAT:
  32317. this._offsetsCache[keyOffset] = toValue - fromValue;
  32318. break;
  32319. // Quaternion
  32320. case Animation.ANIMATIONTYPE_QUATERNION:
  32321. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32322. break;
  32323. // Vector3
  32324. case Animation.ANIMATIONTYPE_VECTOR3:
  32325. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32326. // Vector2
  32327. case Animation.ANIMATIONTYPE_VECTOR2:
  32328. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32329. // Size
  32330. case Animation.ANIMATIONTYPE_SIZE:
  32331. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32332. // Color3
  32333. case Animation.ANIMATIONTYPE_COLOR3:
  32334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32335. default:
  32336. break;
  32337. }
  32338. this._highLimitsCache[keyOffset] = toValue;
  32339. }
  32340. highLimitValue = this._highLimitsCache[keyOffset];
  32341. offsetValue = this._offsetsCache[keyOffset];
  32342. }
  32343. }
  32344. if (offsetValue === undefined) {
  32345. switch (this.dataType) {
  32346. // Float
  32347. case Animation.ANIMATIONTYPE_FLOAT:
  32348. offsetValue = 0;
  32349. break;
  32350. // Quaternion
  32351. case Animation.ANIMATIONTYPE_QUATERNION:
  32352. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32353. break;
  32354. // Vector3
  32355. case Animation.ANIMATIONTYPE_VECTOR3:
  32356. offsetValue = BABYLON.Vector3.Zero();
  32357. break;
  32358. // Vector2
  32359. case Animation.ANIMATIONTYPE_VECTOR2:
  32360. offsetValue = BABYLON.Vector2.Zero();
  32361. break;
  32362. // Size
  32363. case Animation.ANIMATIONTYPE_SIZE:
  32364. offsetValue = BABYLON.Size.Zero();
  32365. break;
  32366. // Color3
  32367. case Animation.ANIMATIONTYPE_COLOR3:
  32368. offsetValue = BABYLON.Color3.Black();
  32369. }
  32370. }
  32371. // Compute value
  32372. var repeatCount = (ratio / range) >> 0;
  32373. var currentFrame = returnValue ? from + ratio % range : to;
  32374. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32375. // Set value
  32376. this.setValue(currentValue);
  32377. // Check events
  32378. for (var index = 0; index < this._events.length; index++) {
  32379. if (currentFrame >= this._events[index].frame) {
  32380. var event = this._events[index];
  32381. if (!event.isDone) {
  32382. // If event should be done only once, remove it.
  32383. if (event.onlyOnce) {
  32384. this._events.splice(index, 1);
  32385. index--;
  32386. }
  32387. event.isDone = true;
  32388. event.action();
  32389. } // Don't do anything if the event has already be done.
  32390. }
  32391. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32392. // reset event, the animation is looping
  32393. this._events[index].isDone = false;
  32394. }
  32395. }
  32396. if (!returnValue) {
  32397. this._stopped = true;
  32398. }
  32399. return returnValue;
  32400. };
  32401. Animation.prototype.serialize = function () {
  32402. var serializationObject = {};
  32403. serializationObject.name = this.name;
  32404. serializationObject.property = this.targetProperty;
  32405. serializationObject.framePerSecond = this.framePerSecond;
  32406. serializationObject.dataType = this.dataType;
  32407. serializationObject.loopBehavior = this.loopMode;
  32408. serializationObject.enableBlending = this.enableBlending;
  32409. serializationObject.blendingSpeed = this.blendingSpeed;
  32410. var dataType = this.dataType;
  32411. serializationObject.keys = [];
  32412. var keys = this.getKeys();
  32413. for (var index = 0; index < keys.length; index++) {
  32414. var animationKey = keys[index];
  32415. var key = {};
  32416. key.frame = animationKey.frame;
  32417. switch (dataType) {
  32418. case Animation.ANIMATIONTYPE_FLOAT:
  32419. key.values = [animationKey.value];
  32420. break;
  32421. case Animation.ANIMATIONTYPE_QUATERNION:
  32422. case Animation.ANIMATIONTYPE_MATRIX:
  32423. case Animation.ANIMATIONTYPE_VECTOR3:
  32424. case Animation.ANIMATIONTYPE_COLOR3:
  32425. key.values = animationKey.value.asArray();
  32426. break;
  32427. }
  32428. serializationObject.keys.push(key);
  32429. }
  32430. serializationObject.ranges = [];
  32431. for (var name in this._ranges) {
  32432. var range = {};
  32433. range.name = name;
  32434. range.from = this._ranges[name].from;
  32435. range.to = this._ranges[name].to;
  32436. serializationObject.ranges.push(range);
  32437. }
  32438. return serializationObject;
  32439. };
  32440. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32441. get: function () {
  32442. return Animation._ANIMATIONTYPE_FLOAT;
  32443. },
  32444. enumerable: true,
  32445. configurable: true
  32446. });
  32447. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32448. get: function () {
  32449. return Animation._ANIMATIONTYPE_VECTOR3;
  32450. },
  32451. enumerable: true,
  32452. configurable: true
  32453. });
  32454. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32455. get: function () {
  32456. return Animation._ANIMATIONTYPE_VECTOR2;
  32457. },
  32458. enumerable: true,
  32459. configurable: true
  32460. });
  32461. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32462. get: function () {
  32463. return Animation._ANIMATIONTYPE_SIZE;
  32464. },
  32465. enumerable: true,
  32466. configurable: true
  32467. });
  32468. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32469. get: function () {
  32470. return Animation._ANIMATIONTYPE_QUATERNION;
  32471. },
  32472. enumerable: true,
  32473. configurable: true
  32474. });
  32475. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32476. get: function () {
  32477. return Animation._ANIMATIONTYPE_MATRIX;
  32478. },
  32479. enumerable: true,
  32480. configurable: true
  32481. });
  32482. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32483. get: function () {
  32484. return Animation._ANIMATIONTYPE_COLOR3;
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32490. get: function () {
  32491. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32492. },
  32493. enumerable: true,
  32494. configurable: true
  32495. });
  32496. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32497. get: function () {
  32498. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32499. },
  32500. enumerable: true,
  32501. configurable: true
  32502. });
  32503. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32504. get: function () {
  32505. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32506. },
  32507. enumerable: true,
  32508. configurable: true
  32509. });
  32510. Animation.Parse = function (parsedAnimation) {
  32511. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32512. var dataType = parsedAnimation.dataType;
  32513. var keys = [];
  32514. var data;
  32515. var index;
  32516. if (parsedAnimation.enableBlending) {
  32517. animation.enableBlending = parsedAnimation.enableBlending;
  32518. }
  32519. if (parsedAnimation.blendingSpeed) {
  32520. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32521. }
  32522. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32523. var key = parsedAnimation.keys[index];
  32524. switch (dataType) {
  32525. case Animation.ANIMATIONTYPE_FLOAT:
  32526. data = key.values[0];
  32527. break;
  32528. case Animation.ANIMATIONTYPE_QUATERNION:
  32529. data = BABYLON.Quaternion.FromArray(key.values);
  32530. break;
  32531. case Animation.ANIMATIONTYPE_MATRIX:
  32532. data = BABYLON.Matrix.FromArray(key.values);
  32533. break;
  32534. case Animation.ANIMATIONTYPE_COLOR3:
  32535. data = BABYLON.Color3.FromArray(key.values);
  32536. break;
  32537. case Animation.ANIMATIONTYPE_VECTOR3:
  32538. default:
  32539. data = BABYLON.Vector3.FromArray(key.values);
  32540. break;
  32541. }
  32542. keys.push({
  32543. frame: key.frame,
  32544. value: data
  32545. });
  32546. }
  32547. animation.setKeys(keys);
  32548. if (parsedAnimation.ranges) {
  32549. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32550. data = parsedAnimation.ranges[index];
  32551. animation.createRange(data.name, data.from, data.to);
  32552. }
  32553. }
  32554. return animation;
  32555. };
  32556. Animation.AppendSerializedAnimations = function (source, destination) {
  32557. if (source.animations) {
  32558. destination.animations = [];
  32559. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32560. var animation = source.animations[animationIndex];
  32561. destination.animations.push(animation.serialize());
  32562. }
  32563. }
  32564. };
  32565. return Animation;
  32566. }());
  32567. // Statics
  32568. Animation._ANIMATIONTYPE_FLOAT = 0;
  32569. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32570. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32571. Animation._ANIMATIONTYPE_MATRIX = 3;
  32572. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32573. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32574. Animation._ANIMATIONTYPE_SIZE = 6;
  32575. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32576. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32577. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32578. BABYLON.Animation = Animation;
  32579. })(BABYLON || (BABYLON = {}));
  32580. //# sourceMappingURL=babylon.animation.js.map
  32581. var BABYLON;
  32582. (function (BABYLON) {
  32583. var Animatable = (function () {
  32584. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32585. if (fromFrame === void 0) { fromFrame = 0; }
  32586. if (toFrame === void 0) { toFrame = 100; }
  32587. if (loopAnimation === void 0) { loopAnimation = false; }
  32588. if (speedRatio === void 0) { speedRatio = 1.0; }
  32589. this.target = target;
  32590. this.fromFrame = fromFrame;
  32591. this.toFrame = toFrame;
  32592. this.loopAnimation = loopAnimation;
  32593. this.speedRatio = speedRatio;
  32594. this.onAnimationEnd = onAnimationEnd;
  32595. this._animations = new Array();
  32596. this._paused = false;
  32597. this.animationStarted = false;
  32598. if (animations) {
  32599. this.appendAnimations(target, animations);
  32600. }
  32601. this._scene = scene;
  32602. scene._activeAnimatables.push(this);
  32603. }
  32604. // Methods
  32605. Animatable.prototype.getAnimations = function () {
  32606. return this._animations;
  32607. };
  32608. Animatable.prototype.appendAnimations = function (target, animations) {
  32609. for (var index = 0; index < animations.length; index++) {
  32610. var animation = animations[index];
  32611. animation._target = target;
  32612. this._animations.push(animation);
  32613. }
  32614. };
  32615. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32616. var animations = this._animations;
  32617. for (var index = 0; index < animations.length; index++) {
  32618. if (animations[index].targetProperty === property) {
  32619. return animations[index];
  32620. }
  32621. }
  32622. return null;
  32623. };
  32624. Animatable.prototype.reset = function () {
  32625. var animations = this._animations;
  32626. for (var index = 0; index < animations.length; index++) {
  32627. animations[index].reset();
  32628. }
  32629. this._localDelayOffset = null;
  32630. this._pausedDelay = null;
  32631. };
  32632. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32633. var animations = this._animations;
  32634. for (var index = 0; index < animations.length; index++) {
  32635. animations[index].enableBlending = true;
  32636. animations[index].blendingSpeed = blendingSpeed;
  32637. }
  32638. };
  32639. Animatable.prototype.disableBlending = function () {
  32640. var animations = this._animations;
  32641. for (var index = 0; index < animations.length; index++) {
  32642. animations[index].enableBlending = false;
  32643. }
  32644. };
  32645. Animatable.prototype.goToFrame = function (frame) {
  32646. var animations = this._animations;
  32647. if (animations[0]) {
  32648. var fps = animations[0].framePerSecond;
  32649. var currentFrame = animations[0].currentFrame;
  32650. var adjustTime = frame - currentFrame;
  32651. var delay = adjustTime * 1000 / fps;
  32652. this._localDelayOffset -= delay;
  32653. }
  32654. for (var index = 0; index < animations.length; index++) {
  32655. animations[index].goToFrame(frame);
  32656. }
  32657. };
  32658. Animatable.prototype.pause = function () {
  32659. if (this._paused) {
  32660. return;
  32661. }
  32662. this._paused = true;
  32663. };
  32664. Animatable.prototype.restart = function () {
  32665. this._paused = false;
  32666. };
  32667. Animatable.prototype.stop = function (animationName) {
  32668. if (animationName) {
  32669. var idx = this._scene._activeAnimatables.indexOf(this);
  32670. if (idx > -1) {
  32671. var animations = this._animations;
  32672. for (var index = animations.length - 1; index >= 0; index--) {
  32673. if (typeof animationName === "string" && animations[index].name != animationName) {
  32674. continue;
  32675. }
  32676. animations[index].reset();
  32677. animations.splice(index, 1);
  32678. }
  32679. if (animations.length == 0) {
  32680. this._scene._activeAnimatables.splice(idx, 1);
  32681. if (this.onAnimationEnd) {
  32682. this.onAnimationEnd();
  32683. }
  32684. }
  32685. }
  32686. }
  32687. else {
  32688. var index = this._scene._activeAnimatables.indexOf(this);
  32689. if (index > -1) {
  32690. this._scene._activeAnimatables.splice(index, 1);
  32691. var animations = this._animations;
  32692. for (var index = 0; index < animations.length; index++) {
  32693. animations[index].reset();
  32694. }
  32695. if (this.onAnimationEnd) {
  32696. this.onAnimationEnd();
  32697. }
  32698. }
  32699. }
  32700. };
  32701. Animatable.prototype._animate = function (delay) {
  32702. if (this._paused) {
  32703. this.animationStarted = false;
  32704. if (!this._pausedDelay) {
  32705. this._pausedDelay = delay;
  32706. }
  32707. return true;
  32708. }
  32709. if (!this._localDelayOffset) {
  32710. this._localDelayOffset = delay;
  32711. }
  32712. else if (this._pausedDelay) {
  32713. this._localDelayOffset += delay - this._pausedDelay;
  32714. this._pausedDelay = null;
  32715. }
  32716. // Animating
  32717. var running = false;
  32718. var animations = this._animations;
  32719. var index;
  32720. for (index = 0; index < animations.length; index++) {
  32721. var animation = animations[index];
  32722. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  32723. running = running || isRunning;
  32724. }
  32725. this.animationStarted = running;
  32726. if (!running) {
  32727. // Remove from active animatables
  32728. index = this._scene._activeAnimatables.indexOf(this);
  32729. this._scene._activeAnimatables.splice(index, 1);
  32730. }
  32731. if (!running && this.onAnimationEnd) {
  32732. this.onAnimationEnd();
  32733. this.onAnimationEnd = null;
  32734. }
  32735. return running;
  32736. };
  32737. return Animatable;
  32738. }());
  32739. BABYLON.Animatable = Animatable;
  32740. })(BABYLON || (BABYLON = {}));
  32741. //# sourceMappingURL=babylon.animatable.js.map
  32742. var BABYLON;
  32743. (function (BABYLON) {
  32744. var EasingFunction = (function () {
  32745. function EasingFunction() {
  32746. // Properties
  32747. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  32748. }
  32749. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  32750. get: function () {
  32751. return EasingFunction._EASINGMODE_EASEIN;
  32752. },
  32753. enumerable: true,
  32754. configurable: true
  32755. });
  32756. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  32757. get: function () {
  32758. return EasingFunction._EASINGMODE_EASEOUT;
  32759. },
  32760. enumerable: true,
  32761. configurable: true
  32762. });
  32763. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  32764. get: function () {
  32765. return EasingFunction._EASINGMODE_EASEINOUT;
  32766. },
  32767. enumerable: true,
  32768. configurable: true
  32769. });
  32770. EasingFunction.prototype.setEasingMode = function (easingMode) {
  32771. var n = Math.min(Math.max(easingMode, 0), 2);
  32772. this._easingMode = n;
  32773. };
  32774. EasingFunction.prototype.getEasingMode = function () {
  32775. return this._easingMode;
  32776. };
  32777. EasingFunction.prototype.easeInCore = function (gradient) {
  32778. throw new Error('You must implement this method');
  32779. };
  32780. EasingFunction.prototype.ease = function (gradient) {
  32781. switch (this._easingMode) {
  32782. case EasingFunction.EASINGMODE_EASEIN:
  32783. return this.easeInCore(gradient);
  32784. case EasingFunction.EASINGMODE_EASEOUT:
  32785. return (1 - this.easeInCore(1 - gradient));
  32786. }
  32787. if (gradient >= 0.5) {
  32788. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  32789. }
  32790. return (this.easeInCore(gradient * 2) * 0.5);
  32791. };
  32792. return EasingFunction;
  32793. }());
  32794. //Statics
  32795. EasingFunction._EASINGMODE_EASEIN = 0;
  32796. EasingFunction._EASINGMODE_EASEOUT = 1;
  32797. EasingFunction._EASINGMODE_EASEINOUT = 2;
  32798. BABYLON.EasingFunction = EasingFunction;
  32799. var CircleEase = (function (_super) {
  32800. __extends(CircleEase, _super);
  32801. function CircleEase() {
  32802. return _super.apply(this, arguments) || this;
  32803. }
  32804. CircleEase.prototype.easeInCore = function (gradient) {
  32805. gradient = Math.max(0, Math.min(1, gradient));
  32806. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  32807. };
  32808. return CircleEase;
  32809. }(EasingFunction));
  32810. BABYLON.CircleEase = CircleEase;
  32811. var BackEase = (function (_super) {
  32812. __extends(BackEase, _super);
  32813. function BackEase(amplitude) {
  32814. if (amplitude === void 0) { amplitude = 1; }
  32815. var _this = _super.call(this) || this;
  32816. _this.amplitude = amplitude;
  32817. return _this;
  32818. }
  32819. BackEase.prototype.easeInCore = function (gradient) {
  32820. var num = Math.max(0, this.amplitude);
  32821. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  32822. };
  32823. return BackEase;
  32824. }(EasingFunction));
  32825. BABYLON.BackEase = BackEase;
  32826. var BounceEase = (function (_super) {
  32827. __extends(BounceEase, _super);
  32828. function BounceEase(bounces, bounciness) {
  32829. if (bounces === void 0) { bounces = 3; }
  32830. if (bounciness === void 0) { bounciness = 2; }
  32831. var _this = _super.call(this) || this;
  32832. _this.bounces = bounces;
  32833. _this.bounciness = bounciness;
  32834. return _this;
  32835. }
  32836. BounceEase.prototype.easeInCore = function (gradient) {
  32837. var y = Math.max(0.0, this.bounces);
  32838. var bounciness = this.bounciness;
  32839. if (bounciness <= 1.0) {
  32840. bounciness = 1.001;
  32841. }
  32842. var num9 = Math.pow(bounciness, y);
  32843. var num5 = 1.0 - bounciness;
  32844. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  32845. var num15 = gradient * num4;
  32846. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  32847. var num3 = Math.floor(num65);
  32848. var num13 = num3 + 1.0;
  32849. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  32850. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  32851. var num7 = (num8 + num12) * 0.5;
  32852. var num6 = gradient - num7;
  32853. var num2 = num7 - num8;
  32854. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  32855. };
  32856. return BounceEase;
  32857. }(EasingFunction));
  32858. BABYLON.BounceEase = BounceEase;
  32859. var CubicEase = (function (_super) {
  32860. __extends(CubicEase, _super);
  32861. function CubicEase() {
  32862. return _super.apply(this, arguments) || this;
  32863. }
  32864. CubicEase.prototype.easeInCore = function (gradient) {
  32865. return (gradient * gradient * gradient);
  32866. };
  32867. return CubicEase;
  32868. }(EasingFunction));
  32869. BABYLON.CubicEase = CubicEase;
  32870. var ElasticEase = (function (_super) {
  32871. __extends(ElasticEase, _super);
  32872. function ElasticEase(oscillations, springiness) {
  32873. if (oscillations === void 0) { oscillations = 3; }
  32874. if (springiness === void 0) { springiness = 3; }
  32875. var _this = _super.call(this) || this;
  32876. _this.oscillations = oscillations;
  32877. _this.springiness = springiness;
  32878. return _this;
  32879. }
  32880. ElasticEase.prototype.easeInCore = function (gradient) {
  32881. var num2;
  32882. var num3 = Math.max(0.0, this.oscillations);
  32883. var num = Math.max(0.0, this.springiness);
  32884. if (num == 0) {
  32885. num2 = gradient;
  32886. }
  32887. else {
  32888. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  32889. }
  32890. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  32891. };
  32892. return ElasticEase;
  32893. }(EasingFunction));
  32894. BABYLON.ElasticEase = ElasticEase;
  32895. var ExponentialEase = (function (_super) {
  32896. __extends(ExponentialEase, _super);
  32897. function ExponentialEase(exponent) {
  32898. if (exponent === void 0) { exponent = 2; }
  32899. var _this = _super.call(this) || this;
  32900. _this.exponent = exponent;
  32901. return _this;
  32902. }
  32903. ExponentialEase.prototype.easeInCore = function (gradient) {
  32904. if (this.exponent <= 0) {
  32905. return gradient;
  32906. }
  32907. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  32908. };
  32909. return ExponentialEase;
  32910. }(EasingFunction));
  32911. BABYLON.ExponentialEase = ExponentialEase;
  32912. var PowerEase = (function (_super) {
  32913. __extends(PowerEase, _super);
  32914. function PowerEase(power) {
  32915. if (power === void 0) { power = 2; }
  32916. var _this = _super.call(this) || this;
  32917. _this.power = power;
  32918. return _this;
  32919. }
  32920. PowerEase.prototype.easeInCore = function (gradient) {
  32921. var y = Math.max(0.0, this.power);
  32922. return Math.pow(gradient, y);
  32923. };
  32924. return PowerEase;
  32925. }(EasingFunction));
  32926. BABYLON.PowerEase = PowerEase;
  32927. var QuadraticEase = (function (_super) {
  32928. __extends(QuadraticEase, _super);
  32929. function QuadraticEase() {
  32930. return _super.apply(this, arguments) || this;
  32931. }
  32932. QuadraticEase.prototype.easeInCore = function (gradient) {
  32933. return (gradient * gradient);
  32934. };
  32935. return QuadraticEase;
  32936. }(EasingFunction));
  32937. BABYLON.QuadraticEase = QuadraticEase;
  32938. var QuarticEase = (function (_super) {
  32939. __extends(QuarticEase, _super);
  32940. function QuarticEase() {
  32941. return _super.apply(this, arguments) || this;
  32942. }
  32943. QuarticEase.prototype.easeInCore = function (gradient) {
  32944. return (gradient * gradient * gradient * gradient);
  32945. };
  32946. return QuarticEase;
  32947. }(EasingFunction));
  32948. BABYLON.QuarticEase = QuarticEase;
  32949. var QuinticEase = (function (_super) {
  32950. __extends(QuinticEase, _super);
  32951. function QuinticEase() {
  32952. return _super.apply(this, arguments) || this;
  32953. }
  32954. QuinticEase.prototype.easeInCore = function (gradient) {
  32955. return (gradient * gradient * gradient * gradient * gradient);
  32956. };
  32957. return QuinticEase;
  32958. }(EasingFunction));
  32959. BABYLON.QuinticEase = QuinticEase;
  32960. var SineEase = (function (_super) {
  32961. __extends(SineEase, _super);
  32962. function SineEase() {
  32963. return _super.apply(this, arguments) || this;
  32964. }
  32965. SineEase.prototype.easeInCore = function (gradient) {
  32966. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  32967. };
  32968. return SineEase;
  32969. }(EasingFunction));
  32970. BABYLON.SineEase = SineEase;
  32971. var BezierCurveEase = (function (_super) {
  32972. __extends(BezierCurveEase, _super);
  32973. function BezierCurveEase(x1, y1, x2, y2) {
  32974. if (x1 === void 0) { x1 = 0; }
  32975. if (y1 === void 0) { y1 = 0; }
  32976. if (x2 === void 0) { x2 = 1; }
  32977. if (y2 === void 0) { y2 = 1; }
  32978. var _this = _super.call(this) || this;
  32979. _this.x1 = x1;
  32980. _this.y1 = y1;
  32981. _this.x2 = x2;
  32982. _this.y2 = y2;
  32983. return _this;
  32984. }
  32985. BezierCurveEase.prototype.easeInCore = function (gradient) {
  32986. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  32987. };
  32988. return BezierCurveEase;
  32989. }(EasingFunction));
  32990. BABYLON.BezierCurveEase = BezierCurveEase;
  32991. })(BABYLON || (BABYLON = {}));
  32992. //# sourceMappingURL=babylon.easing.js.map
  32993. /// <reference path="..\babylon.node.ts" />
  32994. var BABYLON;
  32995. (function (BABYLON) {
  32996. var Bone = (function (_super) {
  32997. __extends(Bone, _super);
  32998. function Bone(name, skeleton, parentBone, matrix, restPose) {
  32999. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33000. _this.name = name;
  33001. _this.children = new Array();
  33002. _this.animations = new Array();
  33003. _this._worldTransform = new BABYLON.Matrix();
  33004. _this._absoluteTransform = new BABYLON.Matrix();
  33005. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33006. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33007. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33008. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33009. _this._scalingDeterminant = 1;
  33010. _this._skeleton = skeleton;
  33011. _this._localMatrix = matrix;
  33012. _this._baseMatrix = matrix.clone();
  33013. _this._restPose = restPose ? restPose : matrix.clone();
  33014. skeleton.bones.push(_this);
  33015. if (parentBone) {
  33016. _this._parent = parentBone;
  33017. parentBone.children.push(_this);
  33018. }
  33019. else {
  33020. _this._parent = null;
  33021. }
  33022. _this._updateDifferenceMatrix();
  33023. if (_this.getAbsoluteTransform().determinant() < 0) {
  33024. _this._scalingDeterminant *= -1;
  33025. }
  33026. return _this;
  33027. }
  33028. Object.defineProperty(Bone.prototype, "_matrix", {
  33029. get: function () {
  33030. return this._localMatrix;
  33031. },
  33032. set: function (val) {
  33033. if (this._localMatrix) {
  33034. this._localMatrix.copyFrom(val);
  33035. }
  33036. else {
  33037. this._localMatrix = val;
  33038. }
  33039. },
  33040. enumerable: true,
  33041. configurable: true
  33042. });
  33043. // Members
  33044. Bone.prototype.getParent = function () {
  33045. return this._parent;
  33046. };
  33047. Bone.prototype.getLocalMatrix = function () {
  33048. return this._localMatrix;
  33049. };
  33050. Bone.prototype.getBaseMatrix = function () {
  33051. return this._baseMatrix;
  33052. };
  33053. Bone.prototype.getRestPose = function () {
  33054. return this._restPose;
  33055. };
  33056. Bone.prototype.returnToRest = function () {
  33057. this.updateMatrix(this._restPose.clone());
  33058. };
  33059. Bone.prototype.getWorldMatrix = function () {
  33060. return this._worldTransform;
  33061. };
  33062. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33063. return this._invertedAbsoluteTransform;
  33064. };
  33065. Bone.prototype.getAbsoluteTransform = function () {
  33066. return this._absoluteTransform;
  33067. };
  33068. // Methods
  33069. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33070. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33071. this._baseMatrix = matrix.clone();
  33072. this._localMatrix = matrix.clone();
  33073. this._skeleton._markAsDirty();
  33074. if (updateDifferenceMatrix) {
  33075. this._updateDifferenceMatrix();
  33076. }
  33077. };
  33078. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33079. if (!rootMatrix) {
  33080. rootMatrix = this._baseMatrix;
  33081. }
  33082. if (this._parent) {
  33083. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33084. }
  33085. else {
  33086. this._absoluteTransform.copyFrom(rootMatrix);
  33087. }
  33088. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33089. for (var index = 0; index < this.children.length; index++) {
  33090. this.children[index]._updateDifferenceMatrix();
  33091. }
  33092. };
  33093. Bone.prototype.markAsDirty = function () {
  33094. this._currentRenderId++;
  33095. this._skeleton._markAsDirty();
  33096. };
  33097. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33098. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33099. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33100. // all animation may be coming from a library skeleton, so may need to create animation
  33101. if (this.animations.length === 0) {
  33102. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33103. this.animations[0].setKeys([]);
  33104. }
  33105. // get animation info / verify there is such a range from the source bone
  33106. var sourceRange = source.animations[0].getRange(rangeName);
  33107. if (!sourceRange) {
  33108. return false;
  33109. }
  33110. var from = sourceRange.from;
  33111. var to = sourceRange.to;
  33112. var sourceKeys = source.animations[0].getKeys();
  33113. // rescaling prep
  33114. var sourceBoneLength = source.length;
  33115. var sourceParent = source.getParent();
  33116. var parent = this.getParent();
  33117. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33118. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33119. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33120. var destKeys = this.animations[0].getKeys();
  33121. // loop vars declaration
  33122. var orig;
  33123. var origTranslation;
  33124. var mat;
  33125. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33126. orig = sourceKeys[key];
  33127. if (orig.frame >= from && orig.frame <= to) {
  33128. if (rescaleAsRequired) {
  33129. mat = orig.value.clone();
  33130. // scale based on parent ratio, when bone has parent
  33131. if (parentScalingReqd) {
  33132. origTranslation = mat.getTranslation();
  33133. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33134. }
  33135. else if (dimensionsScalingReqd) {
  33136. origTranslation = mat.getTranslation();
  33137. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33138. }
  33139. else {
  33140. mat = orig.value;
  33141. }
  33142. }
  33143. else {
  33144. mat = orig.value;
  33145. }
  33146. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33147. }
  33148. }
  33149. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33150. return true;
  33151. };
  33152. /**
  33153. * Translate the bone in local or world space.
  33154. * @param vec The amount to translate the bone.
  33155. * @param space The space that the translation is in.
  33156. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33157. */
  33158. Bone.prototype.translate = function (vec, space, mesh) {
  33159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33160. var lm = this.getLocalMatrix();
  33161. if (space == BABYLON.Space.LOCAL) {
  33162. lm.m[12] += vec.x;
  33163. lm.m[13] += vec.y;
  33164. lm.m[14] += vec.z;
  33165. }
  33166. else {
  33167. this._skeleton.computeAbsoluteTransforms();
  33168. var tmat = BABYLON.Tmp.Matrix[0];
  33169. var tvec = BABYLON.Tmp.Vector3[0];
  33170. if (mesh) {
  33171. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33172. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33173. }
  33174. else {
  33175. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33176. }
  33177. tmat.m[12] = 0;
  33178. tmat.m[13] = 0;
  33179. tmat.m[14] = 0;
  33180. tmat.invert();
  33181. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33182. lm.m[12] += tvec.x;
  33183. lm.m[13] += tvec.y;
  33184. lm.m[14] += tvec.z;
  33185. }
  33186. this.markAsDirty();
  33187. };
  33188. /**
  33189. * Set the postion of the bone in local or world space.
  33190. * @param position The position to set the bone.
  33191. * @param space The space that the position is in.
  33192. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33193. */
  33194. Bone.prototype.setPosition = function (position, space, mesh) {
  33195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33196. var lm = this.getLocalMatrix();
  33197. if (space == BABYLON.Space.LOCAL) {
  33198. lm.m[12] = position.x;
  33199. lm.m[13] = position.y;
  33200. lm.m[14] = position.z;
  33201. }
  33202. else {
  33203. this._skeleton.computeAbsoluteTransforms();
  33204. var tmat = BABYLON.Tmp.Matrix[0];
  33205. var vec = BABYLON.Tmp.Vector3[0];
  33206. if (mesh) {
  33207. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33208. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33209. }
  33210. else {
  33211. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33212. }
  33213. tmat.invert();
  33214. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  33215. lm.m[12] = vec.x;
  33216. lm.m[13] = vec.y;
  33217. lm.m[14] = vec.z;
  33218. }
  33219. this.markAsDirty();
  33220. };
  33221. /**
  33222. * Set the absolute postion of the bone (world space).
  33223. * @param position The position to set the bone.
  33224. * @param mesh The mesh that this bone is attached to.
  33225. */
  33226. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  33227. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  33228. };
  33229. /**
  33230. * Set the scale of the bone on the x, y and z axes.
  33231. * @param x The scale of the bone on the x axis.
  33232. * @param x The scale of the bone on the y axis.
  33233. * @param z The scale of the bone on the z axis.
  33234. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33235. */
  33236. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  33237. if (scaleChildren === void 0) { scaleChildren = false; }
  33238. if (this.animations[0] && !this.animations[0].isStopped()) {
  33239. if (!scaleChildren) {
  33240. this._negateScaleChildren.x = 1 / x;
  33241. this._negateScaleChildren.y = 1 / y;
  33242. this._negateScaleChildren.z = 1 / z;
  33243. }
  33244. this._syncScaleVector();
  33245. }
  33246. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  33247. };
  33248. /**
  33249. * Scale the bone on the x, y and z axes.
  33250. * @param x The amount to scale the bone on the x axis.
  33251. * @param x The amount to scale the bone on the y axis.
  33252. * @param z The amount to scale the bone on the z axis.
  33253. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33254. */
  33255. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  33256. if (scaleChildren === void 0) { scaleChildren = false; }
  33257. var locMat = this.getLocalMatrix();
  33258. var origLocMat = BABYLON.Tmp.Matrix[0];
  33259. origLocMat.copyFrom(locMat);
  33260. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  33261. origLocMatInv.copyFrom(origLocMat);
  33262. origLocMatInv.invert();
  33263. var scaleMat = BABYLON.Tmp.Matrix[2];
  33264. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  33265. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  33266. this._scaleVector.x *= x;
  33267. this._scaleVector.y *= y;
  33268. this._scaleVector.z *= z;
  33269. locMat.multiplyToRef(origLocMatInv, locMat);
  33270. locMat.multiplyToRef(scaleMat, locMat);
  33271. locMat.multiplyToRef(origLocMat, locMat);
  33272. var parent = this.getParent();
  33273. if (parent) {
  33274. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  33275. }
  33276. else {
  33277. this.getAbsoluteTransform().copyFrom(locMat);
  33278. }
  33279. var len = this.children.length;
  33280. scaleMat.invert();
  33281. for (var i = 0; i < len; i++) {
  33282. var child = this.children[i];
  33283. var cm = child.getLocalMatrix();
  33284. cm.multiplyToRef(scaleMat, cm);
  33285. var lm = child.getLocalMatrix();
  33286. lm.m[12] *= x;
  33287. lm.m[13] *= y;
  33288. lm.m[14] *= z;
  33289. }
  33290. this.computeAbsoluteTransforms();
  33291. if (scaleChildren) {
  33292. for (var i = 0; i < len; i++) {
  33293. this.children[i].scale(x, y, z, scaleChildren);
  33294. }
  33295. }
  33296. this.markAsDirty();
  33297. };
  33298. /**
  33299. * Set the yaw, pitch, and roll of the bone in local or world space.
  33300. * @param yaw The rotation of the bone on the y axis.
  33301. * @param pitch The rotation of the bone on the x axis.
  33302. * @param roll The rotation of the bone on the z axis.
  33303. * @param space The space that the axes of rotation are in.
  33304. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33305. */
  33306. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  33307. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33308. var rotMat = BABYLON.Tmp.Matrix[0];
  33309. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  33310. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33311. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33312. rotMatInv.multiplyToRef(rotMat, rotMat);
  33313. this._rotateWithMatrix(rotMat, space, mesh);
  33314. };
  33315. /**
  33316. * Rotate the bone on an axis in local or world space.
  33317. * @param axis The axis to rotate the bone on.
  33318. * @param amount The amount to rotate the bone.
  33319. * @param space The space that the axis is in.
  33320. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33321. */
  33322. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  33323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33324. var rmat = BABYLON.Tmp.Matrix[0];
  33325. rmat.m[12] = 0;
  33326. rmat.m[13] = 0;
  33327. rmat.m[14] = 0;
  33328. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  33329. this._rotateWithMatrix(rmat, space, mesh);
  33330. };
  33331. /**
  33332. * Set the rotation of the bone to a particular axis angle in local or world space.
  33333. * @param axis The axis to rotate the bone on.
  33334. * @param angle The angle that the bone should be rotated to.
  33335. * @param space The space that the axis is in.
  33336. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33337. */
  33338. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  33339. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33340. var rotMat = BABYLON.Tmp.Matrix[0];
  33341. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  33342. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33343. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33344. rotMatInv.multiplyToRef(rotMat, rotMat);
  33345. this._rotateWithMatrix(rotMat, space, mesh);
  33346. };
  33347. /**
  33348. * Set the euler rotation of the bone in local of world space.
  33349. * @param rotation The euler rotation that the bone should be set to.
  33350. * @param space The space that the rotation is in.
  33351. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33352. */
  33353. Bone.prototype.setRotation = function (rotation, space, mesh) {
  33354. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33355. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  33356. };
  33357. /**
  33358. * Set the quaternion rotation of the bone in local of world space.
  33359. * @param quat The quaternion rotation that the bone should be set to.
  33360. * @param space The space that the rotation is in.
  33361. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33362. */
  33363. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  33364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33365. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33366. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33367. var rotMat = BABYLON.Tmp.Matrix[1];
  33368. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  33369. rotMatInv.multiplyToRef(rotMat, rotMat);
  33370. this._rotateWithMatrix(rotMat, space, mesh);
  33371. };
  33372. /**
  33373. * Set the rotation matrix of the bone in local of world space.
  33374. * @param rotMat The rotation matrix that the bone should be set to.
  33375. * @param space The space that the rotation is in.
  33376. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33377. */
  33378. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  33379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33380. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33381. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33382. var rotMat2 = BABYLON.Tmp.Matrix[1];
  33383. rotMat2.copyFrom(rotMat);
  33384. rotMatInv.multiplyToRef(rotMat, rotMat2);
  33385. this._rotateWithMatrix(rotMat2, space, mesh);
  33386. };
  33387. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  33388. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33389. var lmat = this.getLocalMatrix();
  33390. var lx = lmat.m[12];
  33391. var ly = lmat.m[13];
  33392. var lz = lmat.m[14];
  33393. var parent = this.getParent();
  33394. var parentScale = BABYLON.Tmp.Matrix[3];
  33395. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  33396. if (parent) {
  33397. if (space == BABYLON.Space.WORLD) {
  33398. if (mesh) {
  33399. parentScale.copyFrom(mesh.getWorldMatrix());
  33400. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  33401. }
  33402. else {
  33403. parentScale.copyFrom(parent.getAbsoluteTransform());
  33404. }
  33405. }
  33406. else {
  33407. parentScale = parent._scaleMatrix;
  33408. }
  33409. parentScaleInv.copyFrom(parentScale);
  33410. parentScaleInv.invert();
  33411. lmat.multiplyToRef(parentScale, lmat);
  33412. lmat.multiplyToRef(rmat, lmat);
  33413. lmat.multiplyToRef(parentScaleInv, lmat);
  33414. }
  33415. else {
  33416. if (space == BABYLON.Space.WORLD && mesh) {
  33417. parentScale.copyFrom(mesh.getWorldMatrix());
  33418. parentScaleInv.copyFrom(parentScale);
  33419. parentScaleInv.invert();
  33420. lmat.multiplyToRef(parentScale, lmat);
  33421. lmat.multiplyToRef(rmat, lmat);
  33422. lmat.multiplyToRef(parentScaleInv, lmat);
  33423. }
  33424. else {
  33425. lmat.multiplyToRef(rmat, lmat);
  33426. }
  33427. }
  33428. lmat.m[12] = lx;
  33429. lmat.m[13] = ly;
  33430. lmat.m[14] = lz;
  33431. this.computeAbsoluteTransforms();
  33432. this.markAsDirty();
  33433. };
  33434. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  33435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33436. if (space == BABYLON.Space.WORLD) {
  33437. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33438. scaleMatrix.copyFrom(this._scaleMatrix);
  33439. rotMatInv.copyFrom(this.getAbsoluteTransform());
  33440. if (mesh) {
  33441. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  33442. var meshScale = BABYLON.Tmp.Matrix[3];
  33443. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  33444. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  33445. }
  33446. rotMatInv.invert();
  33447. scaleMatrix.m[0] *= this._scalingDeterminant;
  33448. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33449. }
  33450. else {
  33451. rotMatInv.copyFrom(this.getLocalMatrix());
  33452. rotMatInv.invert();
  33453. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33454. scaleMatrix.copyFrom(this._scaleMatrix);
  33455. if (this._parent) {
  33456. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  33457. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  33458. pscaleMatrix.invert();
  33459. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  33460. }
  33461. else {
  33462. scaleMatrix.m[0] *= this._scalingDeterminant;
  33463. }
  33464. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33465. }
  33466. };
  33467. /**
  33468. * Get the scale of the bone
  33469. * @returns the scale of the bone
  33470. */
  33471. Bone.prototype.getScale = function () {
  33472. return this._scaleVector.clone();
  33473. };
  33474. /**
  33475. * Copy the scale of the bone to a vector3.
  33476. * @param result The vector3 to copy the scale to
  33477. */
  33478. Bone.prototype.getScaleToRef = function (result) {
  33479. result.copyFrom(this._scaleVector);
  33480. };
  33481. /**
  33482. * Get the position of the bone in local or world space.
  33483. * @param space The space that the returned position is in.
  33484. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33485. * @returns The position of the bone
  33486. */
  33487. Bone.prototype.getPosition = function (space, mesh) {
  33488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33489. var pos = BABYLON.Vector3.Zero();
  33490. this.getPositionToRef(space, mesh, pos);
  33491. return pos;
  33492. };
  33493. /**
  33494. * Copy the position of the bone to a vector3 in local or world space.
  33495. * @param space The space that the returned position is in.
  33496. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33497. * @param result The vector3 to copy the position to.
  33498. */
  33499. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  33500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33501. if (space == BABYLON.Space.LOCAL) {
  33502. var lm = this.getLocalMatrix();
  33503. result.x = lm.m[12];
  33504. result.y = lm.m[13];
  33505. result.z = lm.m[14];
  33506. }
  33507. else {
  33508. this._skeleton.computeAbsoluteTransforms();
  33509. var tmat = BABYLON.Tmp.Matrix[0];
  33510. if (mesh) {
  33511. tmat.copyFrom(this.getAbsoluteTransform());
  33512. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33513. }
  33514. else {
  33515. tmat = this.getAbsoluteTransform();
  33516. }
  33517. result.x = tmat.m[12];
  33518. result.y = tmat.m[13];
  33519. result.z = tmat.m[14];
  33520. }
  33521. };
  33522. /**
  33523. * Get the absolute position of the bone (world space).
  33524. * @param mesh The mesh that this bone is attached to.
  33525. * @returns The absolute position of the bone
  33526. */
  33527. Bone.prototype.getAbsolutePosition = function (mesh) {
  33528. var pos = BABYLON.Vector3.Zero();
  33529. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  33530. return pos;
  33531. };
  33532. /**
  33533. * Copy the absolute position of the bone (world space) to the result param.
  33534. * @param mesh The mesh that this bone is attached to.
  33535. * @param result The vector3 to copy the absolute position to.
  33536. */
  33537. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  33538. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  33539. };
  33540. /**
  33541. * Compute the absolute transforms of this bone and its children.
  33542. */
  33543. Bone.prototype.computeAbsoluteTransforms = function () {
  33544. if (this._parent) {
  33545. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33546. }
  33547. else {
  33548. this._absoluteTransform.copyFrom(this._localMatrix);
  33549. var poseMatrix = this._skeleton.getPoseMatrix();
  33550. if (poseMatrix) {
  33551. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  33552. }
  33553. }
  33554. var children = this.children;
  33555. var len = children.length;
  33556. for (var i = 0; i < len; i++) {
  33557. children[i].computeAbsoluteTransforms();
  33558. }
  33559. };
  33560. Bone.prototype._syncScaleVector = function () {
  33561. var lm = this.getLocalMatrix();
  33562. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  33563. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  33564. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  33565. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  33566. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  33567. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  33568. this._scaleVector.x = xs * Math.sqrt(xsq);
  33569. this._scaleVector.y = ys * Math.sqrt(ysq);
  33570. this._scaleVector.z = zs * Math.sqrt(zsq);
  33571. if (this._parent) {
  33572. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  33573. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  33574. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  33575. }
  33576. 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);
  33577. };
  33578. /**
  33579. * Get the world direction from an axis that is in the local space of the bone.
  33580. * @param localAxis The local direction that is used to compute the world direction.
  33581. * @param mesh The mesh that this bone is attached to.
  33582. * @returns The world direction
  33583. */
  33584. Bone.prototype.getDirection = function (localAxis, mesh) {
  33585. var result = BABYLON.Vector3.Zero();
  33586. this.getDirectionToRef(localAxis, mesh, result);
  33587. return result;
  33588. };
  33589. /**
  33590. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  33591. * @param localAxis The local direction that is used to compute the world direction.
  33592. * @param mesh The mesh that this bone is attached to.
  33593. * @param result The vector3 that the world direction will be copied to.
  33594. */
  33595. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  33596. this._skeleton.computeAbsoluteTransforms();
  33597. var mat = BABYLON.Tmp.Matrix[0];
  33598. mat.copyFrom(this.getAbsoluteTransform());
  33599. if (mesh) {
  33600. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33601. }
  33602. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  33603. result.normalize();
  33604. };
  33605. /**
  33606. * Get the euler rotation of the bone in local or world space.
  33607. * @param space The space that the rotation should be in.
  33608. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33609. * @returns The euler rotation
  33610. */
  33611. Bone.prototype.getRotation = function (space, mesh) {
  33612. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33613. var result = BABYLON.Vector3.Zero();
  33614. this.getRotationToRef(space, mesh, result);
  33615. return result;
  33616. };
  33617. /**
  33618. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  33619. * @param space The space that the rotation should be in.
  33620. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33621. * @param result The vector3 that the rotation should be copied to.
  33622. */
  33623. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  33624. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33625. var quat = BABYLON.Tmp.Quaternion[0];
  33626. this.getRotationQuaternionToRef(space, mesh, quat);
  33627. quat.toEulerAnglesToRef(result);
  33628. };
  33629. /**
  33630. * Get the quaternion rotation of the bone in either local or world space.
  33631. * @param space The space that the rotation should be in.
  33632. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33633. * @returns The quaternion rotation
  33634. */
  33635. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  33636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33637. var result = BABYLON.Quaternion.Identity();
  33638. this.getRotationQuaternionToRef(space, mesh, result);
  33639. return result;
  33640. };
  33641. /**
  33642. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  33643. * @param space The space that the rotation should be in.
  33644. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33645. * @param result The quaternion that the rotation should be copied to.
  33646. */
  33647. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  33648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33649. if (space == BABYLON.Space.LOCAL) {
  33650. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33651. }
  33652. else {
  33653. var mat = BABYLON.Tmp.Matrix[0];
  33654. var amat = this.getAbsoluteTransform();
  33655. if (mesh) {
  33656. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33657. }
  33658. else {
  33659. mat.copyFrom(amat);
  33660. }
  33661. mat.m[0] *= this._scalingDeterminant;
  33662. mat.m[1] *= this._scalingDeterminant;
  33663. mat.m[2] *= this._scalingDeterminant;
  33664. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33665. }
  33666. };
  33667. /**
  33668. * Get the rotation matrix of the bone in local or world space.
  33669. * @param space The space that the rotation should be in.
  33670. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33671. * @returns The rotation matrix
  33672. */
  33673. Bone.prototype.getRotationMatrix = function (space, mesh) {
  33674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33675. var result = BABYLON.Matrix.Identity();
  33676. this.getRotationMatrixToRef(space, mesh, result);
  33677. return result;
  33678. };
  33679. /**
  33680. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  33681. * @param space The space that the rotation should be in.
  33682. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33683. * @param result The quaternion that the rotation should be copied to.
  33684. */
  33685. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  33686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33687. if (space == BABYLON.Space.LOCAL) {
  33688. this.getLocalMatrix().getRotationMatrixToRef(result);
  33689. }
  33690. else {
  33691. var mat = BABYLON.Tmp.Matrix[0];
  33692. var amat = this.getAbsoluteTransform();
  33693. if (mesh) {
  33694. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33695. }
  33696. else {
  33697. mat.copyFrom(amat);
  33698. }
  33699. mat.m[0] *= this._scalingDeterminant;
  33700. mat.m[1] *= this._scalingDeterminant;
  33701. mat.m[2] *= this._scalingDeterminant;
  33702. mat.getRotationMatrixToRef(result);
  33703. }
  33704. };
  33705. /**
  33706. * Get the world position of a point that is in the local space of the bone.
  33707. * @param position The local position
  33708. * @param mesh The mesh that this bone is attached to.
  33709. * @returns The world position
  33710. */
  33711. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  33712. var result = BABYLON.Vector3.Zero();
  33713. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  33714. return result;
  33715. };
  33716. /**
  33717. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  33718. * @param position The local position
  33719. * @param mesh The mesh that this bone is attached to.
  33720. * @param result The vector3 that the world position should be copied to.
  33721. */
  33722. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  33723. this._skeleton.computeAbsoluteTransforms();
  33724. var tmat = BABYLON.Tmp.Matrix[0];
  33725. if (mesh) {
  33726. tmat.copyFrom(this.getAbsoluteTransform());
  33727. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33728. }
  33729. else {
  33730. tmat = this.getAbsoluteTransform();
  33731. }
  33732. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33733. };
  33734. /**
  33735. * Get the local position of a point that is in world space.
  33736. * @param position The world position
  33737. * @param mesh The mesh that this bone is attached to.
  33738. * @returns The local position
  33739. */
  33740. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  33741. var result = BABYLON.Vector3.Zero();
  33742. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  33743. return result;
  33744. };
  33745. /**
  33746. * Get the local position of a point that is in world space and copy it to the result param.
  33747. * @param position The world position
  33748. * @param mesh The mesh that this bone is attached to.
  33749. * @param result The vector3 that the local position should be copied to.
  33750. */
  33751. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  33752. this._skeleton.computeAbsoluteTransforms();
  33753. var tmat = BABYLON.Tmp.Matrix[0];
  33754. tmat.copyFrom(this.getAbsoluteTransform());
  33755. if (mesh) {
  33756. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33757. }
  33758. tmat.invert();
  33759. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33760. };
  33761. return Bone;
  33762. }(BABYLON.Node));
  33763. BABYLON.Bone = Bone;
  33764. })(BABYLON || (BABYLON = {}));
  33765. //# sourceMappingURL=babylon.bone.js.map
  33766. var BABYLON;
  33767. (function (BABYLON) {
  33768. var BoneIKController = (function () {
  33769. function BoneIKController(mesh, bone, options) {
  33770. this.targetPosition = BABYLON.Vector3.Zero();
  33771. this.poleTargetPosition = BABYLON.Vector3.Zero();
  33772. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  33773. this.poleAngle = 0;
  33774. this.slerpAmount = 1;
  33775. this._bone1Quat = BABYLON.Quaternion.Identity();
  33776. this._bone1Mat = BABYLON.Matrix.Identity();
  33777. this._bone2Ang = Math.PI;
  33778. this._maxAngle = Math.PI;
  33779. this._tmpVec1 = BABYLON.Vector3.Zero();
  33780. this._tmpVec2 = BABYLON.Vector3.Zero();
  33781. this._tmpVec3 = BABYLON.Vector3.Zero();
  33782. this._tmpVec4 = BABYLON.Vector3.Zero();
  33783. this._tmpVec5 = BABYLON.Vector3.Zero();
  33784. this._tmpMat1 = BABYLON.Matrix.Identity();
  33785. this._tmpMat2 = BABYLON.Matrix.Identity();
  33786. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  33787. this._rightHandedSystem = false;
  33788. this._bendAxis = BABYLON.Vector3.Right();
  33789. this._slerping = false;
  33790. this._adjustRoll = 0;
  33791. this._bone2 = bone;
  33792. this._bone1 = bone.getParent();
  33793. this.mesh = mesh;
  33794. var bonePos = bone.getPosition();
  33795. if (bone.getAbsoluteTransform().determinant() > 0) {
  33796. this._rightHandedSystem = true;
  33797. this._bendAxis.x = 0;
  33798. this._bendAxis.y = 0;
  33799. this._bendAxis.z = -1;
  33800. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  33801. this._adjustRoll = Math.PI * .5;
  33802. this._bendAxis.z = 1;
  33803. }
  33804. }
  33805. if (this._bone1.length) {
  33806. var boneScale1 = this._bone1.getScale();
  33807. var boneScale2 = this._bone2.getScale();
  33808. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  33809. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  33810. }
  33811. else if (this._bone1.children[0]) {
  33812. mesh.computeWorldMatrix(true);
  33813. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  33814. var pos2 = this._bone2.getAbsolutePosition(mesh);
  33815. var pos3 = this._bone1.getAbsolutePosition(mesh);
  33816. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  33817. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  33818. }
  33819. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  33820. this.maxAngle = Math.PI;
  33821. if (options) {
  33822. if (options.targetMesh) {
  33823. this.targetMesh = options.targetMesh;
  33824. this.targetMesh.computeWorldMatrix(true);
  33825. }
  33826. if (options.poleTargetMesh) {
  33827. this.poleTargetMesh = options.poleTargetMesh;
  33828. this.poleTargetMesh.computeWorldMatrix(true);
  33829. }
  33830. else if (options.poleTargetBone) {
  33831. this.poleTargetBone = options.poleTargetBone;
  33832. }
  33833. else if (this._bone1.getParent()) {
  33834. this.poleTargetBone = this._bone1.getParent();
  33835. }
  33836. if (options.poleTargetLocalOffset) {
  33837. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  33838. }
  33839. if (options.poleAngle) {
  33840. this.poleAngle = options.poleAngle;
  33841. }
  33842. if (options.bendAxis) {
  33843. this._bendAxis.copyFrom(options.bendAxis);
  33844. }
  33845. if (options.maxAngle) {
  33846. this.maxAngle = options.maxAngle;
  33847. }
  33848. if (options.slerpAmount) {
  33849. this.slerpAmount = options.slerpAmount;
  33850. }
  33851. }
  33852. }
  33853. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  33854. get: function () {
  33855. return this._maxAngle;
  33856. },
  33857. set: function (value) {
  33858. this._setMaxAngle(value);
  33859. },
  33860. enumerable: true,
  33861. configurable: true
  33862. });
  33863. BoneIKController.prototype._setMaxAngle = function (ang) {
  33864. if (ang < 0) {
  33865. ang = 0;
  33866. }
  33867. if (ang > Math.PI || ang == undefined) {
  33868. ang = Math.PI;
  33869. }
  33870. this._maxAngle = ang;
  33871. var a = this._bone1Length;
  33872. var b = this._bone2Length;
  33873. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  33874. };
  33875. BoneIKController.prototype.update = function () {
  33876. var bone1 = this._bone1;
  33877. var target = this.targetPosition;
  33878. var poleTarget = this.poleTargetPosition;
  33879. var mat1 = this._tmpMat1;
  33880. var mat2 = this._tmpMat2;
  33881. if (this.targetMesh) {
  33882. target.copyFrom(this.targetMesh.getAbsolutePosition());
  33883. }
  33884. if (this.poleTargetBone) {
  33885. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  33886. }
  33887. else if (this.poleTargetMesh) {
  33888. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  33889. }
  33890. var bonePos = this._tmpVec1;
  33891. var zaxis = this._tmpVec2;
  33892. var xaxis = this._tmpVec3;
  33893. var yaxis = this._tmpVec4;
  33894. var upAxis = this._tmpVec5;
  33895. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  33896. poleTarget.subtractToRef(bonePos, upAxis);
  33897. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  33898. upAxis.y = 1;
  33899. }
  33900. else {
  33901. upAxis.normalize();
  33902. }
  33903. target.subtractToRef(bonePos, yaxis);
  33904. yaxis.normalize();
  33905. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  33906. zaxis.normalize();
  33907. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  33908. xaxis.normalize();
  33909. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  33910. var a = this._bone1Length;
  33911. var b = this._bone2Length;
  33912. var c = BABYLON.Vector3.Distance(bonePos, target);
  33913. if (this._maxReach > 0) {
  33914. c = Math.min(this._maxReach, c);
  33915. }
  33916. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  33917. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  33918. if (acosa > 1) {
  33919. acosa = 1;
  33920. }
  33921. if (acosb > 1) {
  33922. acosb = 1;
  33923. }
  33924. if (acosa < -1) {
  33925. acosa = -1;
  33926. }
  33927. if (acosb < -1) {
  33928. acosb = -1;
  33929. }
  33930. var angA = Math.acos(acosa);
  33931. var angB = Math.acos(acosb);
  33932. var angC = -angA - angB;
  33933. if (this._rightHandedSystem) {
  33934. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  33935. mat2.multiplyToRef(mat1, mat1);
  33936. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  33937. mat2.multiplyToRef(mat1, mat1);
  33938. }
  33939. else {
  33940. this._tmpVec1.copyFrom(this._bendAxis);
  33941. this._tmpVec1.x *= -1;
  33942. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  33943. mat2.multiplyToRef(mat1, mat1);
  33944. }
  33945. if (this.poleAngle) {
  33946. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  33947. mat1.multiplyToRef(mat2, mat1);
  33948. }
  33949. if (this.slerpAmount < 1) {
  33950. if (!this._slerping) {
  33951. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  33952. }
  33953. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  33954. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  33955. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  33956. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  33957. this._slerping = true;
  33958. }
  33959. else {
  33960. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  33961. this._bone1Mat.copyFrom(mat1);
  33962. this._slerping = false;
  33963. }
  33964. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  33965. this._bone2Ang = angC;
  33966. };
  33967. return BoneIKController;
  33968. }());
  33969. BABYLON.BoneIKController = BoneIKController;
  33970. })(BABYLON || (BABYLON = {}));
  33971. //# sourceMappingURL=babylon.boneIKController.js.map
  33972. var BABYLON;
  33973. (function (BABYLON) {
  33974. var BoneLookController = (function () {
  33975. function BoneLookController(mesh, bone, target, options) {
  33976. this.upAxis = BABYLON.Vector3.Up();
  33977. this.adjustYaw = 0;
  33978. this.adjustPitch = 0;
  33979. this.adjustRoll = 0;
  33980. this._tmpVec1 = BABYLON.Vector3.Zero();
  33981. this._tmpVec2 = BABYLON.Vector3.Zero();
  33982. this._tmpVec3 = BABYLON.Vector3.Zero();
  33983. this._tmpVec4 = BABYLON.Vector3.Zero();
  33984. this._tmpMat1 = BABYLON.Matrix.Identity();
  33985. this._tmpMat2 = BABYLON.Matrix.Identity();
  33986. this.mesh = mesh;
  33987. this.bone = bone;
  33988. this.target = target;
  33989. if (options) {
  33990. if (options.adjustYaw) {
  33991. this.adjustYaw = options.adjustYaw;
  33992. }
  33993. if (options.adjustPitch) {
  33994. this.adjustPitch = options.adjustPitch;
  33995. }
  33996. if (options.adjustRoll) {
  33997. this.adjustRoll = options.adjustRoll;
  33998. }
  33999. }
  34000. }
  34001. BoneLookController.prototype.update = function () {
  34002. var bone = this.bone;
  34003. var target = this.target;
  34004. var bonePos = this._tmpVec1;
  34005. var zaxis = this._tmpVec2;
  34006. var xaxis = this._tmpVec3;
  34007. var yaxis = this._tmpVec4;
  34008. var mat1 = this._tmpMat1;
  34009. var mat2 = this._tmpMat2;
  34010. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34011. target.subtractToRef(bonePos, zaxis);
  34012. zaxis.normalize();
  34013. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  34014. xaxis.normalize();
  34015. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  34016. yaxis.normalize();
  34017. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34018. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  34019. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  34020. mat2.multiplyToRef(mat1, mat1);
  34021. }
  34022. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34023. };
  34024. return BoneLookController;
  34025. }());
  34026. BABYLON.BoneLookController = BoneLookController;
  34027. })(BABYLON || (BABYLON = {}));
  34028. //# sourceMappingURL=babylon.boneLookController.js.map
  34029. var BABYLON;
  34030. (function (BABYLON) {
  34031. var Skeleton = (function () {
  34032. function Skeleton(name, id, scene) {
  34033. this.name = name;
  34034. this.id = id;
  34035. this.bones = new Array();
  34036. this.needInitialSkinMatrix = false;
  34037. this._isDirty = true;
  34038. this._meshesWithPoseMatrix = new Array();
  34039. this._identity = BABYLON.Matrix.Identity();
  34040. this._ranges = {};
  34041. this._lastAbsoluteTransformsUpdateId = -1;
  34042. this.bones = [];
  34043. this._scene = scene;
  34044. scene.skeletons.push(this);
  34045. //make sure it will recalculate the matrix next time prepare is called.
  34046. this._isDirty = true;
  34047. }
  34048. // Members
  34049. Skeleton.prototype.getTransformMatrices = function (mesh) {
  34050. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  34051. return mesh._bonesTransformMatrices;
  34052. }
  34053. if (!this._transformMatrices) {
  34054. this.prepare();
  34055. }
  34056. return this._transformMatrices;
  34057. };
  34058. Skeleton.prototype.getScene = function () {
  34059. return this._scene;
  34060. };
  34061. // Methods
  34062. /**
  34063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34064. */
  34065. Skeleton.prototype.toString = function (fullDetails) {
  34066. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  34067. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34068. if (fullDetails) {
  34069. ret += ", Ranges: {";
  34070. var first = true;
  34071. for (var name_1 in this._ranges) {
  34072. if (first) {
  34073. ret += ", ";
  34074. first = false;
  34075. }
  34076. ret += name_1;
  34077. }
  34078. ret += "}";
  34079. }
  34080. return ret;
  34081. };
  34082. /**
  34083. * Get bone's index searching by name
  34084. * @param {string} name is bone's name to search for
  34085. * @return {number} Indice of the bone. Returns -1 if not found
  34086. */
  34087. Skeleton.prototype.getBoneIndexByName = function (name) {
  34088. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  34089. if (this.bones[boneIndex].name === name) {
  34090. return boneIndex;
  34091. }
  34092. }
  34093. return -1;
  34094. };
  34095. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  34096. // check name not already in use
  34097. if (!this._ranges[name]) {
  34098. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  34099. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34100. if (this.bones[i].animations[0]) {
  34101. this.bones[i].animations[0].createRange(name, from, to);
  34102. }
  34103. }
  34104. }
  34105. };
  34106. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  34107. if (deleteFrames === void 0) { deleteFrames = true; }
  34108. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34109. if (this.bones[i].animations[0]) {
  34110. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  34111. }
  34112. }
  34113. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34114. };
  34115. Skeleton.prototype.getAnimationRange = function (name) {
  34116. return this._ranges[name];
  34117. };
  34118. /**
  34119. * Returns as an Array, all AnimationRanges defined on this skeleton
  34120. */
  34121. Skeleton.prototype.getAnimationRanges = function () {
  34122. var animationRanges = [];
  34123. var name;
  34124. var i = 0;
  34125. for (name in this._ranges) {
  34126. animationRanges[i] = this._ranges[name];
  34127. i++;
  34128. }
  34129. return animationRanges;
  34130. };
  34131. /**
  34132. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  34133. */
  34134. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  34135. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  34136. if (this._ranges[name] || !source.getAnimationRange(name)) {
  34137. return false;
  34138. }
  34139. var ret = true;
  34140. var frameOffset = this._getHighestAnimationFrame() + 1;
  34141. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  34142. var boneDict = {};
  34143. var sourceBones = source.bones;
  34144. var nBones;
  34145. var i;
  34146. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  34147. boneDict[sourceBones[i].name] = sourceBones[i];
  34148. }
  34149. if (this.bones.length !== sourceBones.length) {
  34150. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  34151. ret = false;
  34152. }
  34153. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  34154. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  34155. var boneName = this.bones[i].name;
  34156. var sourceBone = boneDict[boneName];
  34157. if (sourceBone) {
  34158. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  34159. }
  34160. else {
  34161. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  34162. ret = false;
  34163. }
  34164. }
  34165. // do not call createAnimationRange(), since it also is done to bones, which was already done
  34166. var range = source.getAnimationRange(name);
  34167. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  34168. return ret;
  34169. };
  34170. Skeleton.prototype.returnToRest = function () {
  34171. for (var index = 0; index < this.bones.length; index++) {
  34172. this.bones[index].returnToRest();
  34173. }
  34174. };
  34175. Skeleton.prototype._getHighestAnimationFrame = function () {
  34176. var ret = 0;
  34177. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34178. if (this.bones[i].animations[0]) {
  34179. var highest = this.bones[i].animations[0].getHighestFrame();
  34180. if (ret < highest) {
  34181. ret = highest;
  34182. }
  34183. }
  34184. }
  34185. return ret;
  34186. };
  34187. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  34188. var range = this.getAnimationRange(name);
  34189. if (!range) {
  34190. return null;
  34191. }
  34192. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  34193. };
  34194. Skeleton.prototype._markAsDirty = function () {
  34195. this._isDirty = true;
  34196. };
  34197. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  34198. this._meshesWithPoseMatrix.push(mesh);
  34199. };
  34200. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  34201. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  34202. if (index > -1) {
  34203. this._meshesWithPoseMatrix.splice(index, 1);
  34204. }
  34205. };
  34206. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  34207. for (var index = 0; index < this.bones.length; index++) {
  34208. var bone = this.bones[index];
  34209. var parentBone = bone.getParent();
  34210. if (parentBone) {
  34211. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  34212. }
  34213. else {
  34214. if (initialSkinMatrix) {
  34215. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  34216. }
  34217. else {
  34218. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  34219. }
  34220. }
  34221. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  34222. }
  34223. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  34224. };
  34225. Skeleton.prototype.prepare = function () {
  34226. if (!this._isDirty) {
  34227. return;
  34228. }
  34229. if (this.needInitialSkinMatrix) {
  34230. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  34231. var mesh = this._meshesWithPoseMatrix[index];
  34232. var poseMatrix = mesh.getPoseMatrix();
  34233. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  34234. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34235. }
  34236. if (this._synchronizedWithMesh !== mesh) {
  34237. this._synchronizedWithMesh = mesh;
  34238. // Prepare bones
  34239. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  34240. var bone = this.bones[boneIndex];
  34241. if (!bone.getParent()) {
  34242. var matrix = bone.getBaseMatrix();
  34243. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  34244. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  34245. }
  34246. }
  34247. }
  34248. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  34249. }
  34250. }
  34251. else {
  34252. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  34253. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34254. }
  34255. this._computeTransformMatrices(this._transformMatrices, null);
  34256. }
  34257. this._isDirty = false;
  34258. this._scene._activeBones.addCount(this.bones.length, false);
  34259. };
  34260. Skeleton.prototype.getAnimatables = function () {
  34261. if (!this._animatables || this._animatables.length !== this.bones.length) {
  34262. this._animatables = [];
  34263. for (var index = 0; index < this.bones.length; index++) {
  34264. this._animatables.push(this.bones[index]);
  34265. }
  34266. }
  34267. return this._animatables;
  34268. };
  34269. Skeleton.prototype.clone = function (name, id) {
  34270. var result = new Skeleton(name, id || name, this._scene);
  34271. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34272. for (var index = 0; index < this.bones.length; index++) {
  34273. var source = this.bones[index];
  34274. var parentBone = null;
  34275. if (source.getParent()) {
  34276. var parentIndex = this.bones.indexOf(source.getParent());
  34277. parentBone = result.bones[parentIndex];
  34278. }
  34279. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  34280. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  34281. }
  34282. if (this._ranges) {
  34283. result._ranges = {};
  34284. for (var rangeName in this._ranges) {
  34285. result._ranges[rangeName] = this._ranges[rangeName].clone();
  34286. }
  34287. }
  34288. this._isDirty = true;
  34289. return result;
  34290. };
  34291. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  34292. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  34293. this.bones.forEach(function (bone) {
  34294. bone.animations.forEach(function (animation) {
  34295. animation.enableBlending = true;
  34296. animation.blendingSpeed = blendingSpeed;
  34297. });
  34298. });
  34299. };
  34300. Skeleton.prototype.dispose = function () {
  34301. this._meshesWithPoseMatrix = [];
  34302. // Animations
  34303. this.getScene().stopAnimation(this);
  34304. // Remove from scene
  34305. this.getScene().removeSkeleton(this);
  34306. };
  34307. Skeleton.prototype.serialize = function () {
  34308. var serializationObject = {};
  34309. serializationObject.name = this.name;
  34310. serializationObject.id = this.id;
  34311. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  34312. serializationObject.bones = [];
  34313. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34314. for (var index = 0; index < this.bones.length; index++) {
  34315. var bone = this.bones[index];
  34316. var serializedBone = {
  34317. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  34318. name: bone.name,
  34319. matrix: bone.getLocalMatrix().toArray(),
  34320. rest: bone.getRestPose().toArray()
  34321. };
  34322. serializationObject.bones.push(serializedBone);
  34323. if (bone.length) {
  34324. serializedBone.length = bone.length;
  34325. }
  34326. if (bone.animations && bone.animations.length > 0) {
  34327. serializedBone.animation = bone.animations[0].serialize();
  34328. }
  34329. serializationObject.ranges = [];
  34330. for (var name in this._ranges) {
  34331. var range = {};
  34332. range.name = name;
  34333. range.from = this._ranges[name].from;
  34334. range.to = this._ranges[name].to;
  34335. serializationObject.ranges.push(range);
  34336. }
  34337. }
  34338. return serializationObject;
  34339. };
  34340. Skeleton.Parse = function (parsedSkeleton, scene) {
  34341. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  34342. if (parsedSkeleton.dimensionsAtRest) {
  34343. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  34344. }
  34345. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  34346. var index;
  34347. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  34348. var parsedBone = parsedSkeleton.bones[index];
  34349. var parentBone = null;
  34350. if (parsedBone.parentBoneIndex > -1) {
  34351. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  34352. }
  34353. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  34354. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  34355. if (parsedBone.length) {
  34356. bone.length = parsedBone.length;
  34357. }
  34358. if (parsedBone.animation) {
  34359. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  34360. }
  34361. }
  34362. // placed after bones, so createAnimationRange can cascade down
  34363. if (parsedSkeleton.ranges) {
  34364. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  34365. var data = parsedSkeleton.ranges[index];
  34366. skeleton.createAnimationRange(data.name, data.from, data.to);
  34367. }
  34368. }
  34369. return skeleton;
  34370. };
  34371. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  34372. if (forceUpdate === void 0) { forceUpdate = false; }
  34373. var renderId = this._scene.getRenderId();
  34374. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  34375. this.bones[0].computeAbsoluteTransforms();
  34376. this._lastAbsoluteTransformsUpdateId = renderId;
  34377. }
  34378. };
  34379. Skeleton.prototype.getPoseMatrix = function () {
  34380. var poseMatrix;
  34381. if (this._meshesWithPoseMatrix.length > 0) {
  34382. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  34383. }
  34384. return poseMatrix;
  34385. };
  34386. return Skeleton;
  34387. }());
  34388. BABYLON.Skeleton = Skeleton;
  34389. })(BABYLON || (BABYLON = {}));
  34390. //# sourceMappingURL=babylon.skeleton.js.map
  34391. var BABYLON;
  34392. (function (BABYLON) {
  34393. var PostProcess = (function () {
  34394. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  34395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34396. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34397. this.name = name;
  34398. this.width = -1;
  34399. this.height = -1;
  34400. /*
  34401. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34402. Can only be used on a single postprocess or on the last one of a chain.
  34403. */
  34404. this.enablePixelPerfectMode = false;
  34405. this._reusable = false;
  34406. this._textures = new BABYLON.SmartArray(2);
  34407. this._currentRenderTextureInd = 0;
  34408. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34409. // Events
  34410. /**
  34411. * An event triggered when the postprocess is activated.
  34412. * @type {BABYLON.Observable}
  34413. */
  34414. this.onActivateObservable = new BABYLON.Observable();
  34415. /**
  34416. * An event triggered when the postprocess changes its size.
  34417. * @type {BABYLON.Observable}
  34418. */
  34419. this.onSizeChangedObservable = new BABYLON.Observable();
  34420. /**
  34421. * An event triggered when the postprocess applies its effect.
  34422. * @type {BABYLON.Observable}
  34423. */
  34424. this.onApplyObservable = new BABYLON.Observable();
  34425. /**
  34426. * An event triggered before rendering the postprocess
  34427. * @type {BABYLON.Observable}
  34428. */
  34429. this.onBeforeRenderObservable = new BABYLON.Observable();
  34430. /**
  34431. * An event triggered after rendering the postprocess
  34432. * @type {BABYLON.Observable}
  34433. */
  34434. this.onAfterRenderObservable = new BABYLON.Observable();
  34435. if (camera != null) {
  34436. this._camera = camera;
  34437. this._scene = camera.getScene();
  34438. camera.attachPostProcess(this);
  34439. this._engine = this._scene.getEngine();
  34440. }
  34441. else {
  34442. this._engine = engine;
  34443. }
  34444. this._options = options;
  34445. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34446. this._reusable = reusable || false;
  34447. this._textureType = textureType;
  34448. this._samplers = samplers || [];
  34449. this._samplers.push("textureSampler");
  34450. this._fragmentUrl = fragmentUrl;
  34451. this._parameters = parameters || [];
  34452. this._parameters.push("scale");
  34453. this.updateEffect(defines);
  34454. }
  34455. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34456. set: function (callback) {
  34457. if (this._onActivateObserver) {
  34458. this.onActivateObservable.remove(this._onActivateObserver);
  34459. }
  34460. this._onActivateObserver = this.onActivateObservable.add(callback);
  34461. },
  34462. enumerable: true,
  34463. configurable: true
  34464. });
  34465. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34466. set: function (callback) {
  34467. if (this._onSizeChangedObserver) {
  34468. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34469. }
  34470. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34471. },
  34472. enumerable: true,
  34473. configurable: true
  34474. });
  34475. Object.defineProperty(PostProcess.prototype, "onApply", {
  34476. set: function (callback) {
  34477. if (this._onApplyObserver) {
  34478. this.onApplyObservable.remove(this._onApplyObserver);
  34479. }
  34480. this._onApplyObserver = this.onApplyObservable.add(callback);
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34486. set: function (callback) {
  34487. if (this._onBeforeRenderObserver) {
  34488. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34489. }
  34490. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34491. },
  34492. enumerable: true,
  34493. configurable: true
  34494. });
  34495. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34496. set: function (callback) {
  34497. if (this._onAfterRenderObserver) {
  34498. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34499. }
  34500. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34501. },
  34502. enumerable: true,
  34503. configurable: true
  34504. });
  34505. PostProcess.prototype.updateEffect = function (defines) {
  34506. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  34507. };
  34508. PostProcess.prototype.isReusable = function () {
  34509. return this._reusable;
  34510. };
  34511. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34512. PostProcess.prototype.markTextureDirty = function () {
  34513. this.width = -1;
  34514. };
  34515. PostProcess.prototype.activate = function (camera, sourceTexture) {
  34516. camera = camera || this._camera;
  34517. var scene = camera.getScene();
  34518. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  34519. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34520. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34521. var desiredWidth = this._options.width || requiredWidth;
  34522. var desiredHeight = this._options.height || requiredHeight;
  34523. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  34524. if (!this._options.width) {
  34525. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  34526. }
  34527. if (!this._options.height) {
  34528. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  34529. }
  34530. }
  34531. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34532. if (this._textures.length > 0) {
  34533. for (var i = 0; i < this._textures.length; i++) {
  34534. this._engine._releaseTexture(this._textures.data[i]);
  34535. }
  34536. this._textures.reset();
  34537. }
  34538. this.width = desiredWidth;
  34539. this.height = desiredHeight;
  34540. var textureSize = { width: this.width, height: this.height };
  34541. var textureOptions = {
  34542. generateMipMaps: false,
  34543. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  34544. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  34545. samplingMode: this.renderTargetSamplingMode,
  34546. type: this._textureType
  34547. };
  34548. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34549. if (this._reusable) {
  34550. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34551. }
  34552. this.onSizeChangedObservable.notifyObservers(this);
  34553. }
  34554. if (this.enablePixelPerfectMode) {
  34555. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  34556. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  34557. }
  34558. else {
  34559. this._scaleRatio.copyFromFloats(1, 1);
  34560. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  34561. }
  34562. this.onActivateObservable.notifyObservers(camera);
  34563. // Clear
  34564. if (this.clearColor) {
  34565. this._engine.clear(this.clearColor, true, true, true);
  34566. }
  34567. else {
  34568. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  34569. }
  34570. if (this._reusable) {
  34571. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  34572. }
  34573. };
  34574. Object.defineProperty(PostProcess.prototype, "isSupported", {
  34575. get: function () {
  34576. return this._effect.isSupported;
  34577. },
  34578. enumerable: true,
  34579. configurable: true
  34580. });
  34581. PostProcess.prototype.apply = function () {
  34582. // Check
  34583. if (!this._effect.isReady())
  34584. return null;
  34585. // States
  34586. this._engine.enableEffect(this._effect);
  34587. this._engine.setState(false);
  34588. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34589. this._engine.setDepthBuffer(false);
  34590. this._engine.setDepthWrite(false);
  34591. // Texture
  34592. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  34593. // Parameters
  34594. this._effect.setVector2("scale", this._scaleRatio);
  34595. this.onApplyObservable.notifyObservers(this._effect);
  34596. return this._effect;
  34597. };
  34598. PostProcess.prototype.dispose = function (camera) {
  34599. camera = camera || this._camera;
  34600. if (this._textures.length > 0) {
  34601. for (var i = 0; i < this._textures.length; i++) {
  34602. this._engine._releaseTexture(this._textures.data[i]);
  34603. }
  34604. this._textures.reset();
  34605. }
  34606. if (!camera) {
  34607. return;
  34608. }
  34609. camera.detachPostProcess(this);
  34610. var index = camera._postProcesses.indexOf(this);
  34611. if (index === 0 && camera._postProcesses.length > 0) {
  34612. this._camera._postProcesses[0].markTextureDirty();
  34613. }
  34614. this.onActivateObservable.clear();
  34615. this.onAfterRenderObservable.clear();
  34616. this.onApplyObservable.clear();
  34617. this.onBeforeRenderObservable.clear();
  34618. this.onSizeChangedObservable.clear();
  34619. };
  34620. return PostProcess;
  34621. }());
  34622. BABYLON.PostProcess = PostProcess;
  34623. })(BABYLON || (BABYLON = {}));
  34624. //# sourceMappingURL=babylon.postProcess.js.map
  34625. var BABYLON;
  34626. (function (BABYLON) {
  34627. var PostProcessManager = (function () {
  34628. function PostProcessManager(scene) {
  34629. this._vertexBuffers = {};
  34630. this._scene = scene;
  34631. }
  34632. PostProcessManager.prototype._prepareBuffers = function () {
  34633. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34634. return;
  34635. }
  34636. // VBO
  34637. var vertices = [];
  34638. vertices.push(1, 1);
  34639. vertices.push(-1, 1);
  34640. vertices.push(-1, -1);
  34641. vertices.push(1, -1);
  34642. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34643. // Indices
  34644. var indices = [];
  34645. indices.push(0);
  34646. indices.push(1);
  34647. indices.push(2);
  34648. indices.push(0);
  34649. indices.push(2);
  34650. indices.push(3);
  34651. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34652. };
  34653. // Methods
  34654. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  34655. var postProcesses = this._scene.activeCamera._postProcesses;
  34656. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34657. return false;
  34658. }
  34659. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  34660. return true;
  34661. };
  34662. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  34663. var engine = this._scene.getEngine();
  34664. for (var index = 0; index < postProcesses.length; index++) {
  34665. if (index < postProcesses.length - 1) {
  34666. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34667. }
  34668. else {
  34669. if (targetTexture) {
  34670. engine.bindFramebuffer(targetTexture);
  34671. }
  34672. else {
  34673. engine.restoreDefaultFramebuffer();
  34674. }
  34675. }
  34676. var pp = postProcesses[index];
  34677. var effect = pp.apply();
  34678. if (effect) {
  34679. pp.onBeforeRenderObservable.notifyObservers(effect);
  34680. // VBOs
  34681. this._prepareBuffers();
  34682. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34683. // Draw order
  34684. engine.draw(true, 0, 6);
  34685. pp.onAfterRenderObservable.notifyObservers(effect);
  34686. }
  34687. }
  34688. // Restore depth buffer
  34689. engine.setDepthBuffer(true);
  34690. engine.setDepthWrite(true);
  34691. };
  34692. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  34693. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  34694. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34695. return;
  34696. }
  34697. var engine = this._scene.getEngine();
  34698. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34699. if (index < len - 1) {
  34700. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34701. }
  34702. else {
  34703. if (targetTexture) {
  34704. engine.bindFramebuffer(targetTexture, faceIndex);
  34705. }
  34706. else {
  34707. engine.restoreDefaultFramebuffer();
  34708. }
  34709. }
  34710. if (doNotPresent) {
  34711. break;
  34712. }
  34713. var pp = postProcesses[index];
  34714. var effect = pp.apply();
  34715. if (effect) {
  34716. pp.onBeforeRenderObservable.notifyObservers(effect);
  34717. // VBOs
  34718. this._prepareBuffers();
  34719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34720. // Draw order
  34721. engine.draw(true, 0, 6);
  34722. pp.onAfterRenderObservable.notifyObservers(effect);
  34723. }
  34724. }
  34725. // Restore depth buffer
  34726. engine.setDepthBuffer(true);
  34727. engine.setDepthWrite(true);
  34728. };
  34729. PostProcessManager.prototype.dispose = function () {
  34730. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34731. if (buffer) {
  34732. buffer.dispose();
  34733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34734. }
  34735. if (this._indexBuffer) {
  34736. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34737. this._indexBuffer = null;
  34738. }
  34739. };
  34740. return PostProcessManager;
  34741. }());
  34742. BABYLON.PostProcessManager = PostProcessManager;
  34743. })(BABYLON || (BABYLON = {}));
  34744. //# sourceMappingURL=babylon.postProcessManager.js.map
  34745. var BABYLON;
  34746. (function (BABYLON) {
  34747. var PassPostProcess = (function (_super) {
  34748. __extends(PassPostProcess, _super);
  34749. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  34750. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  34751. }
  34752. return PassPostProcess;
  34753. }(BABYLON.PostProcess));
  34754. BABYLON.PassPostProcess = PassPostProcess;
  34755. })(BABYLON || (BABYLON = {}));
  34756. //# sourceMappingURL=babylon.passPostProcess.js.map
  34757. var BABYLON;
  34758. (function (BABYLON) {
  34759. /**
  34760. * This is a holder class for the physics joint created by the physics plugin.
  34761. * It holds a set of functions to control the underlying joint.
  34762. */
  34763. var PhysicsJoint = (function () {
  34764. function PhysicsJoint(type, jointData) {
  34765. this.type = type;
  34766. this.jointData = jointData;
  34767. jointData.nativeParams = jointData.nativeParams || {};
  34768. }
  34769. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  34770. get: function () {
  34771. return this._physicsJoint;
  34772. },
  34773. set: function (newJoint) {
  34774. if (this._physicsJoint) {
  34775. }
  34776. this._physicsJoint = newJoint;
  34777. },
  34778. enumerable: true,
  34779. configurable: true
  34780. });
  34781. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  34782. set: function (physicsPlugin) {
  34783. this._physicsPlugin = physicsPlugin;
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. /**
  34789. * Execute a function that is physics-plugin specific.
  34790. * @param {Function} func the function that will be executed.
  34791. * It accepts two parameters: the physics world and the physics joint.
  34792. */
  34793. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  34794. func(this._physicsPlugin.world, this._physicsJoint);
  34795. };
  34796. return PhysicsJoint;
  34797. }());
  34798. //TODO check if the native joints are the same
  34799. //Joint Types
  34800. PhysicsJoint.DistanceJoint = 0;
  34801. PhysicsJoint.HingeJoint = 1;
  34802. PhysicsJoint.BallAndSocketJoint = 2;
  34803. PhysicsJoint.WheelJoint = 3;
  34804. PhysicsJoint.SliderJoint = 4;
  34805. //OIMO
  34806. PhysicsJoint.PrismaticJoint = 5;
  34807. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  34808. PhysicsJoint.UniversalJoint = 6;
  34809. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  34810. //Cannon
  34811. //Similar to a Ball-Joint. Different in params
  34812. PhysicsJoint.PointToPointJoint = 8;
  34813. //Cannon only at the moment
  34814. PhysicsJoint.SpringJoint = 9;
  34815. PhysicsJoint.LockJoint = 10;
  34816. BABYLON.PhysicsJoint = PhysicsJoint;
  34817. /**
  34818. * A class representing a physics distance joint.
  34819. */
  34820. var DistanceJoint = (function (_super) {
  34821. __extends(DistanceJoint, _super);
  34822. function DistanceJoint(jointData) {
  34823. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  34824. }
  34825. /**
  34826. * Update the predefined distance.
  34827. */
  34828. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  34829. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  34830. };
  34831. return DistanceJoint;
  34832. }(PhysicsJoint));
  34833. BABYLON.DistanceJoint = DistanceJoint;
  34834. var MotorEnabledJoint = (function (_super) {
  34835. __extends(MotorEnabledJoint, _super);
  34836. function MotorEnabledJoint(type, jointData) {
  34837. return _super.call(this, type, jointData) || this;
  34838. }
  34839. /**
  34840. * Set the motor values.
  34841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34842. * @param {number} force the force to apply
  34843. * @param {number} maxForce max force for this motor.
  34844. */
  34845. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  34846. this._physicsPlugin.setMotor(this, force, maxForce);
  34847. };
  34848. /**
  34849. * Set the motor's limits.
  34850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34851. */
  34852. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  34853. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  34854. };
  34855. return MotorEnabledJoint;
  34856. }(PhysicsJoint));
  34857. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  34858. /**
  34859. * This class represents a single hinge physics joint
  34860. */
  34861. var HingeJoint = (function (_super) {
  34862. __extends(HingeJoint, _super);
  34863. function HingeJoint(jointData) {
  34864. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  34865. }
  34866. /**
  34867. * Set the motor values.
  34868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34869. * @param {number} force the force to apply
  34870. * @param {number} maxForce max force for this motor.
  34871. */
  34872. HingeJoint.prototype.setMotor = function (force, maxForce) {
  34873. this._physicsPlugin.setMotor(this, force, maxForce);
  34874. };
  34875. /**
  34876. * Set the motor's limits.
  34877. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34878. */
  34879. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  34880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  34881. };
  34882. return HingeJoint;
  34883. }(MotorEnabledJoint));
  34884. BABYLON.HingeJoint = HingeJoint;
  34885. /**
  34886. * This class represents a dual hinge physics joint (same as wheel joint)
  34887. */
  34888. var Hinge2Joint = (function (_super) {
  34889. __extends(Hinge2Joint, _super);
  34890. function Hinge2Joint(jointData) {
  34891. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  34892. }
  34893. /**
  34894. * Set the motor values.
  34895. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34896. * @param {number} force the force to apply
  34897. * @param {number} maxForce max force for this motor.
  34898. * @param {motorIndex} the motor's index, 0 or 1.
  34899. */
  34900. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  34901. if (motorIndex === void 0) { motorIndex = 0; }
  34902. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  34903. };
  34904. /**
  34905. * Set the motor limits.
  34906. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34907. * @param {number} upperLimit the upper limit
  34908. * @param {number} lowerLimit lower limit
  34909. * @param {motorIndex} the motor's index, 0 or 1.
  34910. */
  34911. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  34912. if (motorIndex === void 0) { motorIndex = 0; }
  34913. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  34914. };
  34915. return Hinge2Joint;
  34916. }(MotorEnabledJoint));
  34917. BABYLON.Hinge2Joint = Hinge2Joint;
  34918. })(BABYLON || (BABYLON = {}));
  34919. //# sourceMappingURL=babylon.physicsJoint.js.map
  34920. var BABYLON;
  34921. (function (BABYLON) {
  34922. var PhysicsImpostor = (function () {
  34923. function PhysicsImpostor(object, type, _options, _scene) {
  34924. if (_options === void 0) { _options = { mass: 0 }; }
  34925. var _this = this;
  34926. this.object = object;
  34927. this.type = type;
  34928. this._options = _options;
  34929. this._scene = _scene;
  34930. this._bodyUpdateRequired = false;
  34931. this._onBeforePhysicsStepCallbacks = new Array();
  34932. this._onAfterPhysicsStepCallbacks = new Array();
  34933. this._onPhysicsCollideCallbacks = [];
  34934. this._deltaPosition = BABYLON.Vector3.Zero();
  34935. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  34936. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  34937. /**
  34938. * this function is executed by the physics engine.
  34939. */
  34940. this.beforeStep = function () {
  34941. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  34942. //conjugate deltaRotation
  34943. if (_this._deltaRotationConjugated) {
  34944. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  34945. }
  34946. else {
  34947. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  34948. }
  34949. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  34950. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  34951. func(_this);
  34952. });
  34953. };
  34954. /**
  34955. * this function is executed by the physics engine.
  34956. */
  34957. this.afterStep = function () {
  34958. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  34959. func(_this);
  34960. });
  34961. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  34962. _this.object.position.addInPlace(_this._deltaPosition);
  34963. if (_this._deltaRotation) {
  34964. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  34965. }
  34966. };
  34967. /**
  34968. * Legacy collision detection event support
  34969. */
  34970. this.onCollideEvent = null;
  34971. //event and body object due to cannon's event-based architecture.
  34972. this.onCollide = function (e) {
  34973. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  34974. return;
  34975. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  34976. if (otherImpostor) {
  34977. // Legacy collision detection event support
  34978. if (_this.onCollideEvent) {
  34979. _this.onCollideEvent(_this, otherImpostor);
  34980. }
  34981. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  34982. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  34983. }).forEach(function (obj) {
  34984. obj.callback(_this, otherImpostor);
  34985. });
  34986. }
  34987. };
  34988. //sanity check!
  34989. if (!this.object) {
  34990. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  34991. return;
  34992. }
  34993. //legacy support for old syntax.
  34994. if (!this._scene && object.getScene) {
  34995. this._scene = object.getScene();
  34996. }
  34997. this._physicsEngine = this._scene.getPhysicsEngine();
  34998. if (!this._physicsEngine) {
  34999. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  35000. }
  35001. else {
  35002. //set the object's quaternion, if not set
  35003. if (!this.object.rotationQuaternion) {
  35004. if (this.object.rotation) {
  35005. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  35006. }
  35007. else {
  35008. this.object.rotationQuaternion = new BABYLON.Quaternion();
  35009. }
  35010. }
  35011. //default options params
  35012. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  35013. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  35014. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  35015. this._joints = [];
  35016. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  35017. if (!this.object.parent) {
  35018. this._init();
  35019. }
  35020. }
  35021. }
  35022. /**
  35023. * This function will completly initialize this impostor.
  35024. * It will create a new body - but only if this mesh has no parent.
  35025. * If it has, this impostor will not be used other than to define the impostor
  35026. * of the child mesh.
  35027. */
  35028. PhysicsImpostor.prototype._init = function () {
  35029. this._physicsEngine.removeImpostor(this);
  35030. this.physicsBody = null;
  35031. this._parent = this._parent || this._getPhysicsParent();
  35032. if (!this.parent) {
  35033. this._physicsEngine.addImpostor(this);
  35034. }
  35035. };
  35036. PhysicsImpostor.prototype._getPhysicsParent = function () {
  35037. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  35038. var parentMesh = this.object.parent;
  35039. return parentMesh.physicsImpostor;
  35040. }
  35041. return;
  35042. };
  35043. /**
  35044. * Should a new body be generated.
  35045. */
  35046. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  35047. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  35048. };
  35049. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  35050. this.forceUpdate();
  35051. };
  35052. /**
  35053. * Force a regeneration of this or the parent's impostor's body.
  35054. * Use under cautious - This will remove all joints already implemented.
  35055. */
  35056. PhysicsImpostor.prototype.forceUpdate = function () {
  35057. this._init();
  35058. if (this.parent) {
  35059. this.parent.forceUpdate();
  35060. }
  35061. };
  35062. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  35063. /*public get mesh(): AbstractMesh {
  35064. return this._mesh;
  35065. }*/
  35066. /**
  35067. * Gets the body that holds this impostor. Either its own, or its parent.
  35068. */
  35069. get: function () {
  35070. return this._parent ? this._parent.physicsBody : this._physicsBody;
  35071. },
  35072. /**
  35073. * Set the physics body. Used mainly by the physics engine/plugin
  35074. */
  35075. set: function (physicsBody) {
  35076. if (this._physicsBody) {
  35077. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  35078. }
  35079. this._physicsBody = physicsBody;
  35080. this.resetUpdateFlags();
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  35086. get: function () {
  35087. return this._parent;
  35088. },
  35089. set: function (value) {
  35090. this._parent = value;
  35091. },
  35092. enumerable: true,
  35093. configurable: true
  35094. });
  35095. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  35096. this._bodyUpdateRequired = false;
  35097. };
  35098. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  35099. if (this.object.getBoundingInfo) {
  35100. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  35101. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  35102. }
  35103. else {
  35104. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  35105. }
  35106. };
  35107. PhysicsImpostor.prototype.getObjectCenter = function () {
  35108. if (this.object.getBoundingInfo) {
  35109. return this.object.getBoundingInfo().boundingBox.center;
  35110. }
  35111. else {
  35112. return this.object.position;
  35113. }
  35114. };
  35115. /**
  35116. * Get a specific parametes from the options parameter.
  35117. */
  35118. PhysicsImpostor.prototype.getParam = function (paramName) {
  35119. return this._options[paramName];
  35120. };
  35121. /**
  35122. * Sets a specific parameter in the options given to the physics plugin
  35123. */
  35124. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  35125. this._options[paramName] = value;
  35126. this._bodyUpdateRequired = true;
  35127. };
  35128. /**
  35129. * Specifically change the body's mass option. Won't recreate the physics body object
  35130. */
  35131. PhysicsImpostor.prototype.setMass = function (mass) {
  35132. if (this.getParam("mass") !== mass) {
  35133. this.setParam("mass", mass);
  35134. }
  35135. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  35136. };
  35137. PhysicsImpostor.prototype.getLinearVelocity = function () {
  35138. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  35139. };
  35140. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  35141. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  35142. };
  35143. PhysicsImpostor.prototype.getAngularVelocity = function () {
  35144. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  35145. };
  35146. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  35147. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  35148. };
  35149. /**
  35150. * Execute a function with the physics plugin native code.
  35151. * Provide a function the will have two variables - the world object and the physics body object.
  35152. */
  35153. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  35154. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  35155. };
  35156. /**
  35157. * Register a function that will be executed before the physics world is stepping forward.
  35158. */
  35159. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  35160. this._onBeforePhysicsStepCallbacks.push(func);
  35161. };
  35162. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  35163. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  35164. if (index > -1) {
  35165. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  35166. }
  35167. else {
  35168. BABYLON.Tools.Warn("Function to remove was not found");
  35169. }
  35170. };
  35171. /**
  35172. * Register a function that will be executed after the physics step
  35173. */
  35174. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  35175. this._onAfterPhysicsStepCallbacks.push(func);
  35176. };
  35177. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  35178. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  35179. if (index > -1) {
  35180. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  35181. }
  35182. else {
  35183. BABYLON.Tools.Warn("Function to remove was not found");
  35184. }
  35185. };
  35186. /**
  35187. * register a function that will be executed when this impostor collides against a different body.
  35188. */
  35189. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  35190. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35191. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  35192. };
  35193. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  35194. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35195. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  35196. if (index > -1) {
  35197. this._onPhysicsCollideCallbacks.splice(index, 1);
  35198. }
  35199. else {
  35200. BABYLON.Tools.Warn("Function to remove was not found");
  35201. }
  35202. };
  35203. /**
  35204. * Apply a force
  35205. */
  35206. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  35207. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  35208. };
  35209. /**
  35210. * Apply an impulse
  35211. */
  35212. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  35213. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  35214. };
  35215. /**
  35216. * A help function to create a joint.
  35217. */
  35218. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  35219. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  35220. this.addJoint(otherImpostor, joint);
  35221. };
  35222. /**
  35223. * Add a joint to this impostor with a different impostor.
  35224. */
  35225. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  35226. this._joints.push({
  35227. otherImpostor: otherImpostor,
  35228. joint: joint
  35229. });
  35230. this._physicsEngine.addJoint(this, otherImpostor, joint);
  35231. };
  35232. /**
  35233. * Will keep this body still, in a sleep mode.
  35234. */
  35235. PhysicsImpostor.prototype.sleep = function () {
  35236. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  35237. };
  35238. /**
  35239. * Wake the body up.
  35240. */
  35241. PhysicsImpostor.prototype.wakeUp = function () {
  35242. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  35243. };
  35244. PhysicsImpostor.prototype.clone = function (newObject) {
  35245. if (!newObject)
  35246. return null;
  35247. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  35248. };
  35249. PhysicsImpostor.prototype.dispose = function () {
  35250. var _this = this;
  35251. //no dispose if no physics engine is available.
  35252. if (!this._physicsEngine) {
  35253. return;
  35254. }
  35255. this._joints.forEach(function (j) {
  35256. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  35257. });
  35258. //dispose the physics body
  35259. this._physicsEngine.removeImpostor(this);
  35260. if (this.parent) {
  35261. this.parent.forceUpdate();
  35262. }
  35263. else {
  35264. }
  35265. };
  35266. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  35267. this._deltaPosition.copyFrom(position);
  35268. };
  35269. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  35270. if (!this._deltaRotation) {
  35271. this._deltaRotation = new BABYLON.Quaternion();
  35272. }
  35273. this._deltaRotation.copyFrom(rotation);
  35274. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  35275. };
  35276. return PhysicsImpostor;
  35277. }());
  35278. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  35279. //Impostor types
  35280. PhysicsImpostor.NoImpostor = 0;
  35281. PhysicsImpostor.SphereImpostor = 1;
  35282. PhysicsImpostor.BoxImpostor = 2;
  35283. PhysicsImpostor.PlaneImpostor = 3;
  35284. PhysicsImpostor.MeshImpostor = 4;
  35285. PhysicsImpostor.CylinderImpostor = 7;
  35286. PhysicsImpostor.ParticleImpostor = 8;
  35287. PhysicsImpostor.HeightmapImpostor = 9;
  35288. BABYLON.PhysicsImpostor = PhysicsImpostor;
  35289. })(BABYLON || (BABYLON = {}));
  35290. //# sourceMappingURL=babylon.physicsImpostor.js.map
  35291. var BABYLON;
  35292. (function (BABYLON) {
  35293. var PhysicsEngine = (function () {
  35294. function PhysicsEngine(gravity, _physicsPlugin) {
  35295. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  35296. this._physicsPlugin = _physicsPlugin;
  35297. //new methods and parameters
  35298. this._impostors = [];
  35299. this._joints = [];
  35300. if (!this._physicsPlugin.isSupported()) {
  35301. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  35302. + "Please make sure it is included.");
  35303. }
  35304. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  35305. this.setGravity(gravity);
  35306. this.setTimeStep();
  35307. }
  35308. PhysicsEngine.prototype.setGravity = function (gravity) {
  35309. this.gravity = gravity;
  35310. this._physicsPlugin.setGravity(this.gravity);
  35311. };
  35312. /**
  35313. * Set the time step of the physics engine.
  35314. * default is 1/60.
  35315. * To slow it down, enter 1/600 for example.
  35316. * To speed it up, 1/30
  35317. * @param {number} newTimeStep the new timestep to apply to this world.
  35318. */
  35319. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  35320. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  35321. this._physicsPlugin.setTimeStep(newTimeStep);
  35322. };
  35323. PhysicsEngine.prototype.dispose = function () {
  35324. this._impostors.forEach(function (impostor) {
  35325. impostor.dispose();
  35326. });
  35327. this._physicsPlugin.dispose();
  35328. };
  35329. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  35330. return this._physicsPlugin.name;
  35331. };
  35332. /**
  35333. * Adding a new impostor for the impostor tracking.
  35334. * This will be done by the impostor itself.
  35335. * @param {PhysicsImpostor} impostor the impostor to add
  35336. */
  35337. PhysicsEngine.prototype.addImpostor = function (impostor) {
  35338. impostor.uniqueId = this._impostors.push(impostor);
  35339. //if no parent, generate the body
  35340. if (!impostor.parent) {
  35341. this._physicsPlugin.generatePhysicsBody(impostor);
  35342. }
  35343. };
  35344. /**
  35345. * Remove an impostor from the engine.
  35346. * This impostor and its mesh will not longer be updated by the physics engine.
  35347. * @param {PhysicsImpostor} impostor the impostor to remove
  35348. */
  35349. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  35350. var index = this._impostors.indexOf(impostor);
  35351. if (index > -1) {
  35352. var removed = this._impostors.splice(index, 1);
  35353. //Is it needed?
  35354. if (removed.length) {
  35355. //this will also remove it from the world.
  35356. removed[0].physicsBody = null;
  35357. }
  35358. }
  35359. };
  35360. /**
  35361. * Add a joint to the physics engine
  35362. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  35363. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  35364. * @param {PhysicsJoint} the joint that will connect both impostors.
  35365. */
  35366. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  35367. var impostorJoint = {
  35368. mainImpostor: mainImpostor,
  35369. connectedImpostor: connectedImpostor,
  35370. joint: joint
  35371. };
  35372. joint.physicsPlugin = this._physicsPlugin;
  35373. this._joints.push(impostorJoint);
  35374. this._physicsPlugin.generateJoint(impostorJoint);
  35375. };
  35376. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  35377. var matchingJoints = this._joints.filter(function (impostorJoint) {
  35378. return (impostorJoint.connectedImpostor === connectedImpostor
  35379. && impostorJoint.joint === joint
  35380. && impostorJoint.mainImpostor === mainImpostor);
  35381. });
  35382. if (matchingJoints.length) {
  35383. this._physicsPlugin.removeJoint(matchingJoints[0]);
  35384. }
  35385. };
  35386. /**
  35387. * Called by the scene. no need to call it.
  35388. */
  35389. PhysicsEngine.prototype._step = function (delta) {
  35390. var _this = this;
  35391. //check if any mesh has no body / requires an update
  35392. this._impostors.forEach(function (impostor) {
  35393. if (impostor.isBodyInitRequired()) {
  35394. _this._physicsPlugin.generatePhysicsBody(impostor);
  35395. }
  35396. });
  35397. if (delta > 0.1) {
  35398. delta = 0.1;
  35399. }
  35400. else if (delta <= 0) {
  35401. delta = 1.0 / 60.0;
  35402. }
  35403. this._physicsPlugin.executeStep(delta, this._impostors);
  35404. };
  35405. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  35406. return this._physicsPlugin;
  35407. };
  35408. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  35409. for (var i = 0; i < this._impostors.length; ++i) {
  35410. if (this._impostors[i].object === object) {
  35411. return this._impostors[i];
  35412. }
  35413. }
  35414. };
  35415. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  35416. for (var i = 0; i < this._impostors.length; ++i) {
  35417. if (this._impostors[i].physicsBody === body) {
  35418. return this._impostors[i];
  35419. }
  35420. }
  35421. };
  35422. return PhysicsEngine;
  35423. }());
  35424. // Statics, Legacy support.
  35425. /**
  35426. * @Deprecated
  35427. *
  35428. */
  35429. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  35430. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  35431. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  35432. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  35433. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  35434. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  35435. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  35436. PhysicsEngine.CapsuleImpostor = -1;
  35437. PhysicsEngine.ConeImpostor = -1;
  35438. PhysicsEngine.ConvexHullImpostor = -1;
  35439. PhysicsEngine.Epsilon = 0.001;
  35440. BABYLON.PhysicsEngine = PhysicsEngine;
  35441. })(BABYLON || (BABYLON = {}));
  35442. //# sourceMappingURL=babylon.physicsEngine.js.map
  35443. var BABYLON;
  35444. (function (BABYLON) {
  35445. var VertexData = (function () {
  35446. function VertexData() {
  35447. }
  35448. VertexData.prototype.set = function (data, kind) {
  35449. switch (kind) {
  35450. case BABYLON.VertexBuffer.PositionKind:
  35451. this.positions = data;
  35452. break;
  35453. case BABYLON.VertexBuffer.NormalKind:
  35454. this.normals = data;
  35455. break;
  35456. case BABYLON.VertexBuffer.UVKind:
  35457. this.uvs = data;
  35458. break;
  35459. case BABYLON.VertexBuffer.UV2Kind:
  35460. this.uvs2 = data;
  35461. break;
  35462. case BABYLON.VertexBuffer.UV3Kind:
  35463. this.uvs3 = data;
  35464. break;
  35465. case BABYLON.VertexBuffer.UV4Kind:
  35466. this.uvs4 = data;
  35467. break;
  35468. case BABYLON.VertexBuffer.UV5Kind:
  35469. this.uvs5 = data;
  35470. break;
  35471. case BABYLON.VertexBuffer.UV6Kind:
  35472. this.uvs6 = data;
  35473. break;
  35474. case BABYLON.VertexBuffer.ColorKind:
  35475. this.colors = data;
  35476. break;
  35477. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35478. this.matricesIndices = data;
  35479. break;
  35480. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35481. this.matricesWeights = data;
  35482. break;
  35483. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35484. this.matricesIndicesExtra = data;
  35485. break;
  35486. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35487. this.matricesWeightsExtra = data;
  35488. break;
  35489. }
  35490. };
  35491. /**
  35492. * Associates the vertexData to the passed Mesh.
  35493. * Sets it as updatable or not (default `false`).
  35494. * Returns the VertexData.
  35495. */
  35496. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35497. this._applyTo(mesh, updatable);
  35498. return this;
  35499. };
  35500. /**
  35501. * Associates the vertexData to the passed Geometry.
  35502. * Sets it as updatable or not (default `false`).
  35503. * Returns the VertexData.
  35504. */
  35505. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35506. this._applyTo(geometry, updatable);
  35507. return this;
  35508. };
  35509. /**
  35510. * Updates the associated mesh.
  35511. * Returns the VertexData.
  35512. */
  35513. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35514. this._update(mesh);
  35515. return this;
  35516. };
  35517. /**
  35518. * Updates the associated geometry.
  35519. * Returns the VertexData.
  35520. */
  35521. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35522. this._update(geometry);
  35523. return this;
  35524. };
  35525. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35526. if (this.positions) {
  35527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35528. }
  35529. if (this.normals) {
  35530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35531. }
  35532. if (this.uvs) {
  35533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35534. }
  35535. if (this.uvs2) {
  35536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35537. }
  35538. if (this.uvs3) {
  35539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35540. }
  35541. if (this.uvs4) {
  35542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35543. }
  35544. if (this.uvs5) {
  35545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35546. }
  35547. if (this.uvs6) {
  35548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35549. }
  35550. if (this.colors) {
  35551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35552. }
  35553. if (this.matricesIndices) {
  35554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35555. }
  35556. if (this.matricesWeights) {
  35557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35558. }
  35559. if (this.matricesIndicesExtra) {
  35560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35561. }
  35562. if (this.matricesWeightsExtra) {
  35563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35564. }
  35565. if (this.indices) {
  35566. meshOrGeometry.setIndices(this.indices);
  35567. }
  35568. return this;
  35569. };
  35570. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35571. if (this.positions) {
  35572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35573. }
  35574. if (this.normals) {
  35575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35576. }
  35577. if (this.uvs) {
  35578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35579. }
  35580. if (this.uvs2) {
  35581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35582. }
  35583. if (this.uvs3) {
  35584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35585. }
  35586. if (this.uvs4) {
  35587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35588. }
  35589. if (this.uvs5) {
  35590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35591. }
  35592. if (this.uvs6) {
  35593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35594. }
  35595. if (this.colors) {
  35596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35597. }
  35598. if (this.matricesIndices) {
  35599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35600. }
  35601. if (this.matricesWeights) {
  35602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35603. }
  35604. if (this.matricesIndicesExtra) {
  35605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35606. }
  35607. if (this.matricesWeightsExtra) {
  35608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35609. }
  35610. if (this.indices) {
  35611. meshOrGeometry.setIndices(this.indices);
  35612. }
  35613. return this;
  35614. };
  35615. /**
  35616. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35617. * Returns the VertexData.
  35618. */
  35619. VertexData.prototype.transform = function (matrix) {
  35620. var transformed = BABYLON.Vector3.Zero();
  35621. var index;
  35622. if (this.positions) {
  35623. var position = BABYLON.Vector3.Zero();
  35624. for (index = 0; index < this.positions.length; index += 3) {
  35625. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35626. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35627. this.positions[index] = transformed.x;
  35628. this.positions[index + 1] = transformed.y;
  35629. this.positions[index + 2] = transformed.z;
  35630. }
  35631. }
  35632. if (this.normals) {
  35633. var normal = BABYLON.Vector3.Zero();
  35634. for (index = 0; index < this.normals.length; index += 3) {
  35635. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35636. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35637. this.normals[index] = transformed.x;
  35638. this.normals[index + 1] = transformed.y;
  35639. this.normals[index + 2] = transformed.z;
  35640. }
  35641. }
  35642. return this;
  35643. };
  35644. /**
  35645. * Merges the passed VertexData into the current one.
  35646. * Returns the modified VertexData.
  35647. */
  35648. VertexData.prototype.merge = function (other) {
  35649. if (other.indices) {
  35650. if (!this.indices) {
  35651. this.indices = [];
  35652. }
  35653. var offset = this.positions ? this.positions.length / 3 : 0;
  35654. for (var index = 0; index < other.indices.length; index++) {
  35655. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35656. this.indices.push(other.indices[index] + offset);
  35657. }
  35658. }
  35659. this.positions = this._mergeElement(this.positions, other.positions);
  35660. this.normals = this._mergeElement(this.normals, other.normals);
  35661. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35662. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35663. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35664. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35665. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35666. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35667. this.colors = this._mergeElement(this.colors, other.colors);
  35668. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35669. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35670. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35671. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35672. return this;
  35673. };
  35674. VertexData.prototype._mergeElement = function (source, other) {
  35675. if (!other)
  35676. return source;
  35677. if (!source)
  35678. return other;
  35679. var len = other.length + source.length;
  35680. var isSrcTypedArray = source instanceof Float32Array;
  35681. var isOthTypedArray = other instanceof Float32Array;
  35682. // use non-loop method when the source is Float32Array
  35683. if (isSrcTypedArray) {
  35684. var ret32 = new Float32Array(len);
  35685. ret32.set(source);
  35686. ret32.set(other, source.length);
  35687. return ret32;
  35688. }
  35689. else if (!isOthTypedArray) {
  35690. return source.concat(other);
  35691. }
  35692. else {
  35693. var ret = source.slice(0); // copy source to a separate array
  35694. for (var i = 0, len = other.length; i < len; i++) {
  35695. ret.push(other[i]);
  35696. }
  35697. return ret;
  35698. }
  35699. };
  35700. /**
  35701. * Serializes the VertexData.
  35702. * Returns a serialized object.
  35703. */
  35704. VertexData.prototype.serialize = function () {
  35705. var serializationObject = this.serialize();
  35706. if (this.positions) {
  35707. serializationObject.positions = this.positions;
  35708. }
  35709. if (this.normals) {
  35710. serializationObject.normals = this.normals;
  35711. }
  35712. if (this.uvs) {
  35713. serializationObject.uvs = this.uvs;
  35714. }
  35715. if (this.uvs2) {
  35716. serializationObject.uvs2 = this.uvs2;
  35717. }
  35718. if (this.uvs3) {
  35719. serializationObject.uvs3 = this.uvs3;
  35720. }
  35721. if (this.uvs4) {
  35722. serializationObject.uvs4 = this.uvs4;
  35723. }
  35724. if (this.uvs5) {
  35725. serializationObject.uvs5 = this.uvs5;
  35726. }
  35727. if (this.uvs6) {
  35728. serializationObject.uvs6 = this.uvs6;
  35729. }
  35730. if (this.colors) {
  35731. serializationObject.colors = this.colors;
  35732. }
  35733. if (this.matricesIndices) {
  35734. serializationObject.matricesIndices = this.matricesIndices;
  35735. serializationObject.matricesIndices._isExpanded = true;
  35736. }
  35737. if (this.matricesWeights) {
  35738. serializationObject.matricesWeights = this.matricesWeights;
  35739. }
  35740. if (this.matricesIndicesExtra) {
  35741. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35742. serializationObject.matricesIndicesExtra._isExpanded = true;
  35743. }
  35744. if (this.matricesWeightsExtra) {
  35745. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35746. }
  35747. serializationObject.indices = this.indices;
  35748. return serializationObject;
  35749. };
  35750. // Statics
  35751. /**
  35752. * Returns the object VertexData associated to the passed mesh.
  35753. */
  35754. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  35755. return VertexData._ExtractFrom(mesh, copyWhenShared);
  35756. };
  35757. /**
  35758. * Returns the object VertexData associated to the passed geometry.
  35759. */
  35760. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  35761. return VertexData._ExtractFrom(geometry, copyWhenShared);
  35762. };
  35763. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  35764. var result = new VertexData();
  35765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35766. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  35767. }
  35768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35769. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  35770. }
  35771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35772. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  35773. }
  35774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35775. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  35776. }
  35777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35778. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  35779. }
  35780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35781. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  35782. }
  35783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35784. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  35785. }
  35786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35787. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  35788. }
  35789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35790. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  35791. }
  35792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35793. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  35794. }
  35795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35796. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  35797. }
  35798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35799. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  35800. }
  35801. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35802. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  35803. }
  35804. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35805. return result;
  35806. };
  35807. /**
  35808. * Creates the vertexData of the Ribbon.
  35809. */
  35810. VertexData.CreateRibbon = function (options) {
  35811. var pathArray = options.pathArray;
  35812. var closeArray = options.closeArray || false;
  35813. var closePath = options.closePath || false;
  35814. var invertUV = options.invertUV || false;
  35815. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35816. var offset = options.offset || defaultOffset;
  35817. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35818. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35819. var positions = [];
  35820. var indices = [];
  35821. var normals = [];
  35822. var uvs = [];
  35823. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35824. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35825. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35826. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35827. var minlg; // minimal length among all paths from pathArray
  35828. var lg = []; // array of path lengths : nb of vertex per path
  35829. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35830. var p; // path iterator
  35831. var i; // point iterator
  35832. var j; // point iterator
  35833. // if single path in pathArray
  35834. if (pathArray.length < 2) {
  35835. var ar1 = [];
  35836. var ar2 = [];
  35837. for (i = 0; i < pathArray[0].length - offset; i++) {
  35838. ar1.push(pathArray[0][i]);
  35839. ar2.push(pathArray[0][i + offset]);
  35840. }
  35841. pathArray = [ar1, ar2];
  35842. }
  35843. // positions and horizontal distances (u)
  35844. var idc = 0;
  35845. var closePathCorr = (closePath) ? 1 : 0;
  35846. var path;
  35847. var l;
  35848. minlg = pathArray[0].length;
  35849. var vectlg;
  35850. var dist;
  35851. for (p = 0; p < pathArray.length; p++) {
  35852. uTotalDistance[p] = 0;
  35853. us[p] = [0];
  35854. path = pathArray[p];
  35855. l = path.length;
  35856. minlg = (minlg < l) ? minlg : l;
  35857. j = 0;
  35858. while (j < l) {
  35859. positions.push(path[j].x, path[j].y, path[j].z);
  35860. if (j > 0) {
  35861. vectlg = path[j].subtract(path[j - 1]).length();
  35862. dist = vectlg + uTotalDistance[p];
  35863. us[p].push(dist);
  35864. uTotalDistance[p] = dist;
  35865. }
  35866. j++;
  35867. }
  35868. if (closePath) {
  35869. j--;
  35870. positions.push(path[0].x, path[0].y, path[0].z);
  35871. vectlg = path[j].subtract(path[0]).length();
  35872. dist = vectlg + uTotalDistance[p];
  35873. us[p].push(dist);
  35874. uTotalDistance[p] = dist;
  35875. }
  35876. lg[p] = l + closePathCorr;
  35877. idx[p] = idc;
  35878. idc += (l + closePathCorr);
  35879. }
  35880. // vertical distances (v)
  35881. var path1;
  35882. var path2;
  35883. var vertex1;
  35884. var vertex2;
  35885. for (i = 0; i < minlg + closePathCorr; i++) {
  35886. vTotalDistance[i] = 0;
  35887. vs[i] = [0];
  35888. for (p = 0; p < pathArray.length - 1; p++) {
  35889. path1 = pathArray[p];
  35890. path2 = pathArray[p + 1];
  35891. if (i === minlg) {
  35892. vertex1 = path1[0];
  35893. vertex2 = path2[0];
  35894. }
  35895. else {
  35896. vertex1 = path1[i];
  35897. vertex2 = path2[i];
  35898. }
  35899. vectlg = vertex2.subtract(vertex1).length();
  35900. dist = vectlg + vTotalDistance[i];
  35901. vs[i].push(dist);
  35902. vTotalDistance[i] = dist;
  35903. }
  35904. if (closeArray) {
  35905. path1 = pathArray[p];
  35906. path2 = pathArray[0];
  35907. if (i === minlg) {
  35908. vertex2 = path2[0];
  35909. }
  35910. vectlg = vertex2.subtract(vertex1).length();
  35911. dist = vectlg + vTotalDistance[i];
  35912. vTotalDistance[i] = dist;
  35913. }
  35914. }
  35915. // uvs
  35916. var u;
  35917. var v;
  35918. for (p = 0; p < pathArray.length; p++) {
  35919. for (i = 0; i < minlg + closePathCorr; i++) {
  35920. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35921. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35922. if (invertUV) {
  35923. uvs.push(v, u);
  35924. }
  35925. else {
  35926. uvs.push(u, v);
  35927. }
  35928. }
  35929. }
  35930. // indices
  35931. p = 0; // path index
  35932. var pi = 0; // positions array index
  35933. var l1 = lg[p] - 1; // path1 length
  35934. var l2 = lg[p + 1] - 1; // path2 length
  35935. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35936. var shft = idx[1] - idx[0]; // shift
  35937. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35938. while (pi <= min && p < path1nb) {
  35939. // 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
  35940. indices.push(pi, pi + shft, pi + 1);
  35941. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35942. pi += 1;
  35943. if (pi === min) {
  35944. p++;
  35945. if (p === lg.length - 1) {
  35946. shft = idx[0] - idx[p];
  35947. l1 = lg[p] - 1;
  35948. l2 = lg[0] - 1;
  35949. }
  35950. else {
  35951. shft = idx[p + 1] - idx[p];
  35952. l1 = lg[p] - 1;
  35953. l2 = lg[p + 1] - 1;
  35954. }
  35955. pi = idx[p];
  35956. min = (l1 < l2) ? l1 + pi : l2 + pi;
  35957. }
  35958. }
  35959. // normals
  35960. VertexData.ComputeNormals(positions, indices, normals);
  35961. if (closePath) {
  35962. var indexFirst = 0;
  35963. var indexLast = 0;
  35964. for (p = 0; p < pathArray.length; p++) {
  35965. indexFirst = idx[p] * 3;
  35966. if (p + 1 < pathArray.length) {
  35967. indexLast = (idx[p + 1] - 1) * 3;
  35968. }
  35969. else {
  35970. indexLast = normals.length - 3;
  35971. }
  35972. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  35973. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  35974. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  35975. normals[indexLast] = normals[indexFirst];
  35976. normals[indexLast + 1] = normals[indexFirst + 1];
  35977. normals[indexLast + 2] = normals[indexFirst + 2];
  35978. }
  35979. }
  35980. // sides
  35981. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  35982. // Result
  35983. var vertexData = new VertexData();
  35984. vertexData.indices = indices;
  35985. vertexData.positions = positions;
  35986. vertexData.normals = normals;
  35987. vertexData.uvs = uvs;
  35988. if (closePath) {
  35989. vertexData._idx = idx;
  35990. }
  35991. return vertexData;
  35992. };
  35993. /**
  35994. * Creates the VertexData of the Box.
  35995. */
  35996. VertexData.CreateBox = function (options) {
  35997. var normalsSource = [
  35998. new BABYLON.Vector3(0, 0, 1),
  35999. new BABYLON.Vector3(0, 0, -1),
  36000. new BABYLON.Vector3(1, 0, 0),
  36001. new BABYLON.Vector3(-1, 0, 0),
  36002. new BABYLON.Vector3(0, 1, 0),
  36003. new BABYLON.Vector3(0, -1, 0)
  36004. ];
  36005. var indices = [];
  36006. var positions = [];
  36007. var normals = [];
  36008. var uvs = [];
  36009. var width = options.width || options.size || 1;
  36010. var height = options.height || options.size || 1;
  36011. var depth = options.depth || options.size || 1;
  36012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36013. var faceUV = options.faceUV || new Array(6);
  36014. var faceColors = options.faceColors;
  36015. var colors = [];
  36016. // default face colors and UV if undefined
  36017. for (var f = 0; f < 6; f++) {
  36018. if (faceUV[f] === undefined) {
  36019. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36020. }
  36021. if (faceColors && faceColors[f] === undefined) {
  36022. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36023. }
  36024. }
  36025. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36026. // Create each face in turn.
  36027. for (var index = 0; index < normalsSource.length; index++) {
  36028. var normal = normalsSource[index];
  36029. // Get two vectors perpendicular to the face normal and to each other.
  36030. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36031. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36032. // Six indices (two triangles) per face.
  36033. var verticesLength = positions.length / 3;
  36034. indices.push(verticesLength);
  36035. indices.push(verticesLength + 1);
  36036. indices.push(verticesLength + 2);
  36037. indices.push(verticesLength);
  36038. indices.push(verticesLength + 2);
  36039. indices.push(verticesLength + 3);
  36040. // Four vertices per face.
  36041. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36042. positions.push(vertex.x, vertex.y, vertex.z);
  36043. normals.push(normal.x, normal.y, normal.z);
  36044. uvs.push(faceUV[index].z, faceUV[index].w);
  36045. if (faceColors) {
  36046. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36047. }
  36048. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36049. positions.push(vertex.x, vertex.y, vertex.z);
  36050. normals.push(normal.x, normal.y, normal.z);
  36051. uvs.push(faceUV[index].x, faceUV[index].w);
  36052. if (faceColors) {
  36053. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36054. }
  36055. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36056. positions.push(vertex.x, vertex.y, vertex.z);
  36057. normals.push(normal.x, normal.y, normal.z);
  36058. uvs.push(faceUV[index].x, faceUV[index].y);
  36059. if (faceColors) {
  36060. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36061. }
  36062. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36063. positions.push(vertex.x, vertex.y, vertex.z);
  36064. normals.push(normal.x, normal.y, normal.z);
  36065. uvs.push(faceUV[index].z, faceUV[index].y);
  36066. if (faceColors) {
  36067. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36068. }
  36069. }
  36070. // sides
  36071. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36072. // Result
  36073. var vertexData = new VertexData();
  36074. vertexData.indices = indices;
  36075. vertexData.positions = positions;
  36076. vertexData.normals = normals;
  36077. vertexData.uvs = uvs;
  36078. if (faceColors) {
  36079. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36080. vertexData.colors = totalColors;
  36081. }
  36082. return vertexData;
  36083. };
  36084. /**
  36085. * Creates the VertexData of the Sphere.
  36086. */
  36087. VertexData.CreateSphere = function (options) {
  36088. var segments = options.segments || 32;
  36089. var diameterX = options.diameterX || options.diameter || 1;
  36090. var diameterY = options.diameterY || options.diameter || 1;
  36091. var diameterZ = options.diameterZ || options.diameter || 1;
  36092. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36093. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36094. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36095. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36096. var totalZRotationSteps = 2 + segments;
  36097. var totalYRotationSteps = 2 * totalZRotationSteps;
  36098. var indices = [];
  36099. var positions = [];
  36100. var normals = [];
  36101. var uvs = [];
  36102. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36103. var normalizedZ = zRotationStep / totalZRotationSteps;
  36104. var angleZ = normalizedZ * Math.PI * slice;
  36105. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36106. var normalizedY = yRotationStep / totalYRotationSteps;
  36107. var angleY = normalizedY * Math.PI * 2 * arc;
  36108. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36109. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36110. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36111. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36112. var vertex = complete.multiply(radius);
  36113. var normal = complete.divide(radius).normalize();
  36114. positions.push(vertex.x, vertex.y, vertex.z);
  36115. normals.push(normal.x, normal.y, normal.z);
  36116. uvs.push(normalizedY, normalizedZ);
  36117. }
  36118. if (zRotationStep > 0) {
  36119. var verticesCount = positions.length / 3;
  36120. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36121. indices.push((firstIndex));
  36122. indices.push((firstIndex + 1));
  36123. indices.push(firstIndex + totalYRotationSteps + 1);
  36124. indices.push((firstIndex + totalYRotationSteps + 1));
  36125. indices.push((firstIndex + 1));
  36126. indices.push((firstIndex + totalYRotationSteps + 2));
  36127. }
  36128. }
  36129. }
  36130. // Sides
  36131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36132. // Result
  36133. var vertexData = new VertexData();
  36134. vertexData.indices = indices;
  36135. vertexData.positions = positions;
  36136. vertexData.normals = normals;
  36137. vertexData.uvs = uvs;
  36138. return vertexData;
  36139. };
  36140. /**
  36141. * Creates the VertexData of the Cylinder or Cone.
  36142. */
  36143. VertexData.CreateCylinder = function (options) {
  36144. var height = options.height || 2;
  36145. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36146. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36147. var tessellation = options.tessellation || 24;
  36148. var subdivisions = options.subdivisions || 1;
  36149. var hasRings = options.hasRings;
  36150. var enclose = options.enclose;
  36151. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36152. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36153. var faceUV = options.faceUV || new Array(3);
  36154. var faceColors = options.faceColors;
  36155. // default face colors and UV if undefined
  36156. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36157. var ringNb = (hasRings) ? subdivisions : 1;
  36158. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36159. var f;
  36160. for (f = 0; f < surfaceNb; f++) {
  36161. if (faceColors && faceColors[f] === undefined) {
  36162. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36163. }
  36164. }
  36165. for (f = 0; f < surfaceNb; f++) {
  36166. if (faceUV && faceUV[f] === undefined) {
  36167. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36168. }
  36169. }
  36170. var indices = [];
  36171. var positions = [];
  36172. var normals = [];
  36173. var uvs = [];
  36174. var colors = [];
  36175. var angle_step = Math.PI * 2 * arc / tessellation;
  36176. var angle;
  36177. var h;
  36178. var radius;
  36179. var tan = (diameterBottom - diameterTop) / 2 / height;
  36180. var ringVertex = BABYLON.Vector3.Zero();
  36181. var ringNormal = BABYLON.Vector3.Zero();
  36182. var ringFirstVertex = BABYLON.Vector3.Zero();
  36183. var ringFirstNormal = BABYLON.Vector3.Zero();
  36184. var quadNormal = BABYLON.Vector3.Zero();
  36185. var Y = BABYLON.Axis.Y;
  36186. // positions, normals, uvs
  36187. var i;
  36188. var j;
  36189. var r;
  36190. var ringIdx = 1;
  36191. var s = 1; // surface index
  36192. var cs = 0;
  36193. var v = 0;
  36194. for (i = 0; i <= subdivisions; i++) {
  36195. h = i / subdivisions;
  36196. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36197. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36198. for (r = 0; r < ringIdx; r++) {
  36199. if (hasRings) {
  36200. s += r;
  36201. }
  36202. if (enclose) {
  36203. s += 2 * r;
  36204. }
  36205. for (j = 0; j <= tessellation; j++) {
  36206. angle = j * angle_step;
  36207. // position
  36208. ringVertex.x = Math.cos(-angle) * radius;
  36209. ringVertex.y = -height / 2 + h * height;
  36210. ringVertex.z = Math.sin(-angle) * radius;
  36211. // normal
  36212. if (diameterTop === 0 && i === subdivisions) {
  36213. // if no top cap, reuse former normals
  36214. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36215. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36216. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36217. }
  36218. else {
  36219. ringNormal.x = ringVertex.x;
  36220. ringNormal.z = ringVertex.z;
  36221. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36222. ringNormal.normalize();
  36223. }
  36224. // keep first ring vertex values for enclose
  36225. if (j === 0) {
  36226. ringFirstVertex.copyFrom(ringVertex);
  36227. ringFirstNormal.copyFrom(ringNormal);
  36228. }
  36229. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36230. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36231. if (hasRings) {
  36232. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36233. }
  36234. else {
  36235. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36236. }
  36237. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36238. if (faceColors) {
  36239. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36240. }
  36241. }
  36242. // if enclose, add four vertices and their dedicated normals
  36243. if (arc !== 1 && enclose) {
  36244. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36245. positions.push(0, ringVertex.y, 0);
  36246. positions.push(0, ringVertex.y, 0);
  36247. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36248. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36249. quadNormal.normalize();
  36250. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36251. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36252. quadNormal.normalize();
  36253. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36254. if (hasRings) {
  36255. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36256. }
  36257. else {
  36258. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36259. }
  36260. uvs.push(faceUV[s + 1].x, v);
  36261. uvs.push(faceUV[s + 1].z, v);
  36262. if (hasRings) {
  36263. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36264. }
  36265. else {
  36266. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36267. }
  36268. uvs.push(faceUV[s + 2].x, v);
  36269. uvs.push(faceUV[s + 2].z, v);
  36270. if (faceColors) {
  36271. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36272. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36273. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36274. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36275. }
  36276. }
  36277. if (cs !== s) {
  36278. cs = s;
  36279. }
  36280. }
  36281. }
  36282. // indices
  36283. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36284. var s;
  36285. i = 0;
  36286. for (s = 0; s < subdivisions; s++) {
  36287. for (j = 0; j < tessellation; j++) {
  36288. var i0 = i * (e + 1) + j;
  36289. var i1 = (i + 1) * (e + 1) + j;
  36290. var i2 = i * (e + 1) + (j + 1);
  36291. var i3 = (i + 1) * (e + 1) + (j + 1);
  36292. indices.push(i0, i1, i2);
  36293. indices.push(i3, i2, i1);
  36294. }
  36295. if (arc !== 1 && enclose) {
  36296. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36297. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36298. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36299. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36300. }
  36301. i = (hasRings) ? (i + 2) : (i + 1);
  36302. }
  36303. // Caps
  36304. var createCylinderCap = function (isTop) {
  36305. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36306. if (radius === 0) {
  36307. return;
  36308. }
  36309. // Cap positions, normals & uvs
  36310. var angle;
  36311. var circleVector;
  36312. var i;
  36313. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36314. var c;
  36315. if (faceColors) {
  36316. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36317. }
  36318. // cap center
  36319. var vbase = positions.length / 3;
  36320. var offset = isTop ? height / 2 : -height / 2;
  36321. var center = new BABYLON.Vector3(0, offset, 0);
  36322. positions.push(center.x, center.y, center.z);
  36323. normals.push(0, isTop ? 1 : -1, 0);
  36324. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36325. if (faceColors) {
  36326. colors.push(c.r, c.g, c.b, c.a);
  36327. }
  36328. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36329. for (i = 0; i <= tessellation; i++) {
  36330. angle = Math.PI * 2 * i * arc / tessellation;
  36331. var cos = Math.cos(-angle);
  36332. var sin = Math.sin(-angle);
  36333. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36334. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36335. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36336. normals.push(0, isTop ? 1 : -1, 0);
  36337. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36338. if (faceColors) {
  36339. colors.push(c.r, c.g, c.b, c.a);
  36340. }
  36341. }
  36342. // Cap indices
  36343. for (i = 0; i < tessellation; i++) {
  36344. if (!isTop) {
  36345. indices.push(vbase);
  36346. indices.push(vbase + (i + 1));
  36347. indices.push(vbase + (i + 2));
  36348. }
  36349. else {
  36350. indices.push(vbase);
  36351. indices.push(vbase + (i + 2));
  36352. indices.push(vbase + (i + 1));
  36353. }
  36354. }
  36355. };
  36356. // add caps to geometry
  36357. createCylinderCap(false);
  36358. createCylinderCap(true);
  36359. // Sides
  36360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36361. var vertexData = new VertexData();
  36362. vertexData.indices = indices;
  36363. vertexData.positions = positions;
  36364. vertexData.normals = normals;
  36365. vertexData.uvs = uvs;
  36366. if (faceColors) {
  36367. vertexData.colors = colors;
  36368. }
  36369. return vertexData;
  36370. };
  36371. /**
  36372. * Creates the VertexData of the Torus.
  36373. */
  36374. VertexData.CreateTorus = function (options) {
  36375. var indices = [];
  36376. var positions = [];
  36377. var normals = [];
  36378. var uvs = [];
  36379. var diameter = options.diameter || 1;
  36380. var thickness = options.thickness || 0.5;
  36381. var tessellation = options.tessellation || 16;
  36382. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36383. var stride = tessellation + 1;
  36384. for (var i = 0; i <= tessellation; i++) {
  36385. var u = i / tessellation;
  36386. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36387. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36388. for (var j = 0; j <= tessellation; j++) {
  36389. var v = 1 - j / tessellation;
  36390. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36391. var dx = Math.cos(innerAngle);
  36392. var dy = Math.sin(innerAngle);
  36393. // Create a vertex.
  36394. var normal = new BABYLON.Vector3(dx, dy, 0);
  36395. var position = normal.scale(thickness / 2);
  36396. var textureCoordinate = new BABYLON.Vector2(u, v);
  36397. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36398. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36399. positions.push(position.x, position.y, position.z);
  36400. normals.push(normal.x, normal.y, normal.z);
  36401. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36402. // And create indices for two triangles.
  36403. var nextI = (i + 1) % stride;
  36404. var nextJ = (j + 1) % stride;
  36405. indices.push(i * stride + j);
  36406. indices.push(i * stride + nextJ);
  36407. indices.push(nextI * stride + j);
  36408. indices.push(i * stride + nextJ);
  36409. indices.push(nextI * stride + nextJ);
  36410. indices.push(nextI * stride + j);
  36411. }
  36412. }
  36413. // Sides
  36414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36415. // Result
  36416. var vertexData = new VertexData();
  36417. vertexData.indices = indices;
  36418. vertexData.positions = positions;
  36419. vertexData.normals = normals;
  36420. vertexData.uvs = uvs;
  36421. return vertexData;
  36422. };
  36423. /**
  36424. * Creates the VertexData of the LineSystem.
  36425. */
  36426. VertexData.CreateLineSystem = function (options) {
  36427. var indices = [];
  36428. var positions = [];
  36429. var lines = options.lines;
  36430. var idx = 0;
  36431. for (var l = 0; l < lines.length; l++) {
  36432. var points = lines[l];
  36433. for (var index = 0; index < points.length; index++) {
  36434. positions.push(points[index].x, points[index].y, points[index].z);
  36435. if (index > 0) {
  36436. indices.push(idx - 1);
  36437. indices.push(idx);
  36438. }
  36439. idx++;
  36440. }
  36441. }
  36442. var vertexData = new VertexData();
  36443. vertexData.indices = indices;
  36444. vertexData.positions = positions;
  36445. return vertexData;
  36446. };
  36447. /**
  36448. * Create the VertexData of the DashedLines.
  36449. */
  36450. VertexData.CreateDashedLines = function (options) {
  36451. var dashSize = options.dashSize || 3;
  36452. var gapSize = options.gapSize || 1;
  36453. var dashNb = options.dashNb || 200;
  36454. var points = options.points;
  36455. var positions = new Array();
  36456. var indices = new Array();
  36457. var curvect = BABYLON.Vector3.Zero();
  36458. var lg = 0;
  36459. var nb = 0;
  36460. var shft = 0;
  36461. var dashshft = 0;
  36462. var curshft = 0;
  36463. var idx = 0;
  36464. var i = 0;
  36465. for (i = 0; i < points.length - 1; i++) {
  36466. points[i + 1].subtractToRef(points[i], curvect);
  36467. lg += curvect.length();
  36468. }
  36469. shft = lg / dashNb;
  36470. dashshft = dashSize * shft / (dashSize + gapSize);
  36471. for (i = 0; i < points.length - 1; i++) {
  36472. points[i + 1].subtractToRef(points[i], curvect);
  36473. nb = Math.floor(curvect.length() / shft);
  36474. curvect.normalize();
  36475. for (var j = 0; j < nb; j++) {
  36476. curshft = shft * j;
  36477. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36478. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36479. indices.push(idx, idx + 1);
  36480. idx += 2;
  36481. }
  36482. }
  36483. // Result
  36484. var vertexData = new VertexData();
  36485. vertexData.positions = positions;
  36486. vertexData.indices = indices;
  36487. return vertexData;
  36488. };
  36489. /**
  36490. * Creates the VertexData of the Ground.
  36491. */
  36492. VertexData.CreateGround = function (options) {
  36493. var indices = [];
  36494. var positions = [];
  36495. var normals = [];
  36496. var uvs = [];
  36497. var row, col;
  36498. var width = options.width || 1;
  36499. var height = options.height || 1;
  36500. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36501. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36502. for (row = 0; row <= subdivisionsY; row++) {
  36503. for (col = 0; col <= subdivisionsX; col++) {
  36504. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36505. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36506. positions.push(position.x, position.y, position.z);
  36507. normals.push(normal.x, normal.y, normal.z);
  36508. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36509. }
  36510. }
  36511. for (row = 0; row < subdivisionsY; row++) {
  36512. for (col = 0; col < subdivisionsX; col++) {
  36513. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36514. indices.push(col + 1 + row * (subdivisionsX + 1));
  36515. indices.push(col + row * (subdivisionsX + 1));
  36516. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36517. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36518. indices.push(col + row * (subdivisionsX + 1));
  36519. }
  36520. }
  36521. // Result
  36522. var vertexData = new VertexData();
  36523. vertexData.indices = indices;
  36524. vertexData.positions = positions;
  36525. vertexData.normals = normals;
  36526. vertexData.uvs = uvs;
  36527. return vertexData;
  36528. };
  36529. /**
  36530. * Creates the VertexData of the TiledGround.
  36531. */
  36532. VertexData.CreateTiledGround = function (options) {
  36533. var xmin = options.xmin || -1.0;
  36534. var zmin = options.zmin || -1.0;
  36535. var xmax = options.xmax || 1.0;
  36536. var zmax = options.zmax || 1.0;
  36537. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36538. var precision = options.precision || { w: 1, h: 1 };
  36539. var indices = [];
  36540. var positions = [];
  36541. var normals = [];
  36542. var uvs = [];
  36543. var row, col, tileRow, tileCol;
  36544. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36545. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36546. precision.w = (precision.w < 1) ? 1 : precision.w;
  36547. precision.h = (precision.h < 1) ? 1 : precision.h;
  36548. var tileSize = {
  36549. 'w': (xmax - xmin) / subdivisions.w,
  36550. 'h': (zmax - zmin) / subdivisions.h
  36551. };
  36552. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36553. // Indices
  36554. var base = positions.length / 3;
  36555. var rowLength = precision.w + 1;
  36556. for (row = 0; row < precision.h; row++) {
  36557. for (col = 0; col < precision.w; col++) {
  36558. var square = [
  36559. base + col + row * rowLength,
  36560. base + (col + 1) + row * rowLength,
  36561. base + (col + 1) + (row + 1) * rowLength,
  36562. base + col + (row + 1) * rowLength
  36563. ];
  36564. indices.push(square[1]);
  36565. indices.push(square[2]);
  36566. indices.push(square[3]);
  36567. indices.push(square[0]);
  36568. indices.push(square[1]);
  36569. indices.push(square[3]);
  36570. }
  36571. }
  36572. // Position, normals and uvs
  36573. var position = BABYLON.Vector3.Zero();
  36574. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36575. for (row = 0; row <= precision.h; row++) {
  36576. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36577. for (col = 0; col <= precision.w; col++) {
  36578. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36579. position.y = 0;
  36580. positions.push(position.x, position.y, position.z);
  36581. normals.push(normal.x, normal.y, normal.z);
  36582. uvs.push(col / precision.w, row / precision.h);
  36583. }
  36584. }
  36585. }
  36586. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36587. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36588. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36589. }
  36590. }
  36591. // Result
  36592. var vertexData = new VertexData();
  36593. vertexData.indices = indices;
  36594. vertexData.positions = positions;
  36595. vertexData.normals = normals;
  36596. vertexData.uvs = uvs;
  36597. return vertexData;
  36598. };
  36599. /**
  36600. * Creates the VertexData of the Ground designed from a heightmap.
  36601. */
  36602. VertexData.CreateGroundFromHeightMap = function (options) {
  36603. var indices = [];
  36604. var positions = [];
  36605. var normals = [];
  36606. var uvs = [];
  36607. var row, col;
  36608. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36609. // Vertices
  36610. for (row = 0; row <= options.subdivisions; row++) {
  36611. for (col = 0; col <= options.subdivisions; col++) {
  36612. 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));
  36613. // Compute height
  36614. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36615. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36616. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36617. var r = options.buffer[pos] / 255.0;
  36618. var g = options.buffer[pos + 1] / 255.0;
  36619. var b = options.buffer[pos + 2] / 255.0;
  36620. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36621. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36622. // Add vertex
  36623. positions.push(position.x, position.y, position.z);
  36624. normals.push(0, 0, 0);
  36625. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36626. }
  36627. }
  36628. // Indices
  36629. for (row = 0; row < options.subdivisions; row++) {
  36630. for (col = 0; col < options.subdivisions; col++) {
  36631. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36632. indices.push(col + 1 + row * (options.subdivisions + 1));
  36633. indices.push(col + row * (options.subdivisions + 1));
  36634. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36635. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36636. indices.push(col + row * (options.subdivisions + 1));
  36637. }
  36638. }
  36639. // Normals
  36640. VertexData.ComputeNormals(positions, indices, normals);
  36641. // Result
  36642. var vertexData = new VertexData();
  36643. vertexData.indices = indices;
  36644. vertexData.positions = positions;
  36645. vertexData.normals = normals;
  36646. vertexData.uvs = uvs;
  36647. return vertexData;
  36648. };
  36649. /**
  36650. * Creates the VertexData of the Plane.
  36651. */
  36652. VertexData.CreatePlane = function (options) {
  36653. var indices = [];
  36654. var positions = [];
  36655. var normals = [];
  36656. var uvs = [];
  36657. var width = options.width || options.size || 1;
  36658. var height = options.height || options.size || 1;
  36659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36660. // Vertices
  36661. var halfWidth = width / 2.0;
  36662. var halfHeight = height / 2.0;
  36663. positions.push(-halfWidth, -halfHeight, 0);
  36664. normals.push(0, 0, -1.0);
  36665. uvs.push(0.0, 0.0);
  36666. positions.push(halfWidth, -halfHeight, 0);
  36667. normals.push(0, 0, -1.0);
  36668. uvs.push(1.0, 0.0);
  36669. positions.push(halfWidth, halfHeight, 0);
  36670. normals.push(0, 0, -1.0);
  36671. uvs.push(1.0, 1.0);
  36672. positions.push(-halfWidth, halfHeight, 0);
  36673. normals.push(0, 0, -1.0);
  36674. uvs.push(0.0, 1.0);
  36675. // Indices
  36676. indices.push(0);
  36677. indices.push(1);
  36678. indices.push(2);
  36679. indices.push(0);
  36680. indices.push(2);
  36681. indices.push(3);
  36682. // Sides
  36683. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36684. // Result
  36685. var vertexData = new VertexData();
  36686. vertexData.indices = indices;
  36687. vertexData.positions = positions;
  36688. vertexData.normals = normals;
  36689. vertexData.uvs = uvs;
  36690. return vertexData;
  36691. };
  36692. /**
  36693. * Creates the VertexData of the Disc or regular Polygon.
  36694. */
  36695. VertexData.CreateDisc = function (options) {
  36696. var positions = [];
  36697. var indices = [];
  36698. var normals = [];
  36699. var uvs = [];
  36700. var radius = options.radius || 0.5;
  36701. var tessellation = options.tessellation || 64;
  36702. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36703. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36704. // positions and uvs
  36705. positions.push(0, 0, 0); // disc center first
  36706. uvs.push(0.5, 0.5);
  36707. var theta = Math.PI * 2 * arc;
  36708. var step = theta / tessellation;
  36709. for (var a = 0; a < theta; a += step) {
  36710. var x = Math.cos(a);
  36711. var y = Math.sin(a);
  36712. var u = (x + 1) / 2;
  36713. var v = (1 - y) / 2;
  36714. positions.push(radius * x, radius * y, 0);
  36715. uvs.push(u, v);
  36716. }
  36717. if (arc === 1) {
  36718. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36719. uvs.push(uvs[2], uvs[3]);
  36720. }
  36721. //indices
  36722. var vertexNb = positions.length / 3;
  36723. for (var i = 1; i < vertexNb - 1; i++) {
  36724. indices.push(i + 1, 0, i);
  36725. }
  36726. // result
  36727. VertexData.ComputeNormals(positions, indices, normals);
  36728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36729. var vertexData = new VertexData();
  36730. vertexData.indices = indices;
  36731. vertexData.positions = positions;
  36732. vertexData.normals = normals;
  36733. vertexData.uvs = uvs;
  36734. return vertexData;
  36735. };
  36736. /**
  36737. * Creates the VertexData of the IcoSphere.
  36738. */
  36739. VertexData.CreateIcoSphere = function (options) {
  36740. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36741. var radius = options.radius || 1;
  36742. var flat = (options.flat === undefined) ? true : options.flat;
  36743. var subdivisions = options.subdivisions || 4;
  36744. var radiusX = options.radiusX || radius;
  36745. var radiusY = options.radiusY || radius;
  36746. var radiusZ = options.radiusZ || radius;
  36747. var t = (1 + Math.sqrt(5)) / 2;
  36748. // 12 vertex x,y,z
  36749. var ico_vertices = [
  36750. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36751. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36752. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36753. ];
  36754. // index of 3 vertex makes a face of icopshere
  36755. var ico_indices = [
  36756. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36757. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36758. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36759. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36760. ];
  36761. // vertex for uv have aliased position, not for UV
  36762. var vertices_unalias_id = [
  36763. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36764. // vertex alias
  36765. 0,
  36766. 2,
  36767. 3,
  36768. 3,
  36769. 3,
  36770. 4,
  36771. 7,
  36772. 8,
  36773. 9,
  36774. 9,
  36775. 10,
  36776. 11 // 23: B + 12
  36777. ];
  36778. // uv as integer step (not pixels !)
  36779. var ico_vertexuv = [
  36780. 5, 1, 3, 1, 6, 4, 0, 0,
  36781. 5, 3, 4, 2, 2, 2, 4, 0,
  36782. 2, 0, 1, 1, 6, 0, 6, 2,
  36783. // vertex alias (for same vertex on different faces)
  36784. 0, 4,
  36785. 3, 3,
  36786. 4, 4,
  36787. 3, 1,
  36788. 4, 2,
  36789. 4, 4,
  36790. 0, 2,
  36791. 1, 1,
  36792. 2, 2,
  36793. 3, 3,
  36794. 1, 3,
  36795. 2, 4 // 23: B + 12
  36796. ];
  36797. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36798. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36799. // First island of uv mapping
  36800. // v = 4h 3+ 2
  36801. // v = 3h 9+ 4
  36802. // v = 2h 9+ 5 B
  36803. // v = 1h 9 1 0
  36804. // v = 0h 3 8 7 A
  36805. // u = 0 1 2 3 4 5 6 *a
  36806. // Second island of uv mapping
  36807. // v = 4h 0+ B+ 4+
  36808. // v = 3h A+ 2+
  36809. // v = 2h 7+ 6 3+
  36810. // v = 1h 8+ 3+
  36811. // v = 0h
  36812. // u = 0 1 2 3 4 5 6 *a
  36813. // Face layout on texture UV mapping
  36814. // ============
  36815. // \ 4 /\ 16 / ======
  36816. // \ / \ / /\ 11 /
  36817. // \/ 7 \/ / \ /
  36818. // ======= / 10 \/
  36819. // /\ 17 /\ =======
  36820. // / \ / \ \ 15 /\
  36821. // / 8 \/ 12 \ \ / \
  36822. // ============ \/ 6 \
  36823. // \ 18 /\ ============
  36824. // \ / \ \ 5 /\ 0 /
  36825. // \/ 13 \ \ / \ /
  36826. // ======= \/ 1 \/
  36827. // =============
  36828. // /\ 19 /\ 2 /\
  36829. // / \ / \ / \
  36830. // / 14 \/ 9 \/ 3 \
  36831. // ===================
  36832. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36833. var ustep = 138 / 1024;
  36834. var vstep = 239 / 1024;
  36835. var uoffset = 60 / 1024;
  36836. var voffset = 26 / 1024;
  36837. // Second island should have margin, not to touch the first island
  36838. // avoid any borderline artefact in pixel rounding
  36839. var island_u_offset = -40 / 1024;
  36840. var island_v_offset = +20 / 1024;
  36841. // face is either island 0 or 1 :
  36842. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36843. var island = [
  36844. 0, 0, 0, 0, 1,
  36845. 0, 0, 1, 1, 0,
  36846. 0, 0, 1, 1, 0,
  36847. 0, 1, 1, 1, 0 // 15 - 19
  36848. ];
  36849. var indices = [];
  36850. var positions = [];
  36851. var normals = [];
  36852. var uvs = [];
  36853. var current_indice = 0;
  36854. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36855. var face_vertex_pos = new Array(3);
  36856. var face_vertex_uv = new Array(3);
  36857. var v012;
  36858. for (v012 = 0; v012 < 3; v012++) {
  36859. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36860. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36861. }
  36862. // create all with normals
  36863. for (var face = 0; face < 20; face++) {
  36864. // 3 vertex per face
  36865. for (v012 = 0; v012 < 3; v012++) {
  36866. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36867. var v_id = ico_indices[3 * face + v012];
  36868. // vertex have 3D position (x,y,z)
  36869. 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]);
  36870. // Normalize to get normal, then scale to radius
  36871. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36872. // uv Coordinates from vertex ID
  36873. 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);
  36874. }
  36875. // Subdivide the face (interpolate pos, norm, uv)
  36876. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36877. // - norm is linear interpolation of vertex corner normal
  36878. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36879. // - uv is linear interpolation
  36880. //
  36881. // Topology is as below for sub-divide by 2
  36882. // vertex shown as v0,v1,v2
  36883. // interp index is i1 to progress in range [v0,v1[
  36884. // interp index is i2 to progress in range [v0,v2[
  36885. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36886. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36887. //
  36888. //
  36889. // i2 v2
  36890. // ^ ^
  36891. // / / \
  36892. // / / \
  36893. // / / \
  36894. // / / (0,1) \
  36895. // / #---------\
  36896. // / / \ (0,0)'/ \
  36897. // / / \ / \
  36898. // / / \ / \
  36899. // / / (0,0) \ / (1,0) \
  36900. // / #---------#---------\
  36901. // v0 v1
  36902. //
  36903. // --------------------> i1
  36904. //
  36905. // interp of (i1,i2):
  36906. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  36907. // along i1 : lerp(x0,x1, i1/(S-i2))
  36908. //
  36909. // centroid of triangle is needed to get help normal computation
  36910. // (c1,c2) are used for centroid location
  36911. var interp_vertex = function (i1, i2, c1, c2) {
  36912. // vertex is interpolated from
  36913. // - face_vertex_pos[0..2]
  36914. // - face_vertex_uv[0..2]
  36915. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  36916. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  36917. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  36918. pos_interp.normalize();
  36919. var vertex_normal;
  36920. if (flat) {
  36921. // in flat mode, recalculate normal as face centroid normal
  36922. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  36923. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  36924. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  36925. }
  36926. else {
  36927. // in smooth mode, recalculate normal from each single vertex position
  36928. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  36929. }
  36930. // Vertex normal need correction due to X,Y,Z radius scaling
  36931. vertex_normal.x /= radiusX;
  36932. vertex_normal.y /= radiusY;
  36933. vertex_normal.z /= radiusZ;
  36934. vertex_normal.normalize();
  36935. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  36936. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  36937. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  36938. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  36939. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  36940. uvs.push(uv_interp.x, uv_interp.y);
  36941. // push each vertex has member of a face
  36942. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  36943. indices.push(current_indice);
  36944. current_indice++;
  36945. };
  36946. for (var i2 = 0; i2 < subdivisions; i2++) {
  36947. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  36948. // face : (i1,i2) for /\ :
  36949. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  36950. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36951. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36952. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36953. if (i1 + i2 + 1 < subdivisions) {
  36954. // face : (i1,i2)' for \/ :
  36955. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36956. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36957. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36958. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36959. }
  36960. }
  36961. }
  36962. }
  36963. // Sides
  36964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36965. // Result
  36966. var vertexData = new VertexData();
  36967. vertexData.indices = indices;
  36968. vertexData.positions = positions;
  36969. vertexData.normals = normals;
  36970. vertexData.uvs = uvs;
  36971. return vertexData;
  36972. };
  36973. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  36974. /**
  36975. * Creates the VertexData of the Polyhedron.
  36976. */
  36977. VertexData.CreatePolyhedron = function (options) {
  36978. // provided polyhedron types :
  36979. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  36980. // 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)
  36981. var polyhedra = [];
  36982. 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]] };
  36983. 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]] };
  36984. polyhedra[2] = {
  36985. 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]],
  36986. 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]]
  36987. };
  36988. polyhedra[3] = {
  36989. 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]],
  36990. 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]]
  36991. };
  36992. polyhedra[4] = {
  36993. 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]],
  36994. 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]]
  36995. };
  36996. 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]] };
  36997. 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]] };
  36998. 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]] };
  36999. 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]] };
  37000. 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]] };
  37001. 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]] };
  37002. 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]] };
  37003. 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]] };
  37004. 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]] };
  37005. polyhedra[14] = {
  37006. 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]],
  37007. 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]]
  37008. };
  37009. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37010. var size = options.size;
  37011. var sizeX = options.sizeX || size || 1;
  37012. var sizeY = options.sizeY || size || 1;
  37013. var sizeZ = options.sizeZ || size || 1;
  37014. var data = options.custom || polyhedra[type];
  37015. var nbfaces = data.face.length;
  37016. var faceUV = options.faceUV || new Array(nbfaces);
  37017. var faceColors = options.faceColors;
  37018. var flat = (options.flat === undefined) ? true : options.flat;
  37019. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37020. var positions = [];
  37021. var indices = [];
  37022. var normals = [];
  37023. var uvs = [];
  37024. var colors = [];
  37025. var index = 0;
  37026. var faceIdx = 0; // face cursor in the array "indexes"
  37027. var indexes = [];
  37028. var i = 0;
  37029. var f = 0;
  37030. var u, v, ang, x, y, tmp;
  37031. // default face colors and UV if undefined
  37032. if (flat) {
  37033. for (f = 0; f < nbfaces; f++) {
  37034. if (faceColors && faceColors[f] === undefined) {
  37035. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37036. }
  37037. if (faceUV && faceUV[f] === undefined) {
  37038. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37039. }
  37040. }
  37041. }
  37042. if (!flat) {
  37043. for (i = 0; i < data.vertex.length; i++) {
  37044. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37045. uvs.push(0, 0);
  37046. }
  37047. for (f = 0; f < nbfaces; f++) {
  37048. for (i = 0; i < data.face[f].length - 2; i++) {
  37049. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37050. }
  37051. }
  37052. }
  37053. else {
  37054. for (f = 0; f < nbfaces; f++) {
  37055. var fl = data.face[f].length; // number of vertices of the current face
  37056. ang = 2 * Math.PI / fl;
  37057. x = 0.5 * Math.tan(ang / 2);
  37058. y = 0.5;
  37059. // positions, uvs, colors
  37060. for (i = 0; i < fl; i++) {
  37061. // positions
  37062. 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);
  37063. indexes.push(index);
  37064. index++;
  37065. // uvs
  37066. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37067. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37068. uvs.push(u, v);
  37069. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37070. y = x * Math.sin(ang) + y * Math.cos(ang);
  37071. x = tmp;
  37072. // colors
  37073. if (faceColors) {
  37074. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37075. }
  37076. }
  37077. // indices from indexes
  37078. for (i = 0; i < fl - 2; i++) {
  37079. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37080. }
  37081. faceIdx += fl;
  37082. }
  37083. }
  37084. VertexData.ComputeNormals(positions, indices, normals);
  37085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37086. var vertexData = new VertexData();
  37087. vertexData.positions = positions;
  37088. vertexData.indices = indices;
  37089. vertexData.normals = normals;
  37090. vertexData.uvs = uvs;
  37091. if (faceColors && flat) {
  37092. vertexData.colors = colors;
  37093. }
  37094. return vertexData;
  37095. };
  37096. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37097. /**
  37098. * Creates the VertexData of the Torus Knot.
  37099. */
  37100. VertexData.CreateTorusKnot = function (options) {
  37101. var indices = [];
  37102. var positions = [];
  37103. var normals = [];
  37104. var uvs = [];
  37105. var radius = options.radius || 2;
  37106. var tube = options.tube || 0.5;
  37107. var radialSegments = options.radialSegments || 32;
  37108. var tubularSegments = options.tubularSegments || 32;
  37109. var p = options.p || 2;
  37110. var q = options.q || 3;
  37111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37112. // Helper
  37113. var getPos = function (angle) {
  37114. var cu = Math.cos(angle);
  37115. var su = Math.sin(angle);
  37116. var quOverP = q / p * angle;
  37117. var cs = Math.cos(quOverP);
  37118. var tx = radius * (2 + cs) * 0.5 * cu;
  37119. var ty = radius * (2 + cs) * su * 0.5;
  37120. var tz = radius * Math.sin(quOverP) * 0.5;
  37121. return new BABYLON.Vector3(tx, ty, tz);
  37122. };
  37123. // Vertices
  37124. var i;
  37125. var j;
  37126. for (i = 0; i <= radialSegments; i++) {
  37127. var modI = i % radialSegments;
  37128. var u = modI / radialSegments * 2 * p * Math.PI;
  37129. var p1 = getPos(u);
  37130. var p2 = getPos(u + 0.01);
  37131. var tang = p2.subtract(p1);
  37132. var n = p2.add(p1);
  37133. var bitan = BABYLON.Vector3.Cross(tang, n);
  37134. n = BABYLON.Vector3.Cross(bitan, tang);
  37135. bitan.normalize();
  37136. n.normalize();
  37137. for (j = 0; j < tubularSegments; j++) {
  37138. var modJ = j % tubularSegments;
  37139. var v = modJ / tubularSegments * 2 * Math.PI;
  37140. var cx = -tube * Math.cos(v);
  37141. var cy = tube * Math.sin(v);
  37142. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37143. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37144. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37145. uvs.push(i / radialSegments);
  37146. uvs.push(j / tubularSegments);
  37147. }
  37148. }
  37149. for (i = 0; i < radialSegments; i++) {
  37150. for (j = 0; j < tubularSegments; j++) {
  37151. var jNext = (j + 1) % tubularSegments;
  37152. var a = i * tubularSegments + j;
  37153. var b = (i + 1) * tubularSegments + j;
  37154. var c = (i + 1) * tubularSegments + jNext;
  37155. var d = i * tubularSegments + jNext;
  37156. indices.push(d);
  37157. indices.push(b);
  37158. indices.push(a);
  37159. indices.push(d);
  37160. indices.push(c);
  37161. indices.push(b);
  37162. }
  37163. }
  37164. // Normals
  37165. VertexData.ComputeNormals(positions, indices, normals);
  37166. // Sides
  37167. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37168. // Result
  37169. var vertexData = new VertexData();
  37170. vertexData.indices = indices;
  37171. vertexData.positions = positions;
  37172. vertexData.normals = normals;
  37173. vertexData.uvs = uvs;
  37174. return vertexData;
  37175. };
  37176. // Tools
  37177. /**
  37178. * @param {any} - positions (number[] or Float32Array)
  37179. * @param {any} - indices (number[] or Uint16Array)
  37180. * @param {any} - normals (number[] or Float32Array)
  37181. * options (optional) :
  37182. * facetPositions : optional array of facet positions (vector3)
  37183. * facetNormals : optional array of facet normals (vector3)
  37184. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37185. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37186. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37187. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37188. * bInfo : optional bounding info, required for facetPartitioning computation
  37189. */
  37190. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37191. // temporary scalar variables
  37192. var index = 0; // facet index
  37193. var p1p2x = 0.0; // p1p2 vector x coordinate
  37194. var p1p2y = 0.0; // p1p2 vector y coordinate
  37195. var p1p2z = 0.0; // p1p2 vector z coordinate
  37196. var p3p2x = 0.0; // p3p2 vector x coordinate
  37197. var p3p2y = 0.0; // p3p2 vector y coordinate
  37198. var p3p2z = 0.0; // p3p2 vector z coordinate
  37199. var faceNormalx = 0.0; // facet normal x coordinate
  37200. var faceNormaly = 0.0; // facet normal y coordinate
  37201. var faceNormalz = 0.0; // facet normal z coordinate
  37202. var length = 0.0; // facet normal length before normalization
  37203. var v1x = 0; // vector1 x index in the positions array
  37204. var v1y = 0; // vector1 y index in the positions array
  37205. var v1z = 0; // vector1 z index in the positions array
  37206. var v2x = 0; // vector2 x index in the positions array
  37207. var v2y = 0; // vector2 y index in the positions array
  37208. var v2z = 0; // vector2 z index in the positions array
  37209. var v3x = 0; // vector3 x index in the positions array
  37210. var v3y = 0; // vector3 y index in the positions array
  37211. var v3z = 0; // vector3 z index in the positions array
  37212. var computeFacetNormals = false;
  37213. var computeFacetPositions = false;
  37214. var computeFacetPartitioning = false;
  37215. if (options) {
  37216. computeFacetNormals = (options.facetNormals) ? true : false;
  37217. computeFacetPositions = (options.facetPositions) ? true : false;
  37218. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37219. }
  37220. // facetPartitioning reinit if needed
  37221. if (computeFacetPartitioning) {
  37222. var ox = 0; // X partitioning index for facet position
  37223. var oy = 0; // Y partinioning index for facet position
  37224. var oz = 0; // Z partinioning index for facet position
  37225. var b1x = 0; // X partitioning index for facet v1 vertex
  37226. var b1y = 0; // Y partitioning index for facet v1 vertex
  37227. var b1z = 0; // z partitioning index for facet v1 vertex
  37228. var b2x = 0; // X partitioning index for facet v2 vertex
  37229. var b2y = 0; // Y partitioning index for facet v2 vertex
  37230. var b2z = 0; // Z partitioning index for facet v2 vertex
  37231. var b3x = 0; // X partitioning index for facet v3 vertex
  37232. var b3y = 0; // Y partitioning index for facet v3 vertex
  37233. var b3z = 0; // Z partitioning index for facet v3 vertex
  37234. var block_idx_o = 0; // facet barycenter block index
  37235. var block_idx_v1 = 0; // v1 vertex block index
  37236. var block_idx_v2 = 0; // v2 vertex block index
  37237. var block_idx_v3 = 0; // v3 vertex block index
  37238. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37239. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37240. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  37241. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  37242. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  37243. var subSq = options.subDiv.max * options.subDiv.max;
  37244. options.facetPartitioning.length = 0;
  37245. }
  37246. // reset the normals
  37247. for (index = 0; index < positions.length; index++) {
  37248. normals[index] = 0.0;
  37249. }
  37250. // Loop : 1 indice triplet = 1 facet
  37251. var nbFaces = indices.length / 3;
  37252. for (index = 0; index < nbFaces; index++) {
  37253. // get the indexes of the coordinates of each vertex of the facet
  37254. v1x = indices[index * 3] * 3;
  37255. v1y = v1x + 1;
  37256. v1z = v1x + 2;
  37257. v2x = indices[index * 3 + 1] * 3;
  37258. v2y = v2x + 1;
  37259. v2z = v2x + 2;
  37260. v3x = indices[index * 3 + 2] * 3;
  37261. v3y = v3x + 1;
  37262. v3z = v3x + 2;
  37263. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37264. p1p2y = positions[v1y] - positions[v2y];
  37265. p1p2z = positions[v1z] - positions[v2z];
  37266. p3p2x = positions[v3x] - positions[v2x];
  37267. p3p2y = positions[v3y] - positions[v2y];
  37268. p3p2z = positions[v3z] - positions[v2z];
  37269. // compute the face normal with the cross product
  37270. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  37271. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  37272. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  37273. // normalize this normal and store it in the array facetData
  37274. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37275. length = (length === 0) ? 1.0 : length;
  37276. faceNormalx /= length;
  37277. faceNormaly /= length;
  37278. faceNormalz /= length;
  37279. if (computeFacetNormals) {
  37280. options.facetNormals[index].x = faceNormalx;
  37281. options.facetNormals[index].y = faceNormaly;
  37282. options.facetNormals[index].z = faceNormalz;
  37283. }
  37284. if (computeFacetPositions) {
  37285. // compute and the facet barycenter coordinates in the array facetPositions
  37286. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37287. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37288. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37289. }
  37290. if (computeFacetPartitioning) {
  37291. // store the facet indexes in arrays in the main facetPartitioning array :
  37292. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37293. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37294. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37295. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37296. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37297. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37298. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37299. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37300. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37301. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37302. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37303. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37304. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37305. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37306. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37307. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37308. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37309. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37310. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37311. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37312. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37313. // push each facet index in each block containing the vertex
  37314. options.facetPartitioning[block_idx_v1].push(index);
  37315. if (block_idx_v2 != block_idx_v1) {
  37316. options.facetPartitioning[block_idx_v2].push(index);
  37317. }
  37318. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37319. options.facetPartitioning[block_idx_v3].push(index);
  37320. }
  37321. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37322. options.facetPartitioning[block_idx_o].push(index);
  37323. }
  37324. }
  37325. // compute the normals anyway
  37326. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37327. normals[v1y] += faceNormaly;
  37328. normals[v1z] += faceNormalz;
  37329. normals[v2x] += faceNormalx;
  37330. normals[v2y] += faceNormaly;
  37331. normals[v2z] += faceNormalz;
  37332. normals[v3x] += faceNormalx;
  37333. normals[v3y] += faceNormaly;
  37334. normals[v3z] += faceNormalz;
  37335. }
  37336. // last normalization of each normal
  37337. for (index = 0; index < normals.length / 3; index++) {
  37338. faceNormalx = normals[index * 3];
  37339. faceNormaly = normals[index * 3 + 1];
  37340. faceNormalz = normals[index * 3 + 2];
  37341. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37342. length = (length === 0) ? 1.0 : length;
  37343. faceNormalx /= length;
  37344. faceNormaly /= length;
  37345. faceNormalz /= length;
  37346. normals[index * 3] = faceNormalx;
  37347. normals[index * 3 + 1] = faceNormaly;
  37348. normals[index * 3 + 2] = faceNormalz;
  37349. }
  37350. };
  37351. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  37352. var li = indices.length;
  37353. var ln = normals.length;
  37354. var i;
  37355. var n;
  37356. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37357. switch (sideOrientation) {
  37358. case BABYLON.Mesh.FRONTSIDE:
  37359. // nothing changed
  37360. break;
  37361. case BABYLON.Mesh.BACKSIDE:
  37362. var tmp;
  37363. // indices
  37364. for (i = 0; i < li; i += 3) {
  37365. tmp = indices[i];
  37366. indices[i] = indices[i + 2];
  37367. indices[i + 2] = tmp;
  37368. }
  37369. // normals
  37370. for (n = 0; n < ln; n++) {
  37371. normals[n] = -normals[n];
  37372. }
  37373. break;
  37374. case BABYLON.Mesh.DOUBLESIDE:
  37375. // positions
  37376. var lp = positions.length;
  37377. var l = lp / 3;
  37378. for (var p = 0; p < lp; p++) {
  37379. positions[lp + p] = positions[p];
  37380. }
  37381. // indices
  37382. for (i = 0; i < li; i += 3) {
  37383. indices[i + li] = indices[i + 2] + l;
  37384. indices[i + 1 + li] = indices[i + 1] + l;
  37385. indices[i + 2 + li] = indices[i] + l;
  37386. }
  37387. // normals
  37388. for (n = 0; n < ln; n++) {
  37389. normals[ln + n] = -normals[n];
  37390. }
  37391. // uvs
  37392. var lu = uvs.length;
  37393. for (var u = 0; u < lu; u++) {
  37394. uvs[u + lu] = uvs[u];
  37395. }
  37396. break;
  37397. }
  37398. };
  37399. /**
  37400. * Creates a new VertexData from the imported parameters.
  37401. */
  37402. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37403. var vertexData = new VertexData();
  37404. // positions
  37405. var positions = parsedVertexData.positions;
  37406. if (positions) {
  37407. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37408. }
  37409. // normals
  37410. var normals = parsedVertexData.normals;
  37411. if (normals) {
  37412. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37413. }
  37414. // uvs
  37415. var uvs = parsedVertexData.uvs;
  37416. if (uvs) {
  37417. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37418. }
  37419. // uv2s
  37420. var uv2s = parsedVertexData.uv2s;
  37421. if (uv2s) {
  37422. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37423. }
  37424. // uv3s
  37425. var uv3s = parsedVertexData.uv3s;
  37426. if (uv3s) {
  37427. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37428. }
  37429. // uv4s
  37430. var uv4s = parsedVertexData.uv4s;
  37431. if (uv4s) {
  37432. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37433. }
  37434. // uv5s
  37435. var uv5s = parsedVertexData.uv5s;
  37436. if (uv5s) {
  37437. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37438. }
  37439. // uv6s
  37440. var uv6s = parsedVertexData.uv6s;
  37441. if (uv6s) {
  37442. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37443. }
  37444. // colors
  37445. var colors = parsedVertexData.colors;
  37446. if (colors) {
  37447. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37448. }
  37449. // matricesIndices
  37450. var matricesIndices = parsedVertexData.matricesIndices;
  37451. if (matricesIndices) {
  37452. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37453. }
  37454. // matricesWeights
  37455. var matricesWeights = parsedVertexData.matricesWeights;
  37456. if (matricesWeights) {
  37457. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37458. }
  37459. // indices
  37460. var indices = parsedVertexData.indices;
  37461. if (indices) {
  37462. vertexData.indices = indices;
  37463. }
  37464. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37465. };
  37466. return VertexData;
  37467. }());
  37468. BABYLON.VertexData = VertexData;
  37469. })(BABYLON || (BABYLON = {}));
  37470. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37471. var BABYLON;
  37472. (function (BABYLON) {
  37473. var Tags = (function () {
  37474. function Tags() {
  37475. }
  37476. Tags.EnableFor = function (obj) {
  37477. obj._tags = obj._tags || {};
  37478. obj.hasTags = function () {
  37479. return Tags.HasTags(obj);
  37480. };
  37481. obj.addTags = function (tagsString) {
  37482. return Tags.AddTagsTo(obj, tagsString);
  37483. };
  37484. obj.removeTags = function (tagsString) {
  37485. return Tags.RemoveTagsFrom(obj, tagsString);
  37486. };
  37487. obj.matchesTagsQuery = function (tagsQuery) {
  37488. return Tags.MatchesQuery(obj, tagsQuery);
  37489. };
  37490. };
  37491. Tags.DisableFor = function (obj) {
  37492. delete obj._tags;
  37493. delete obj.hasTags;
  37494. delete obj.addTags;
  37495. delete obj.removeTags;
  37496. delete obj.matchesTagsQuery;
  37497. };
  37498. Tags.HasTags = function (obj) {
  37499. if (!obj._tags) {
  37500. return false;
  37501. }
  37502. return !BABYLON.Tools.IsEmpty(obj._tags);
  37503. };
  37504. Tags.GetTags = function (obj, asString) {
  37505. if (asString === void 0) { asString = true; }
  37506. if (!obj._tags) {
  37507. return null;
  37508. }
  37509. if (asString) {
  37510. var tagsArray = [];
  37511. for (var tag in obj._tags) {
  37512. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  37513. tagsArray.push(tag);
  37514. }
  37515. }
  37516. return tagsArray.join(" ");
  37517. }
  37518. else {
  37519. return obj._tags;
  37520. }
  37521. };
  37522. // the tags 'true' and 'false' are reserved and cannot be used as tags
  37523. // a tag cannot start with '||', '&&', and '!'
  37524. // it cannot contain whitespaces
  37525. Tags.AddTagsTo = function (obj, tagsString) {
  37526. if (!tagsString) {
  37527. return;
  37528. }
  37529. if (typeof tagsString !== "string") {
  37530. return;
  37531. }
  37532. var tags = tagsString.split(" ");
  37533. tags.forEach(function (tag, index, array) {
  37534. Tags._AddTagTo(obj, tag);
  37535. });
  37536. };
  37537. Tags._AddTagTo = function (obj, tag) {
  37538. tag = tag.trim();
  37539. if (tag === "" || tag === "true" || tag === "false") {
  37540. return;
  37541. }
  37542. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  37543. return;
  37544. }
  37545. Tags.EnableFor(obj);
  37546. obj._tags[tag] = true;
  37547. };
  37548. Tags.RemoveTagsFrom = function (obj, tagsString) {
  37549. if (!Tags.HasTags(obj)) {
  37550. return;
  37551. }
  37552. var tags = tagsString.split(" ");
  37553. for (var t in tags) {
  37554. Tags._RemoveTagFrom(obj, tags[t]);
  37555. }
  37556. };
  37557. Tags._RemoveTagFrom = function (obj, tag) {
  37558. delete obj._tags[tag];
  37559. };
  37560. Tags.MatchesQuery = function (obj, tagsQuery) {
  37561. if (tagsQuery === undefined) {
  37562. return true;
  37563. }
  37564. if (tagsQuery === "") {
  37565. return Tags.HasTags(obj);
  37566. }
  37567. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  37568. };
  37569. return Tags;
  37570. }());
  37571. BABYLON.Tags = Tags;
  37572. })(BABYLON || (BABYLON = {}));
  37573. //# sourceMappingURL=babylon.tags.js.map
  37574. var BABYLON;
  37575. (function (BABYLON) {
  37576. var Internals;
  37577. (function (Internals) {
  37578. var AndOrNotEvaluator = (function () {
  37579. function AndOrNotEvaluator() {
  37580. }
  37581. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  37582. if (!query.match(/\([^\(\)]*\)/g)) {
  37583. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  37584. }
  37585. else {
  37586. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  37587. // remove parenthesis
  37588. r = r.slice(1, r.length - 1);
  37589. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  37590. });
  37591. }
  37592. if (query === "true") {
  37593. return true;
  37594. }
  37595. if (query === "false") {
  37596. return false;
  37597. }
  37598. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  37599. };
  37600. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  37601. evaluateCallback = evaluateCallback || (function (r) {
  37602. return r === "true" ? true : false;
  37603. });
  37604. var result;
  37605. var or = parenthesisContent.split("||");
  37606. for (var i in or) {
  37607. if (or.hasOwnProperty(i)) {
  37608. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  37609. var and = ori.split("&&");
  37610. if (and.length > 1) {
  37611. for (var j = 0; j < and.length; ++j) {
  37612. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  37613. if (andj !== "true" && andj !== "false") {
  37614. if (andj[0] === "!") {
  37615. result = !evaluateCallback(andj.substring(1));
  37616. }
  37617. else {
  37618. result = evaluateCallback(andj);
  37619. }
  37620. }
  37621. else {
  37622. result = andj === "true" ? true : false;
  37623. }
  37624. if (!result) {
  37625. ori = "false";
  37626. break;
  37627. }
  37628. }
  37629. }
  37630. if (result || ori === "true") {
  37631. result = true;
  37632. break;
  37633. }
  37634. // result equals false (or undefined)
  37635. if (ori !== "true" && ori !== "false") {
  37636. if (ori[0] === "!") {
  37637. result = !evaluateCallback(ori.substring(1));
  37638. }
  37639. else {
  37640. result = evaluateCallback(ori);
  37641. }
  37642. }
  37643. else {
  37644. result = ori === "true" ? true : false;
  37645. }
  37646. }
  37647. }
  37648. // the whole parenthesis scope is replaced by 'true' or 'false'
  37649. return result ? "true" : "false";
  37650. };
  37651. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  37652. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  37653. // remove whitespaces
  37654. r = r.replace(/[\s]/g, function () { return ""; });
  37655. return r.length % 2 ? "!" : "";
  37656. });
  37657. booleanString = booleanString.trim();
  37658. if (booleanString === "!true") {
  37659. booleanString = "false";
  37660. }
  37661. else if (booleanString === "!false") {
  37662. booleanString = "true";
  37663. }
  37664. return booleanString;
  37665. };
  37666. return AndOrNotEvaluator;
  37667. }());
  37668. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  37669. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37670. })(BABYLON || (BABYLON = {}));
  37671. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  37672. var BABYLON;
  37673. (function (BABYLON) {
  37674. var PostProcessRenderPass = (function () {
  37675. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  37676. this._enabled = true;
  37677. this._refCount = 0;
  37678. this._name = name;
  37679. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  37680. this.setRenderList(renderList);
  37681. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  37682. this._renderTexture.onAfterRenderObservable.add(afterRender);
  37683. this._scene = scene;
  37684. this._renderList = renderList;
  37685. }
  37686. // private
  37687. PostProcessRenderPass.prototype._incRefCount = function () {
  37688. if (this._refCount === 0) {
  37689. this._scene.customRenderTargets.push(this._renderTexture);
  37690. }
  37691. return ++this._refCount;
  37692. };
  37693. PostProcessRenderPass.prototype._decRefCount = function () {
  37694. this._refCount--;
  37695. if (this._refCount <= 0) {
  37696. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  37697. }
  37698. return this._refCount;
  37699. };
  37700. PostProcessRenderPass.prototype._update = function () {
  37701. this.setRenderList(this._renderList);
  37702. };
  37703. // public
  37704. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  37705. this._renderTexture.renderList = renderList;
  37706. };
  37707. PostProcessRenderPass.prototype.getRenderTexture = function () {
  37708. return this._renderTexture;
  37709. };
  37710. return PostProcessRenderPass;
  37711. }());
  37712. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  37713. })(BABYLON || (BABYLON = {}));
  37714. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  37715. var BABYLON;
  37716. (function (BABYLON) {
  37717. var PostProcessRenderEffect = (function () {
  37718. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  37719. this._engine = engine;
  37720. this._name = name;
  37721. this._singleInstance = singleInstance || true;
  37722. this._getPostProcess = getPostProcess;
  37723. this._cameras = [];
  37724. this._indicesForCamera = [];
  37725. this._postProcesses = {};
  37726. this._renderPasses = {};
  37727. this._renderEffectAsPasses = {};
  37728. }
  37729. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  37730. get: function () {
  37731. for (var index in this._postProcesses) {
  37732. if (!this._postProcesses[index].isSupported) {
  37733. return false;
  37734. }
  37735. }
  37736. return true;
  37737. },
  37738. enumerable: true,
  37739. configurable: true
  37740. });
  37741. PostProcessRenderEffect.prototype._update = function () {
  37742. for (var renderPassName in this._renderPasses) {
  37743. this._renderPasses[renderPassName]._update();
  37744. }
  37745. };
  37746. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  37747. this._renderPasses[renderPass._name] = renderPass;
  37748. this._linkParameters();
  37749. };
  37750. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  37751. delete this._renderPasses[renderPass._name];
  37752. this._linkParameters();
  37753. };
  37754. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  37755. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  37756. this._linkParameters();
  37757. };
  37758. PostProcessRenderEffect.prototype.getPass = function (passName) {
  37759. for (var renderPassName in this._renderPasses) {
  37760. if (renderPassName === passName) {
  37761. return this._renderPasses[passName];
  37762. }
  37763. }
  37764. };
  37765. PostProcessRenderEffect.prototype.emptyPasses = function () {
  37766. this._renderPasses = {};
  37767. this._linkParameters();
  37768. };
  37769. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  37770. var cameraKey;
  37771. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37772. for (var i = 0; i < _cam.length; i++) {
  37773. var camera = _cam[i];
  37774. var cameraName = camera.name;
  37775. if (this._singleInstance) {
  37776. cameraKey = 0;
  37777. }
  37778. else {
  37779. cameraKey = cameraName;
  37780. }
  37781. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  37782. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  37783. if (!this._indicesForCamera[cameraName]) {
  37784. this._indicesForCamera[cameraName] = [];
  37785. }
  37786. this._indicesForCamera[cameraName].push(index);
  37787. if (this._cameras.indexOf(camera) === -1) {
  37788. this._cameras[cameraName] = camera;
  37789. }
  37790. for (var passName in this._renderPasses) {
  37791. this._renderPasses[passName]._incRefCount();
  37792. }
  37793. }
  37794. this._linkParameters();
  37795. };
  37796. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  37797. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37798. for (var i = 0; i < _cam.length; i++) {
  37799. var camera = _cam[i];
  37800. var cameraName = camera.name;
  37801. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37802. var index = this._cameras.indexOf(cameraName);
  37803. this._indicesForCamera.splice(index, 1);
  37804. this._cameras.splice(index, 1);
  37805. for (var passName in this._renderPasses) {
  37806. this._renderPasses[passName]._decRefCount();
  37807. }
  37808. }
  37809. };
  37810. PostProcessRenderEffect.prototype._enable = function (cameras) {
  37811. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37812. for (var i = 0; i < _cam.length; i++) {
  37813. var camera = _cam[i];
  37814. var cameraName = camera.name;
  37815. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  37816. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  37817. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  37818. }
  37819. }
  37820. for (var passName in this._renderPasses) {
  37821. this._renderPasses[passName]._incRefCount();
  37822. }
  37823. }
  37824. };
  37825. PostProcessRenderEffect.prototype._disable = function (cameras) {
  37826. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37827. for (var i = 0; i < _cam.length; i++) {
  37828. var camera = _cam[i];
  37829. var cameraName = camera.Name;
  37830. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37831. for (var passName in this._renderPasses) {
  37832. this._renderPasses[passName]._decRefCount();
  37833. }
  37834. }
  37835. };
  37836. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  37837. if (this._singleInstance) {
  37838. return this._postProcesses[0];
  37839. }
  37840. else {
  37841. return this._postProcesses[camera.name];
  37842. }
  37843. };
  37844. PostProcessRenderEffect.prototype._linkParameters = function () {
  37845. var _this = this;
  37846. for (var index in this._postProcesses) {
  37847. if (this.applyParameters) {
  37848. this.applyParameters(this._postProcesses[index]);
  37849. }
  37850. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  37851. _this._linkTextures(effect);
  37852. });
  37853. }
  37854. };
  37855. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  37856. for (var renderPassName in this._renderPasses) {
  37857. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  37858. }
  37859. for (var renderEffectName in this._renderEffectAsPasses) {
  37860. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  37861. }
  37862. };
  37863. return PostProcessRenderEffect;
  37864. }());
  37865. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  37866. })(BABYLON || (BABYLON = {}));
  37867. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  37868. var BABYLON;
  37869. (function (BABYLON) {
  37870. var PostProcessRenderPipeline = (function () {
  37871. function PostProcessRenderPipeline(engine, name) {
  37872. this._engine = engine;
  37873. this._name = name;
  37874. this._renderEffects = {};
  37875. this._renderEffectsForIsolatedPass = {};
  37876. this._cameras = [];
  37877. }
  37878. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  37879. get: function () {
  37880. for (var renderEffectName in this._renderEffects) {
  37881. if (!this._renderEffects[renderEffectName].isSupported) {
  37882. return false;
  37883. }
  37884. }
  37885. return true;
  37886. },
  37887. enumerable: true,
  37888. configurable: true
  37889. });
  37890. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  37891. this._renderEffects[renderEffect._name] = renderEffect;
  37892. };
  37893. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  37894. var renderEffects = this._renderEffects[renderEffectName];
  37895. if (!renderEffects) {
  37896. return;
  37897. }
  37898. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  37899. };
  37900. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  37901. var renderEffects = this._renderEffects[renderEffectName];
  37902. if (!renderEffects) {
  37903. return;
  37904. }
  37905. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  37906. };
  37907. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  37908. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37909. var indicesToDelete = [];
  37910. var i;
  37911. for (i = 0; i < _cam.length; i++) {
  37912. var camera = _cam[i];
  37913. var cameraName = camera.name;
  37914. if (this._cameras.indexOf(camera) === -1) {
  37915. this._cameras[cameraName] = camera;
  37916. }
  37917. else if (unique) {
  37918. indicesToDelete.push(i);
  37919. }
  37920. }
  37921. for (i = 0; i < indicesToDelete.length; i++) {
  37922. cameras.splice(indicesToDelete[i], 1);
  37923. }
  37924. for (var renderEffectName in this._renderEffects) {
  37925. this._renderEffects[renderEffectName]._attachCameras(_cam);
  37926. }
  37927. };
  37928. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  37929. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37930. for (var renderEffectName in this._renderEffects) {
  37931. this._renderEffects[renderEffectName]._detachCameras(_cam);
  37932. }
  37933. for (var i = 0; i < _cam.length; i++) {
  37934. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  37935. }
  37936. };
  37937. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  37938. var _this = this;
  37939. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37940. var pass = null;
  37941. var renderEffectName;
  37942. for (renderEffectName in this._renderEffects) {
  37943. pass = this._renderEffects[renderEffectName].getPass(passName);
  37944. if (pass != null) {
  37945. break;
  37946. }
  37947. }
  37948. if (pass === null) {
  37949. return;
  37950. }
  37951. for (renderEffectName in this._renderEffects) {
  37952. this._renderEffects[renderEffectName]._disable(_cam);
  37953. }
  37954. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  37955. for (var i = 0; i < _cam.length; i++) {
  37956. var camera = _cam[i];
  37957. var cameraName = camera.name;
  37958. 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); });
  37959. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  37960. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  37961. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  37962. }
  37963. };
  37964. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  37965. var _this = this;
  37966. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37967. for (var i = 0; i < _cam.length; i++) {
  37968. var camera = _cam[i];
  37969. var cameraName = camera.name;
  37970. 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); });
  37971. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  37972. }
  37973. for (var renderEffectName in this._renderEffects) {
  37974. this._renderEffects[renderEffectName]._enable(_cam);
  37975. }
  37976. };
  37977. PostProcessRenderPipeline.prototype._update = function () {
  37978. for (var renderEffectName in this._renderEffects) {
  37979. this._renderEffects[renderEffectName]._update();
  37980. }
  37981. for (var i = 0; i < this._cameras.length; i++) {
  37982. var cameraName = this._cameras[i].name;
  37983. if (this._renderEffectsForIsolatedPass[cameraName]) {
  37984. this._renderEffectsForIsolatedPass[cameraName]._update();
  37985. }
  37986. }
  37987. };
  37988. PostProcessRenderPipeline.prototype.dispose = function () {
  37989. // Must be implemented by children
  37990. };
  37991. return PostProcessRenderPipeline;
  37992. }());
  37993. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  37994. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  37995. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  37996. })(BABYLON || (BABYLON = {}));
  37997. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  37998. var BABYLON;
  37999. (function (BABYLON) {
  38000. var PostProcessRenderPipelineManager = (function () {
  38001. function PostProcessRenderPipelineManager() {
  38002. this._renderPipelines = {};
  38003. }
  38004. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  38005. this._renderPipelines[renderPipeline._name] = renderPipeline;
  38006. };
  38007. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  38008. var renderPipeline = this._renderPipelines[renderPipelineName];
  38009. if (!renderPipeline) {
  38010. return;
  38011. }
  38012. renderPipeline._attachCameras(cameras, unique);
  38013. };
  38014. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  38015. var renderPipeline = this._renderPipelines[renderPipelineName];
  38016. if (!renderPipeline) {
  38017. return;
  38018. }
  38019. renderPipeline._detachCameras(cameras);
  38020. };
  38021. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38022. var renderPipeline = this._renderPipelines[renderPipelineName];
  38023. if (!renderPipeline) {
  38024. return;
  38025. }
  38026. renderPipeline._enableEffect(renderEffectName, cameras);
  38027. };
  38028. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38029. var renderPipeline = this._renderPipelines[renderPipelineName];
  38030. if (!renderPipeline) {
  38031. return;
  38032. }
  38033. renderPipeline._disableEffect(renderEffectName, cameras);
  38034. };
  38035. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  38036. var renderPipeline = this._renderPipelines[renderPipelineName];
  38037. if (!renderPipeline) {
  38038. return;
  38039. }
  38040. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  38041. };
  38042. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  38043. var renderPipeline = this._renderPipelines[renderPipelineName];
  38044. if (!renderPipeline) {
  38045. return;
  38046. }
  38047. renderPipeline._disableDisplayOnlyPass(cameras);
  38048. };
  38049. PostProcessRenderPipelineManager.prototype.update = function () {
  38050. for (var renderPipelineName in this._renderPipelines) {
  38051. var pipeline = this._renderPipelines[renderPipelineName];
  38052. if (!pipeline.isSupported) {
  38053. pipeline.dispose();
  38054. delete this._renderPipelines[renderPipelineName];
  38055. }
  38056. else {
  38057. pipeline._update();
  38058. }
  38059. }
  38060. };
  38061. return PostProcessRenderPipelineManager;
  38062. }());
  38063. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  38064. })(BABYLON || (BABYLON = {}));
  38065. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  38066. var BABYLON;
  38067. (function (BABYLON) {
  38068. var BoundingBoxRenderer = (function () {
  38069. function BoundingBoxRenderer(scene) {
  38070. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38071. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38072. this.showBackLines = true;
  38073. this.renderList = new BABYLON.SmartArray(32);
  38074. this._vertexBuffers = {};
  38075. this._scene = scene;
  38076. }
  38077. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38078. if (this._colorShader) {
  38079. return;
  38080. }
  38081. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38082. attributes: [BABYLON.VertexBuffer.PositionKind],
  38083. uniforms: ["worldViewProjection", "color"]
  38084. });
  38085. var engine = this._scene.getEngine();
  38086. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38088. 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]);
  38089. };
  38090. BoundingBoxRenderer.prototype.reset = function () {
  38091. this.renderList.reset();
  38092. };
  38093. BoundingBoxRenderer.prototype.render = function () {
  38094. if (this.renderList.length === 0) {
  38095. return;
  38096. }
  38097. this._prepareRessources();
  38098. if (!this._colorShader.isReady()) {
  38099. return;
  38100. }
  38101. var engine = this._scene.getEngine();
  38102. engine.setDepthWrite(false);
  38103. this._colorShader._preBind();
  38104. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38105. var boundingBox = this.renderList.data[boundingBoxIndex];
  38106. var min = boundingBox.minimum;
  38107. var max = boundingBox.maximum;
  38108. var diff = max.subtract(min);
  38109. var median = min.add(diff.scale(0.5));
  38110. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38111. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38112. .multiply(boundingBox.getWorldMatrix());
  38113. // VBOs
  38114. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38115. if (this.showBackLines) {
  38116. // Back
  38117. engine.setDepthFunctionToGreaterOrEqual();
  38118. this._scene.resetCachedMaterial();
  38119. this._colorShader.setColor4("color", this.backColor.toColor4());
  38120. this._colorShader.bind(worldMatrix);
  38121. // Draw order
  38122. engine.draw(false, 0, 24);
  38123. }
  38124. // Front
  38125. engine.setDepthFunctionToLess();
  38126. this._scene.resetCachedMaterial();
  38127. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38128. this._colorShader.bind(worldMatrix);
  38129. // Draw order
  38130. engine.draw(false, 0, 24);
  38131. }
  38132. this._colorShader.unbind();
  38133. engine.setDepthFunctionToLessOrEqual();
  38134. engine.setDepthWrite(true);
  38135. };
  38136. BoundingBoxRenderer.prototype.dispose = function () {
  38137. if (!this._colorShader) {
  38138. return;
  38139. }
  38140. this._colorShader.dispose();
  38141. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38142. if (buffer) {
  38143. buffer.dispose();
  38144. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38145. }
  38146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38147. };
  38148. return BoundingBoxRenderer;
  38149. }());
  38150. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38151. })(BABYLON || (BABYLON = {}));
  38152. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38153. var BABYLON;
  38154. (function (BABYLON) {
  38155. var Condition = (function () {
  38156. function Condition(actionManager) {
  38157. this._actionManager = actionManager;
  38158. }
  38159. Condition.prototype.isValid = function () {
  38160. return true;
  38161. };
  38162. Condition.prototype._getProperty = function (propertyPath) {
  38163. return this._actionManager._getProperty(propertyPath);
  38164. };
  38165. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38166. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38167. };
  38168. Condition.prototype.serialize = function () {
  38169. };
  38170. Condition.prototype._serialize = function (serializedCondition) {
  38171. return {
  38172. type: 2,
  38173. children: [],
  38174. name: serializedCondition.name,
  38175. properties: serializedCondition.properties
  38176. };
  38177. };
  38178. return Condition;
  38179. }());
  38180. BABYLON.Condition = Condition;
  38181. var ValueCondition = (function (_super) {
  38182. __extends(ValueCondition, _super);
  38183. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38184. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38185. var _this = _super.call(this, actionManager) || this;
  38186. _this.propertyPath = propertyPath;
  38187. _this.value = value;
  38188. _this.operator = operator;
  38189. _this._target = target;
  38190. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38191. _this._property = _this._getProperty(_this.propertyPath);
  38192. return _this;
  38193. }
  38194. Object.defineProperty(ValueCondition, "IsEqual", {
  38195. get: function () {
  38196. return ValueCondition._IsEqual;
  38197. },
  38198. enumerable: true,
  38199. configurable: true
  38200. });
  38201. Object.defineProperty(ValueCondition, "IsDifferent", {
  38202. get: function () {
  38203. return ValueCondition._IsDifferent;
  38204. },
  38205. enumerable: true,
  38206. configurable: true
  38207. });
  38208. Object.defineProperty(ValueCondition, "IsGreater", {
  38209. get: function () {
  38210. return ValueCondition._IsGreater;
  38211. },
  38212. enumerable: true,
  38213. configurable: true
  38214. });
  38215. Object.defineProperty(ValueCondition, "IsLesser", {
  38216. get: function () {
  38217. return ValueCondition._IsLesser;
  38218. },
  38219. enumerable: true,
  38220. configurable: true
  38221. });
  38222. // Methods
  38223. ValueCondition.prototype.isValid = function () {
  38224. switch (this.operator) {
  38225. case ValueCondition.IsGreater:
  38226. return this._effectiveTarget[this._property] > this.value;
  38227. case ValueCondition.IsLesser:
  38228. return this._effectiveTarget[this._property] < this.value;
  38229. case ValueCondition.IsEqual:
  38230. case ValueCondition.IsDifferent:
  38231. var check;
  38232. if (this.value.equals) {
  38233. check = this.value.equals(this._effectiveTarget[this._property]);
  38234. }
  38235. else {
  38236. check = this.value === this._effectiveTarget[this._property];
  38237. }
  38238. return this.operator === ValueCondition.IsEqual ? check : !check;
  38239. }
  38240. return false;
  38241. };
  38242. ValueCondition.prototype.serialize = function () {
  38243. return this._serialize({
  38244. name: "ValueCondition",
  38245. properties: [
  38246. BABYLON.Action._GetTargetProperty(this._target),
  38247. { name: "propertyPath", value: this.propertyPath },
  38248. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38249. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38250. ]
  38251. });
  38252. };
  38253. ValueCondition.GetOperatorName = function (operator) {
  38254. switch (operator) {
  38255. case ValueCondition._IsEqual: return "IsEqual";
  38256. case ValueCondition._IsDifferent: return "IsDifferent";
  38257. case ValueCondition._IsGreater: return "IsGreater";
  38258. case ValueCondition._IsLesser: return "IsLesser";
  38259. default: return "";
  38260. }
  38261. };
  38262. return ValueCondition;
  38263. }(Condition));
  38264. // Statics
  38265. ValueCondition._IsEqual = 0;
  38266. ValueCondition._IsDifferent = 1;
  38267. ValueCondition._IsGreater = 2;
  38268. ValueCondition._IsLesser = 3;
  38269. BABYLON.ValueCondition = ValueCondition;
  38270. var PredicateCondition = (function (_super) {
  38271. __extends(PredicateCondition, _super);
  38272. function PredicateCondition(actionManager, predicate) {
  38273. var _this = _super.call(this, actionManager) || this;
  38274. _this.predicate = predicate;
  38275. return _this;
  38276. }
  38277. PredicateCondition.prototype.isValid = function () {
  38278. return this.predicate();
  38279. };
  38280. return PredicateCondition;
  38281. }(Condition));
  38282. BABYLON.PredicateCondition = PredicateCondition;
  38283. var StateCondition = (function (_super) {
  38284. __extends(StateCondition, _super);
  38285. function StateCondition(actionManager, target, value) {
  38286. var _this = _super.call(this, actionManager) || this;
  38287. _this.value = value;
  38288. _this._target = target;
  38289. return _this;
  38290. }
  38291. // Methods
  38292. StateCondition.prototype.isValid = function () {
  38293. return this._target.state === this.value;
  38294. };
  38295. StateCondition.prototype.serialize = function () {
  38296. return this._serialize({
  38297. name: "StateCondition",
  38298. properties: [
  38299. BABYLON.Action._GetTargetProperty(this._target),
  38300. { name: "value", value: this.value }
  38301. ]
  38302. });
  38303. };
  38304. return StateCondition;
  38305. }(Condition));
  38306. BABYLON.StateCondition = StateCondition;
  38307. })(BABYLON || (BABYLON = {}));
  38308. //# sourceMappingURL=babylon.condition.js.map
  38309. var BABYLON;
  38310. (function (BABYLON) {
  38311. var Action = (function () {
  38312. function Action(triggerOptions, condition) {
  38313. this.triggerOptions = triggerOptions;
  38314. if (triggerOptions.parameter) {
  38315. this.trigger = triggerOptions.trigger;
  38316. this._triggerParameter = triggerOptions.parameter;
  38317. }
  38318. else {
  38319. this.trigger = triggerOptions;
  38320. }
  38321. this._nextActiveAction = this;
  38322. this._condition = condition;
  38323. }
  38324. // Methods
  38325. Action.prototype._prepare = function () {
  38326. };
  38327. Action.prototype.getTriggerParameter = function () {
  38328. return this._triggerParameter;
  38329. };
  38330. Action.prototype._executeCurrent = function (evt) {
  38331. if (this._nextActiveAction._condition) {
  38332. var condition = this._nextActiveAction._condition;
  38333. var currentRenderId = this._actionManager.getScene().getRenderId();
  38334. // We cache the current evaluation for the current frame
  38335. if (condition._evaluationId === currentRenderId) {
  38336. if (!condition._currentResult) {
  38337. return;
  38338. }
  38339. }
  38340. else {
  38341. condition._evaluationId = currentRenderId;
  38342. if (!condition.isValid()) {
  38343. condition._currentResult = false;
  38344. return;
  38345. }
  38346. condition._currentResult = true;
  38347. }
  38348. }
  38349. this._nextActiveAction.execute(evt);
  38350. this.skipToNextActiveAction();
  38351. };
  38352. Action.prototype.execute = function (evt) {
  38353. };
  38354. Action.prototype.skipToNextActiveAction = function () {
  38355. if (this._nextActiveAction._child) {
  38356. if (!this._nextActiveAction._child._actionManager) {
  38357. this._nextActiveAction._child._actionManager = this._actionManager;
  38358. }
  38359. this._nextActiveAction = this._nextActiveAction._child;
  38360. }
  38361. else {
  38362. this._nextActiveAction = this;
  38363. }
  38364. };
  38365. Action.prototype.then = function (action) {
  38366. this._child = action;
  38367. action._actionManager = this._actionManager;
  38368. action._prepare();
  38369. return action;
  38370. };
  38371. Action.prototype._getProperty = function (propertyPath) {
  38372. return this._actionManager._getProperty(propertyPath);
  38373. };
  38374. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38375. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38376. };
  38377. Action.prototype.serialize = function (parent) {
  38378. };
  38379. // Called by BABYLON.Action objects in serialize(...). Internal use
  38380. Action.prototype._serialize = function (serializedAction, parent) {
  38381. var serializationObject = {
  38382. type: 1,
  38383. children: [],
  38384. name: serializedAction.name,
  38385. properties: serializedAction.properties || []
  38386. };
  38387. // Serialize child
  38388. if (this._child) {
  38389. this._child.serialize(serializationObject);
  38390. }
  38391. // Check if "this" has a condition
  38392. if (this._condition) {
  38393. var serializedCondition = this._condition.serialize();
  38394. serializedCondition.children.push(serializationObject);
  38395. if (parent) {
  38396. parent.children.push(serializedCondition);
  38397. }
  38398. return serializedCondition;
  38399. }
  38400. if (parent) {
  38401. parent.children.push(serializationObject);
  38402. }
  38403. return serializationObject;
  38404. };
  38405. return Action;
  38406. }());
  38407. Action._SerializeValueAsString = function (value) {
  38408. if (typeof value === "number") {
  38409. return value.toString();
  38410. }
  38411. if (typeof value === "boolean") {
  38412. return value ? "true" : "false";
  38413. }
  38414. if (value instanceof BABYLON.Vector2) {
  38415. return value.x + ", " + value.y;
  38416. }
  38417. if (value instanceof BABYLON.Vector3) {
  38418. return value.x + ", " + value.y + ", " + value.z;
  38419. }
  38420. if (value instanceof BABYLON.Color3) {
  38421. return value.r + ", " + value.g + ", " + value.b;
  38422. }
  38423. if (value instanceof BABYLON.Color4) {
  38424. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38425. }
  38426. return value; // string
  38427. };
  38428. Action._GetTargetProperty = function (target) {
  38429. return {
  38430. name: "target",
  38431. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38432. : target instanceof BABYLON.Light ? "LightProperties"
  38433. : target instanceof BABYLON.Camera ? "CameraProperties"
  38434. : "SceneProperties",
  38435. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38436. };
  38437. };
  38438. BABYLON.Action = Action;
  38439. })(BABYLON || (BABYLON = {}));
  38440. //# sourceMappingURL=babylon.action.js.map
  38441. var BABYLON;
  38442. (function (BABYLON) {
  38443. /**
  38444. * ActionEvent is the event beint sent when an action is triggered.
  38445. */
  38446. var ActionEvent = (function () {
  38447. /**
  38448. * @constructor
  38449. * @param source The mesh or sprite that triggered the action.
  38450. * @param pointerX The X mouse cursor position at the time of the event
  38451. * @param pointerY The Y mouse cursor position at the time of the event
  38452. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38453. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38454. */
  38455. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38456. this.source = source;
  38457. this.pointerX = pointerX;
  38458. this.pointerY = pointerY;
  38459. this.meshUnderPointer = meshUnderPointer;
  38460. this.sourceEvent = sourceEvent;
  38461. this.additionalData = additionalData;
  38462. }
  38463. /**
  38464. * Helper function to auto-create an ActionEvent from a source mesh.
  38465. * @param source The source mesh that triggered the event
  38466. * @param evt {Event} The original (browser) event
  38467. */
  38468. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38469. var scene = source.getScene();
  38470. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38471. };
  38472. /**
  38473. * Helper function to auto-create an ActionEvent from a source mesh.
  38474. * @param source The source sprite that triggered the event
  38475. * @param scene Scene associated with the sprite
  38476. * @param evt {Event} The original (browser) event
  38477. */
  38478. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38479. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38480. };
  38481. /**
  38482. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38483. * @param scene the scene where the event occurred
  38484. * @param evt {Event} The original (browser) event
  38485. */
  38486. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38487. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38488. };
  38489. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38490. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38491. };
  38492. return ActionEvent;
  38493. }());
  38494. BABYLON.ActionEvent = ActionEvent;
  38495. /**
  38496. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38497. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38498. */
  38499. var ActionManager = (function () {
  38500. function ActionManager(scene) {
  38501. // Members
  38502. this.actions = new Array();
  38503. this.hoverCursor = '';
  38504. this._scene = scene;
  38505. scene._actionManagers.push(this);
  38506. }
  38507. Object.defineProperty(ActionManager, "NothingTrigger", {
  38508. get: function () {
  38509. return ActionManager._NothingTrigger;
  38510. },
  38511. enumerable: true,
  38512. configurable: true
  38513. });
  38514. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38515. get: function () {
  38516. return ActionManager._OnPickTrigger;
  38517. },
  38518. enumerable: true,
  38519. configurable: true
  38520. });
  38521. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38522. get: function () {
  38523. return ActionManager._OnLeftPickTrigger;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38529. get: function () {
  38530. return ActionManager._OnRightPickTrigger;
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38536. get: function () {
  38537. return ActionManager._OnCenterPickTrigger;
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38543. get: function () {
  38544. return ActionManager._OnPickDownTrigger;
  38545. },
  38546. enumerable: true,
  38547. configurable: true
  38548. });
  38549. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38550. get: function () {
  38551. return ActionManager._OnPickUpTrigger;
  38552. },
  38553. enumerable: true,
  38554. configurable: true
  38555. });
  38556. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38557. /// This trigger will only be raised if you also declared a OnPickDown
  38558. get: function () {
  38559. return ActionManager._OnPickOutTrigger;
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38565. get: function () {
  38566. return ActionManager._OnLongPressTrigger;
  38567. },
  38568. enumerable: true,
  38569. configurable: true
  38570. });
  38571. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38572. get: function () {
  38573. return ActionManager._OnPointerOverTrigger;
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38579. get: function () {
  38580. return ActionManager._OnPointerOutTrigger;
  38581. },
  38582. enumerable: true,
  38583. configurable: true
  38584. });
  38585. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38586. get: function () {
  38587. return ActionManager._OnEveryFrameTrigger;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38593. get: function () {
  38594. return ActionManager._OnIntersectionEnterTrigger;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38600. get: function () {
  38601. return ActionManager._OnIntersectionExitTrigger;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38607. get: function () {
  38608. return ActionManager._OnKeyDownTrigger;
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38614. get: function () {
  38615. return ActionManager._OnKeyUpTrigger;
  38616. },
  38617. enumerable: true,
  38618. configurable: true
  38619. });
  38620. // Methods
  38621. ActionManager.prototype.dispose = function () {
  38622. var index = this._scene._actionManagers.indexOf(this);
  38623. if (index > -1) {
  38624. this._scene._actionManagers.splice(index, 1);
  38625. }
  38626. };
  38627. ActionManager.prototype.getScene = function () {
  38628. return this._scene;
  38629. };
  38630. /**
  38631. * Does this action manager handles actions of any of the given triggers
  38632. * @param {number[]} triggers - the triggers to be tested
  38633. * @return {boolean} whether one (or more) of the triggers is handeled
  38634. */
  38635. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38636. for (var index = 0; index < this.actions.length; index++) {
  38637. var action = this.actions[index];
  38638. if (triggers.indexOf(action.trigger) > -1) {
  38639. return true;
  38640. }
  38641. }
  38642. return false;
  38643. };
  38644. /**
  38645. * Does this action manager handles actions of a given trigger
  38646. * @param {number} trigger - the trigger to be tested
  38647. * @return {boolean} whether the trigger is handeled
  38648. */
  38649. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38650. for (var index = 0; index < this.actions.length; index++) {
  38651. var action = this.actions[index];
  38652. if (action.trigger === trigger) {
  38653. return true;
  38654. }
  38655. }
  38656. return false;
  38657. };
  38658. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38659. /**
  38660. * Does this action manager has pointer triggers
  38661. * @return {boolean} whether or not it has pointer triggers
  38662. */
  38663. get: function () {
  38664. for (var index = 0; index < this.actions.length; index++) {
  38665. var action = this.actions[index];
  38666. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38667. return true;
  38668. }
  38669. }
  38670. return false;
  38671. },
  38672. enumerable: true,
  38673. configurable: true
  38674. });
  38675. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38676. /**
  38677. * Does this action manager has pick triggers
  38678. * @return {boolean} whether or not it has pick triggers
  38679. */
  38680. get: function () {
  38681. for (var index = 0; index < this.actions.length; index++) {
  38682. var action = this.actions[index];
  38683. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38684. return true;
  38685. }
  38686. }
  38687. return false;
  38688. },
  38689. enumerable: true,
  38690. configurable: true
  38691. });
  38692. /**
  38693. * Registers an action to this action manager
  38694. * @param {BABYLON.Action} action - the action to be registered
  38695. * @return {BABYLON.Action} the action amended (prepared) after registration
  38696. */
  38697. ActionManager.prototype.registerAction = function (action) {
  38698. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38699. if (this.getScene().actionManager !== this) {
  38700. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38701. return null;
  38702. }
  38703. }
  38704. this.actions.push(action);
  38705. action._actionManager = this;
  38706. action._prepare();
  38707. return action;
  38708. };
  38709. /**
  38710. * Process a specific trigger
  38711. * @param {number} trigger - the trigger to process
  38712. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38713. */
  38714. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38715. for (var index = 0; index < this.actions.length; index++) {
  38716. var action = this.actions[index];
  38717. if (action.trigger === trigger) {
  38718. if (trigger === ActionManager.OnKeyUpTrigger
  38719. || trigger === ActionManager.OnKeyDownTrigger) {
  38720. var parameter = action.getTriggerParameter();
  38721. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38722. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38723. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38724. if (actualkey !== parameter.toLowerCase()) {
  38725. continue;
  38726. }
  38727. }
  38728. }
  38729. action._executeCurrent(evt);
  38730. }
  38731. }
  38732. };
  38733. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38734. var properties = propertyPath.split(".");
  38735. for (var index = 0; index < properties.length - 1; index++) {
  38736. target = target[properties[index]];
  38737. }
  38738. return target;
  38739. };
  38740. ActionManager.prototype._getProperty = function (propertyPath) {
  38741. var properties = propertyPath.split(".");
  38742. return properties[properties.length - 1];
  38743. };
  38744. ActionManager.prototype.serialize = function (name) {
  38745. var root = {
  38746. children: [],
  38747. name: name,
  38748. type: 3,
  38749. properties: [] // Empty for root but required
  38750. };
  38751. for (var i = 0; i < this.actions.length; i++) {
  38752. var triggerObject = {
  38753. type: 0,
  38754. children: [],
  38755. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38756. properties: []
  38757. };
  38758. var triggerOptions = this.actions[i].triggerOptions;
  38759. if (triggerOptions && typeof triggerOptions !== "number") {
  38760. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38761. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38762. }
  38763. else {
  38764. var parameter = {};
  38765. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38766. if (triggerOptions.parameter.mesh) {
  38767. parameter._meshId = triggerOptions.parameter.mesh.id;
  38768. }
  38769. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38770. }
  38771. }
  38772. // Serialize child action, recursively
  38773. this.actions[i].serialize(triggerObject);
  38774. // Add serialized trigger
  38775. root.children.push(triggerObject);
  38776. }
  38777. return root;
  38778. };
  38779. ActionManager.Parse = function (parsedActions, object, scene) {
  38780. var actionManager = new BABYLON.ActionManager(scene);
  38781. if (object === null)
  38782. scene.actionManager = actionManager;
  38783. else
  38784. object.actionManager = actionManager;
  38785. // instanciate a new object
  38786. var instanciate = function (name, params) {
  38787. var newInstance = Object.create(BABYLON[name].prototype);
  38788. newInstance.constructor.apply(newInstance, params);
  38789. return newInstance;
  38790. };
  38791. var parseParameter = function (name, value, target, propertyPath) {
  38792. if (propertyPath === null) {
  38793. // String, boolean or float
  38794. var floatValue = parseFloat(value);
  38795. if (value === "true" || value === "false")
  38796. return value === "true";
  38797. else
  38798. return isNaN(floatValue) ? value : floatValue;
  38799. }
  38800. var effectiveTarget = propertyPath.split(".");
  38801. var values = value.split(",");
  38802. // Get effective Target
  38803. for (var i = 0; i < effectiveTarget.length; i++) {
  38804. target = target[effectiveTarget[i]];
  38805. }
  38806. // Return appropriate value with its type
  38807. if (typeof (target) === "boolean")
  38808. return values[0] === "true";
  38809. if (typeof (target) === "string")
  38810. return values[0];
  38811. // Parameters with multiple values such as Vector3 etc.
  38812. var split = new Array();
  38813. for (var i = 0; i < values.length; i++)
  38814. split.push(parseFloat(values[i]));
  38815. if (target instanceof BABYLON.Vector3)
  38816. return BABYLON.Vector3.FromArray(split);
  38817. if (target instanceof BABYLON.Vector4)
  38818. return BABYLON.Vector4.FromArray(split);
  38819. if (target instanceof BABYLON.Color3)
  38820. return BABYLON.Color3.FromArray(split);
  38821. if (target instanceof BABYLON.Color4)
  38822. return BABYLON.Color4.FromArray(split);
  38823. return parseFloat(values[0]);
  38824. };
  38825. // traverse graph per trigger
  38826. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38827. if (combineArray === void 0) { combineArray = null; }
  38828. if (parsedAction.detached)
  38829. return;
  38830. var parameters = new Array();
  38831. var target = null;
  38832. var propertyPath = null;
  38833. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38834. // Parameters
  38835. if (parsedAction.type === 2)
  38836. parameters.push(actionManager);
  38837. else
  38838. parameters.push(trigger);
  38839. if (combine) {
  38840. var actions = new Array();
  38841. for (var j = 0; j < parsedAction.combine.length; j++) {
  38842. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38843. }
  38844. parameters.push(actions);
  38845. }
  38846. else {
  38847. for (var i = 0; i < parsedAction.properties.length; i++) {
  38848. var value = parsedAction.properties[i].value;
  38849. var name = parsedAction.properties[i].name;
  38850. var targetType = parsedAction.properties[i].targetType;
  38851. if (name === "target")
  38852. if (targetType !== null && targetType === "SceneProperties")
  38853. value = target = scene;
  38854. else
  38855. value = target = scene.getNodeByName(value);
  38856. else if (name === "parent")
  38857. value = scene.getNodeByName(value);
  38858. else if (name === "sound")
  38859. value = scene.getSoundByName(value);
  38860. else if (name !== "propertyPath") {
  38861. if (parsedAction.type === 2 && name === "operator")
  38862. value = BABYLON.ValueCondition[value];
  38863. else
  38864. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38865. }
  38866. else {
  38867. propertyPath = value;
  38868. }
  38869. parameters.push(value);
  38870. }
  38871. }
  38872. if (combineArray === null) {
  38873. parameters.push(condition);
  38874. }
  38875. else {
  38876. parameters.push(null);
  38877. }
  38878. // If interpolate value action
  38879. if (parsedAction.name === "InterpolateValueAction") {
  38880. var param = parameters[parameters.length - 2];
  38881. parameters[parameters.length - 1] = param;
  38882. parameters[parameters.length - 2] = condition;
  38883. }
  38884. // Action or condition(s) and not CombineAction
  38885. var newAction = instanciate(parsedAction.name, parameters);
  38886. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38887. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38888. if (action)
  38889. action.then(nothing);
  38890. else
  38891. actionManager.registerAction(nothing);
  38892. action = nothing;
  38893. }
  38894. if (combineArray === null) {
  38895. if (newAction instanceof BABYLON.Condition) {
  38896. condition = newAction;
  38897. newAction = action;
  38898. }
  38899. else {
  38900. condition = null;
  38901. if (action)
  38902. action.then(newAction);
  38903. else
  38904. actionManager.registerAction(newAction);
  38905. }
  38906. }
  38907. else {
  38908. combineArray.push(newAction);
  38909. }
  38910. for (var i = 0; i < parsedAction.children.length; i++)
  38911. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38912. };
  38913. // triggers
  38914. for (var i = 0; i < parsedActions.children.length; i++) {
  38915. var triggerParams;
  38916. var trigger = parsedActions.children[i];
  38917. if (trigger.properties.length > 0) {
  38918. var param = trigger.properties[0].value;
  38919. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38920. if (value._meshId) {
  38921. value.mesh = scene.getMeshByID(value._meshId);
  38922. }
  38923. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38924. }
  38925. else
  38926. triggerParams = BABYLON.ActionManager[trigger.name];
  38927. for (var j = 0; j < trigger.children.length; j++) {
  38928. if (!trigger.detached)
  38929. traverse(trigger.children[j], triggerParams, null, null);
  38930. }
  38931. }
  38932. };
  38933. ActionManager.GetTriggerName = function (trigger) {
  38934. switch (trigger) {
  38935. case 0: return "NothingTrigger";
  38936. case 1: return "OnPickTrigger";
  38937. case 2: return "OnLeftPickTrigger";
  38938. case 3: return "OnRightPickTrigger";
  38939. case 4: return "OnCenterPickTrigger";
  38940. case 5: return "OnPickDownTrigger";
  38941. case 6: return "OnPickUpTrigger";
  38942. case 7: return "OnLongPressTrigger";
  38943. case 8: return "OnPointerOverTrigger";
  38944. case 9: return "OnPointerOutTrigger";
  38945. case 10: return "OnEveryFrameTrigger";
  38946. case 11: return "OnIntersectionEnterTrigger";
  38947. case 12: return "OnIntersectionExitTrigger";
  38948. case 13: return "OnKeyDownTrigger";
  38949. case 14: return "OnKeyUpTrigger";
  38950. case 15: return "OnPickOutTrigger";
  38951. default: return "";
  38952. }
  38953. };
  38954. return ActionManager;
  38955. }());
  38956. // Statics
  38957. ActionManager._NothingTrigger = 0;
  38958. ActionManager._OnPickTrigger = 1;
  38959. ActionManager._OnLeftPickTrigger = 2;
  38960. ActionManager._OnRightPickTrigger = 3;
  38961. ActionManager._OnCenterPickTrigger = 4;
  38962. ActionManager._OnPickDownTrigger = 5;
  38963. ActionManager._OnPickUpTrigger = 6;
  38964. ActionManager._OnLongPressTrigger = 7;
  38965. ActionManager._OnPointerOverTrigger = 8;
  38966. ActionManager._OnPointerOutTrigger = 9;
  38967. ActionManager._OnEveryFrameTrigger = 10;
  38968. ActionManager._OnIntersectionEnterTrigger = 11;
  38969. ActionManager._OnIntersectionExitTrigger = 12;
  38970. ActionManager._OnKeyDownTrigger = 13;
  38971. ActionManager._OnKeyUpTrigger = 14;
  38972. ActionManager._OnPickOutTrigger = 15;
  38973. ActionManager.DragMovementThreshold = 10; // in pixels
  38974. ActionManager.LongPressDelay = 500; // in milliseconds
  38975. BABYLON.ActionManager = ActionManager;
  38976. })(BABYLON || (BABYLON = {}));
  38977. //# sourceMappingURL=babylon.actionManager.js.map
  38978. var BABYLON;
  38979. (function (BABYLON) {
  38980. var InterpolateValueAction = (function (_super) {
  38981. __extends(InterpolateValueAction, _super);
  38982. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38983. if (duration === void 0) { duration = 1000; }
  38984. var _this = _super.call(this, triggerOptions, condition) || this;
  38985. _this.propertyPath = propertyPath;
  38986. _this.value = value;
  38987. _this.duration = duration;
  38988. _this.stopOtherAnimations = stopOtherAnimations;
  38989. _this.onInterpolationDone = onInterpolationDone;
  38990. _this._target = _this._effectiveTarget = target;
  38991. return _this;
  38992. }
  38993. InterpolateValueAction.prototype._prepare = function () {
  38994. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38995. this._property = this._getProperty(this.propertyPath);
  38996. };
  38997. InterpolateValueAction.prototype.execute = function () {
  38998. var scene = this._actionManager.getScene();
  38999. var keys = [
  39000. {
  39001. frame: 0,
  39002. value: this._effectiveTarget[this._property]
  39003. }, {
  39004. frame: 100,
  39005. value: this.value
  39006. }
  39007. ];
  39008. var dataType;
  39009. if (typeof this.value === "number") {
  39010. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39011. }
  39012. else if (this.value instanceof BABYLON.Color3) {
  39013. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39014. }
  39015. else if (this.value instanceof BABYLON.Vector3) {
  39016. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39017. }
  39018. else if (this.value instanceof BABYLON.Matrix) {
  39019. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39020. }
  39021. else if (this.value instanceof BABYLON.Quaternion) {
  39022. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39023. }
  39024. else {
  39025. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39026. return;
  39027. }
  39028. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39029. animation.setKeys(keys);
  39030. if (this.stopOtherAnimations) {
  39031. scene.stopAnimation(this._effectiveTarget);
  39032. }
  39033. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39034. };
  39035. InterpolateValueAction.prototype.serialize = function (parent) {
  39036. return _super.prototype._serialize.call(this, {
  39037. name: "InterpolateValueAction",
  39038. properties: [
  39039. BABYLON.Action._GetTargetProperty(this._target),
  39040. { name: "propertyPath", value: this.propertyPath },
  39041. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39042. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39043. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39044. ]
  39045. }, parent);
  39046. };
  39047. return InterpolateValueAction;
  39048. }(BABYLON.Action));
  39049. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39050. })(BABYLON || (BABYLON = {}));
  39051. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39052. var BABYLON;
  39053. (function (BABYLON) {
  39054. var SwitchBooleanAction = (function (_super) {
  39055. __extends(SwitchBooleanAction, _super);
  39056. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39057. var _this = _super.call(this, triggerOptions, condition) || this;
  39058. _this.propertyPath = propertyPath;
  39059. _this._target = _this._effectiveTarget = target;
  39060. return _this;
  39061. }
  39062. SwitchBooleanAction.prototype._prepare = function () {
  39063. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39064. this._property = this._getProperty(this.propertyPath);
  39065. };
  39066. SwitchBooleanAction.prototype.execute = function () {
  39067. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39068. };
  39069. SwitchBooleanAction.prototype.serialize = function (parent) {
  39070. return _super.prototype._serialize.call(this, {
  39071. name: "SwitchBooleanAction",
  39072. properties: [
  39073. BABYLON.Action._GetTargetProperty(this._target),
  39074. { name: "propertyPath", value: this.propertyPath }
  39075. ]
  39076. }, parent);
  39077. };
  39078. return SwitchBooleanAction;
  39079. }(BABYLON.Action));
  39080. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39081. var SetStateAction = (function (_super) {
  39082. __extends(SetStateAction, _super);
  39083. function SetStateAction(triggerOptions, target, value, condition) {
  39084. var _this = _super.call(this, triggerOptions, condition) || this;
  39085. _this.value = value;
  39086. _this._target = target;
  39087. return _this;
  39088. }
  39089. SetStateAction.prototype.execute = function () {
  39090. this._target.state = this.value;
  39091. };
  39092. SetStateAction.prototype.serialize = function (parent) {
  39093. return _super.prototype._serialize.call(this, {
  39094. name: "SetStateAction",
  39095. properties: [
  39096. BABYLON.Action._GetTargetProperty(this._target),
  39097. { name: "value", value: this.value }
  39098. ]
  39099. }, parent);
  39100. };
  39101. return SetStateAction;
  39102. }(BABYLON.Action));
  39103. BABYLON.SetStateAction = SetStateAction;
  39104. var SetValueAction = (function (_super) {
  39105. __extends(SetValueAction, _super);
  39106. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39107. var _this = _super.call(this, triggerOptions, condition) || this;
  39108. _this.propertyPath = propertyPath;
  39109. _this.value = value;
  39110. _this._target = _this._effectiveTarget = target;
  39111. return _this;
  39112. }
  39113. SetValueAction.prototype._prepare = function () {
  39114. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39115. this._property = this._getProperty(this.propertyPath);
  39116. };
  39117. SetValueAction.prototype.execute = function () {
  39118. this._effectiveTarget[this._property] = this.value;
  39119. if (this._target.markAsDirty) {
  39120. this._target.markAsDirty(this._property);
  39121. }
  39122. };
  39123. SetValueAction.prototype.serialize = function (parent) {
  39124. return _super.prototype._serialize.call(this, {
  39125. name: "SetValueAction",
  39126. properties: [
  39127. BABYLON.Action._GetTargetProperty(this._target),
  39128. { name: "propertyPath", value: this.propertyPath },
  39129. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39130. ]
  39131. }, parent);
  39132. };
  39133. return SetValueAction;
  39134. }(BABYLON.Action));
  39135. BABYLON.SetValueAction = SetValueAction;
  39136. var IncrementValueAction = (function (_super) {
  39137. __extends(IncrementValueAction, _super);
  39138. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39139. var _this = _super.call(this, triggerOptions, condition) || this;
  39140. _this.propertyPath = propertyPath;
  39141. _this.value = value;
  39142. _this._target = _this._effectiveTarget = target;
  39143. return _this;
  39144. }
  39145. IncrementValueAction.prototype._prepare = function () {
  39146. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39147. this._property = this._getProperty(this.propertyPath);
  39148. if (typeof this._effectiveTarget[this._property] !== "number") {
  39149. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39150. }
  39151. };
  39152. IncrementValueAction.prototype.execute = function () {
  39153. this._effectiveTarget[this._property] += this.value;
  39154. if (this._target.markAsDirty) {
  39155. this._target.markAsDirty(this._property);
  39156. }
  39157. };
  39158. IncrementValueAction.prototype.serialize = function (parent) {
  39159. return _super.prototype._serialize.call(this, {
  39160. name: "IncrementValueAction",
  39161. properties: [
  39162. BABYLON.Action._GetTargetProperty(this._target),
  39163. { name: "propertyPath", value: this.propertyPath },
  39164. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39165. ]
  39166. }, parent);
  39167. };
  39168. return IncrementValueAction;
  39169. }(BABYLON.Action));
  39170. BABYLON.IncrementValueAction = IncrementValueAction;
  39171. var PlayAnimationAction = (function (_super) {
  39172. __extends(PlayAnimationAction, _super);
  39173. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39174. var _this = _super.call(this, triggerOptions, condition) || this;
  39175. _this.from = from;
  39176. _this.to = to;
  39177. _this.loop = loop;
  39178. _this._target = target;
  39179. return _this;
  39180. }
  39181. PlayAnimationAction.prototype._prepare = function () {
  39182. };
  39183. PlayAnimationAction.prototype.execute = function () {
  39184. var scene = this._actionManager.getScene();
  39185. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39186. };
  39187. PlayAnimationAction.prototype.serialize = function (parent) {
  39188. return _super.prototype._serialize.call(this, {
  39189. name: "PlayAnimationAction",
  39190. properties: [
  39191. BABYLON.Action._GetTargetProperty(this._target),
  39192. { name: "from", value: String(this.from) },
  39193. { name: "to", value: String(this.to) },
  39194. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39195. ]
  39196. }, parent);
  39197. };
  39198. return PlayAnimationAction;
  39199. }(BABYLON.Action));
  39200. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39201. var StopAnimationAction = (function (_super) {
  39202. __extends(StopAnimationAction, _super);
  39203. function StopAnimationAction(triggerOptions, target, condition) {
  39204. var _this = _super.call(this, triggerOptions, condition) || this;
  39205. _this._target = target;
  39206. return _this;
  39207. }
  39208. StopAnimationAction.prototype._prepare = function () {
  39209. };
  39210. StopAnimationAction.prototype.execute = function () {
  39211. var scene = this._actionManager.getScene();
  39212. scene.stopAnimation(this._target);
  39213. };
  39214. StopAnimationAction.prototype.serialize = function (parent) {
  39215. return _super.prototype._serialize.call(this, {
  39216. name: "StopAnimationAction",
  39217. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39218. }, parent);
  39219. };
  39220. return StopAnimationAction;
  39221. }(BABYLON.Action));
  39222. BABYLON.StopAnimationAction = StopAnimationAction;
  39223. var DoNothingAction = (function (_super) {
  39224. __extends(DoNothingAction, _super);
  39225. function DoNothingAction(triggerOptions, condition) {
  39226. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39227. return _super.call(this, triggerOptions, condition) || this;
  39228. }
  39229. DoNothingAction.prototype.execute = function () {
  39230. };
  39231. DoNothingAction.prototype.serialize = function (parent) {
  39232. return _super.prototype._serialize.call(this, {
  39233. name: "DoNothingAction",
  39234. properties: []
  39235. }, parent);
  39236. };
  39237. return DoNothingAction;
  39238. }(BABYLON.Action));
  39239. BABYLON.DoNothingAction = DoNothingAction;
  39240. var CombineAction = (function (_super) {
  39241. __extends(CombineAction, _super);
  39242. function CombineAction(triggerOptions, children, condition) {
  39243. var _this = _super.call(this, triggerOptions, condition) || this;
  39244. _this.children = children;
  39245. return _this;
  39246. }
  39247. CombineAction.prototype._prepare = function () {
  39248. for (var index = 0; index < this.children.length; index++) {
  39249. this.children[index]._actionManager = this._actionManager;
  39250. this.children[index]._prepare();
  39251. }
  39252. };
  39253. CombineAction.prototype.execute = function (evt) {
  39254. for (var index = 0; index < this.children.length; index++) {
  39255. this.children[index].execute(evt);
  39256. }
  39257. };
  39258. CombineAction.prototype.serialize = function (parent) {
  39259. var serializationObject = _super.prototype._serialize.call(this, {
  39260. name: "CombineAction",
  39261. properties: [],
  39262. combine: []
  39263. }, parent);
  39264. for (var i = 0; i < this.children.length; i++) {
  39265. serializationObject.combine.push(this.children[i].serialize(null));
  39266. }
  39267. return serializationObject;
  39268. };
  39269. return CombineAction;
  39270. }(BABYLON.Action));
  39271. BABYLON.CombineAction = CombineAction;
  39272. var ExecuteCodeAction = (function (_super) {
  39273. __extends(ExecuteCodeAction, _super);
  39274. function ExecuteCodeAction(triggerOptions, func, condition) {
  39275. var _this = _super.call(this, triggerOptions, condition) || this;
  39276. _this.func = func;
  39277. return _this;
  39278. }
  39279. ExecuteCodeAction.prototype.execute = function (evt) {
  39280. this.func(evt);
  39281. };
  39282. return ExecuteCodeAction;
  39283. }(BABYLON.Action));
  39284. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39285. var SetParentAction = (function (_super) {
  39286. __extends(SetParentAction, _super);
  39287. function SetParentAction(triggerOptions, target, parent, condition) {
  39288. var _this = _super.call(this, triggerOptions, condition) || this;
  39289. _this._target = target;
  39290. _this._parent = parent;
  39291. return _this;
  39292. }
  39293. SetParentAction.prototype._prepare = function () {
  39294. };
  39295. SetParentAction.prototype.execute = function () {
  39296. if (this._target.parent === this._parent) {
  39297. return;
  39298. }
  39299. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39300. invertParentWorldMatrix.invert();
  39301. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39302. this._target.parent = this._parent;
  39303. };
  39304. SetParentAction.prototype.serialize = function (parent) {
  39305. return _super.prototype._serialize.call(this, {
  39306. name: "SetParentAction",
  39307. properties: [
  39308. BABYLON.Action._GetTargetProperty(this._target),
  39309. BABYLON.Action._GetTargetProperty(this._parent),
  39310. ]
  39311. }, parent);
  39312. };
  39313. return SetParentAction;
  39314. }(BABYLON.Action));
  39315. BABYLON.SetParentAction = SetParentAction;
  39316. var PlaySoundAction = (function (_super) {
  39317. __extends(PlaySoundAction, _super);
  39318. function PlaySoundAction(triggerOptions, sound, condition) {
  39319. var _this = _super.call(this, triggerOptions, condition) || this;
  39320. _this._sound = sound;
  39321. return _this;
  39322. }
  39323. PlaySoundAction.prototype._prepare = function () {
  39324. };
  39325. PlaySoundAction.prototype.execute = function () {
  39326. if (this._sound !== undefined)
  39327. this._sound.play();
  39328. };
  39329. PlaySoundAction.prototype.serialize = function (parent) {
  39330. return _super.prototype._serialize.call(this, {
  39331. name: "PlaySoundAction",
  39332. properties: [{ name: "sound", value: this._sound.name }]
  39333. }, parent);
  39334. };
  39335. return PlaySoundAction;
  39336. }(BABYLON.Action));
  39337. BABYLON.PlaySoundAction = PlaySoundAction;
  39338. var StopSoundAction = (function (_super) {
  39339. __extends(StopSoundAction, _super);
  39340. function StopSoundAction(triggerOptions, sound, condition) {
  39341. var _this = _super.call(this, triggerOptions, condition) || this;
  39342. _this._sound = sound;
  39343. return _this;
  39344. }
  39345. StopSoundAction.prototype._prepare = function () {
  39346. };
  39347. StopSoundAction.prototype.execute = function () {
  39348. if (this._sound !== undefined)
  39349. this._sound.stop();
  39350. };
  39351. StopSoundAction.prototype.serialize = function (parent) {
  39352. return _super.prototype._serialize.call(this, {
  39353. name: "StopSoundAction",
  39354. properties: [{ name: "sound", value: this._sound.name }]
  39355. }, parent);
  39356. };
  39357. return StopSoundAction;
  39358. }(BABYLON.Action));
  39359. BABYLON.StopSoundAction = StopSoundAction;
  39360. })(BABYLON || (BABYLON = {}));
  39361. //# sourceMappingURL=babylon.directActions.js.map
  39362. var BABYLON;
  39363. (function (BABYLON) {
  39364. var Geometry = (function () {
  39365. function Geometry(id, scene, vertexData, updatable, mesh) {
  39366. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39367. this._totalVertices = 0;
  39368. this._isDisposed = false;
  39369. this.id = id;
  39370. this._engine = scene.getEngine();
  39371. this._meshes = [];
  39372. this._scene = scene;
  39373. //Init vertex buffer cache
  39374. this._vertexBuffers = {};
  39375. this._indices = [];
  39376. // vertexData
  39377. if (vertexData) {
  39378. this.setAllVerticesData(vertexData, updatable);
  39379. }
  39380. else {
  39381. this._totalVertices = 0;
  39382. this._indices = [];
  39383. }
  39384. if (this._engine.getCaps().vertexArrayObject) {
  39385. this._vertexArrayObjects = {};
  39386. }
  39387. // applyToMesh
  39388. if (mesh) {
  39389. if (mesh instanceof BABYLON.LinesMesh) {
  39390. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39391. this.updateExtend();
  39392. }
  39393. this.applyToMesh(mesh);
  39394. mesh.computeWorldMatrix(true);
  39395. }
  39396. }
  39397. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39398. /**
  39399. * 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
  39400. * @returns The Bias Vector
  39401. */
  39402. get: function () {
  39403. return this._boundingBias;
  39404. },
  39405. set: function (value) {
  39406. if (this._boundingBias && this._boundingBias.equals(value)) {
  39407. return;
  39408. }
  39409. this._boundingBias = value.clone();
  39410. this.updateBoundingInfo(true, null);
  39411. },
  39412. enumerable: true,
  39413. configurable: true
  39414. });
  39415. Object.defineProperty(Geometry.prototype, "extend", {
  39416. get: function () {
  39417. return this._extend;
  39418. },
  39419. enumerable: true,
  39420. configurable: true
  39421. });
  39422. Geometry.prototype.getScene = function () {
  39423. return this._scene;
  39424. };
  39425. Geometry.prototype.getEngine = function () {
  39426. return this._engine;
  39427. };
  39428. Geometry.prototype.isReady = function () {
  39429. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39430. };
  39431. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39432. get: function () {
  39433. for (var index = 0; index < this._meshes.length; index++) {
  39434. if (!this._meshes[index].doNotSerialize) {
  39435. return false;
  39436. }
  39437. }
  39438. return true;
  39439. },
  39440. enumerable: true,
  39441. configurable: true
  39442. });
  39443. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39444. vertexData.applyToGeometry(this, updatable);
  39445. this.notifyUpdate();
  39446. };
  39447. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39448. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39449. this.setVerticesBuffer(buffer);
  39450. };
  39451. Geometry.prototype.setVerticesBuffer = function (buffer) {
  39452. var kind = buffer.getKind();
  39453. if (this._vertexBuffers[kind]) {
  39454. this._vertexBuffers[kind].dispose();
  39455. }
  39456. this._vertexBuffers[kind] = buffer;
  39457. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39458. var data = buffer.getData();
  39459. var stride = buffer.getStrideSize();
  39460. this._totalVertices = data.length / stride;
  39461. this.updateExtend(data, stride);
  39462. var meshes = this._meshes;
  39463. var numOfMeshes = meshes.length;
  39464. for (var index = 0; index < numOfMeshes; index++) {
  39465. var mesh = meshes[index];
  39466. mesh._resetPointsArrayCache();
  39467. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39468. mesh._createGlobalSubMesh();
  39469. mesh.computeWorldMatrix(true);
  39470. }
  39471. }
  39472. this.notifyUpdate(kind);
  39473. if (this._vertexArrayObjects) {
  39474. this._disposeVertexArrayObjects();
  39475. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39476. }
  39477. };
  39478. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  39479. var vertexBuffer = this.getVertexBuffer(kind);
  39480. if (!vertexBuffer) {
  39481. return;
  39482. }
  39483. vertexBuffer.updateDirectly(data, offset);
  39484. this.notifyUpdate(kind);
  39485. };
  39486. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39487. var vertexBuffer = this.getVertexBuffer(kind);
  39488. if (!vertexBuffer) {
  39489. return;
  39490. }
  39491. vertexBuffer.update(data);
  39492. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39493. var stride = vertexBuffer.getStrideSize();
  39494. this._totalVertices = data.length / stride;
  39495. this.updateBoundingInfo(updateExtends, data);
  39496. }
  39497. this.notifyUpdate(kind);
  39498. };
  39499. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  39500. if (updateExtends) {
  39501. this.updateExtend(data);
  39502. }
  39503. var meshes = this._meshes;
  39504. var numOfMeshes = meshes.length;
  39505. for (var index = 0; index < numOfMeshes; index++) {
  39506. var mesh = meshes[index];
  39507. mesh._resetPointsArrayCache();
  39508. if (updateExtends) {
  39509. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39510. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39511. var subMesh = mesh.subMeshes[subIndex];
  39512. subMesh.refreshBoundingInfo();
  39513. }
  39514. }
  39515. }
  39516. };
  39517. Geometry.prototype._bind = function (effect, indexToBind) {
  39518. if (indexToBind === void 0) { indexToBind = undefined; }
  39519. if (indexToBind === undefined) {
  39520. indexToBind = this._indexBuffer;
  39521. }
  39522. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39523. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  39524. return;
  39525. }
  39526. // Using VAO
  39527. if (!this._vertexArrayObjects[effect.key]) {
  39528. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  39529. }
  39530. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39531. };
  39532. Geometry.prototype.getTotalVertices = function () {
  39533. if (!this.isReady()) {
  39534. return 0;
  39535. }
  39536. return this._totalVertices;
  39537. };
  39538. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  39539. var vertexBuffer = this.getVertexBuffer(kind);
  39540. if (!vertexBuffer) {
  39541. return null;
  39542. }
  39543. var orig = vertexBuffer.getData();
  39544. if (!copyWhenShared || this._meshes.length === 1) {
  39545. return orig;
  39546. }
  39547. else {
  39548. var len = orig.length;
  39549. var copy = [];
  39550. for (var i = 0; i < len; i++) {
  39551. copy.push(orig[i]);
  39552. }
  39553. return copy;
  39554. }
  39555. };
  39556. Geometry.prototype.getVertexBuffer = function (kind) {
  39557. if (!this.isReady()) {
  39558. return null;
  39559. }
  39560. return this._vertexBuffers[kind];
  39561. };
  39562. Geometry.prototype.getVertexBuffers = function () {
  39563. if (!this.isReady()) {
  39564. return null;
  39565. }
  39566. return this._vertexBuffers;
  39567. };
  39568. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39569. if (!this._vertexBuffers) {
  39570. if (this._delayInfo) {
  39571. return this._delayInfo.indexOf(kind) !== -1;
  39572. }
  39573. return false;
  39574. }
  39575. return this._vertexBuffers[kind] !== undefined;
  39576. };
  39577. Geometry.prototype.getVerticesDataKinds = function () {
  39578. var result = [];
  39579. var kind;
  39580. if (!this._vertexBuffers && this._delayInfo) {
  39581. for (kind in this._delayInfo) {
  39582. result.push(kind);
  39583. }
  39584. }
  39585. else {
  39586. for (kind in this._vertexBuffers) {
  39587. result.push(kind);
  39588. }
  39589. }
  39590. return result;
  39591. };
  39592. Geometry.prototype.setIndices = function (indices, totalVertices) {
  39593. if (this._indexBuffer) {
  39594. this._engine._releaseBuffer(this._indexBuffer);
  39595. }
  39596. this._disposeVertexArrayObjects();
  39597. this._indices = indices;
  39598. if (this._meshes.length !== 0 && this._indices) {
  39599. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39600. }
  39601. if (totalVertices !== undefined) {
  39602. this._totalVertices = totalVertices;
  39603. }
  39604. var meshes = this._meshes;
  39605. var numOfMeshes = meshes.length;
  39606. for (var index = 0; index < numOfMeshes; index++) {
  39607. meshes[index]._createGlobalSubMesh();
  39608. }
  39609. this.notifyUpdate();
  39610. };
  39611. Geometry.prototype.getTotalIndices = function () {
  39612. if (!this.isReady()) {
  39613. return 0;
  39614. }
  39615. return this._indices.length;
  39616. };
  39617. Geometry.prototype.getIndices = function (copyWhenShared) {
  39618. if (!this.isReady()) {
  39619. return null;
  39620. }
  39621. var orig = this._indices;
  39622. if (!copyWhenShared || this._meshes.length === 1) {
  39623. return orig;
  39624. }
  39625. else {
  39626. var len = orig.length;
  39627. var copy = [];
  39628. for (var i = 0; i < len; i++) {
  39629. copy.push(orig[i]);
  39630. }
  39631. return copy;
  39632. }
  39633. };
  39634. Geometry.prototype.getIndexBuffer = function () {
  39635. if (!this.isReady()) {
  39636. return null;
  39637. }
  39638. return this._indexBuffer;
  39639. };
  39640. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39641. var meshes = this._meshes;
  39642. var index = meshes.indexOf(mesh);
  39643. if (index === -1) {
  39644. return;
  39645. }
  39646. meshes.splice(index, 1);
  39647. mesh._geometry = null;
  39648. if (meshes.length === 0 && shouldDispose) {
  39649. this.dispose();
  39650. }
  39651. };
  39652. Geometry.prototype.applyToMesh = function (mesh) {
  39653. if (mesh._geometry === this) {
  39654. return;
  39655. }
  39656. var previousGeometry = mesh._geometry;
  39657. if (previousGeometry) {
  39658. previousGeometry.releaseForMesh(mesh);
  39659. }
  39660. var meshes = this._meshes;
  39661. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39662. mesh._geometry = this;
  39663. this._scene.pushGeometry(this);
  39664. meshes.push(mesh);
  39665. if (this.isReady()) {
  39666. this._applyToMesh(mesh);
  39667. }
  39668. else {
  39669. mesh._boundingInfo = this._boundingInfo;
  39670. }
  39671. };
  39672. Geometry.prototype.updateExtend = function (data, stride) {
  39673. if (data === void 0) { data = null; }
  39674. if (!data) {
  39675. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  39676. }
  39677. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  39678. };
  39679. Geometry.prototype._applyToMesh = function (mesh) {
  39680. var numOfMeshes = this._meshes.length;
  39681. // vertexBuffers
  39682. for (var kind in this._vertexBuffers) {
  39683. if (numOfMeshes === 1) {
  39684. this._vertexBuffers[kind].create();
  39685. }
  39686. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  39687. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39688. mesh._resetPointsArrayCache();
  39689. if (!this._extend) {
  39690. this.updateExtend(this._vertexBuffers[kind].getData());
  39691. }
  39692. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39693. mesh._createGlobalSubMesh();
  39694. //bounding info was just created again, world matrix should be applied again.
  39695. mesh._updateBoundingInfo();
  39696. }
  39697. }
  39698. // indexBuffer
  39699. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39700. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39701. }
  39702. if (this._indexBuffer) {
  39703. this._indexBuffer.references = numOfMeshes;
  39704. }
  39705. };
  39706. Geometry.prototype.notifyUpdate = function (kind) {
  39707. if (this.onGeometryUpdated) {
  39708. this.onGeometryUpdated(this, kind);
  39709. }
  39710. };
  39711. Geometry.prototype.load = function (scene, onLoaded) {
  39712. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39713. return;
  39714. }
  39715. if (this.isReady()) {
  39716. if (onLoaded) {
  39717. onLoaded();
  39718. }
  39719. return;
  39720. }
  39721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39722. this._queueLoad(scene, onLoaded);
  39723. };
  39724. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39725. var _this = this;
  39726. scene._addPendingData(this);
  39727. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  39728. _this._delayLoadingFunction(JSON.parse(data), _this);
  39729. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39730. _this._delayInfo = [];
  39731. scene._removePendingData(_this);
  39732. var meshes = _this._meshes;
  39733. var numOfMeshes = meshes.length;
  39734. for (var index = 0; index < numOfMeshes; index++) {
  39735. _this._applyToMesh(meshes[index]);
  39736. }
  39737. if (onLoaded) {
  39738. onLoaded();
  39739. }
  39740. }, function () { }, scene.database);
  39741. };
  39742. /**
  39743. * Invert the geometry to move from a right handed system to a left handed one.
  39744. */
  39745. Geometry.prototype.toLeftHanded = function () {
  39746. // Flip faces
  39747. var tIndices = this.getIndices(false);
  39748. if (tIndices != null && tIndices.length > 0) {
  39749. for (var i = 0; i < tIndices.length; i += 3) {
  39750. var tTemp = tIndices[i + 0];
  39751. tIndices[i + 0] = tIndices[i + 2];
  39752. tIndices[i + 2] = tTemp;
  39753. }
  39754. this.setIndices(tIndices);
  39755. }
  39756. // Negate position.z
  39757. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39758. if (tPositions != null && tPositions.length > 0) {
  39759. for (var i = 0; i < tPositions.length; i += 3) {
  39760. tPositions[i + 2] = -tPositions[i + 2];
  39761. }
  39762. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39763. }
  39764. // Negate normal.z
  39765. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39766. if (tNormals != null && tNormals.length > 0) {
  39767. for (var i = 0; i < tNormals.length; i += 3) {
  39768. tNormals[i + 2] = -tNormals[i + 2];
  39769. }
  39770. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39771. }
  39772. };
  39773. Geometry.prototype.isDisposed = function () {
  39774. return this._isDisposed;
  39775. };
  39776. Geometry.prototype._disposeVertexArrayObjects = function () {
  39777. if (this._vertexArrayObjects) {
  39778. for (var kind in this._vertexArrayObjects) {
  39779. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39780. }
  39781. this._vertexArrayObjects = {};
  39782. }
  39783. };
  39784. Geometry.prototype.dispose = function () {
  39785. var meshes = this._meshes;
  39786. var numOfMeshes = meshes.length;
  39787. var index;
  39788. for (index = 0; index < numOfMeshes; index++) {
  39789. this.releaseForMesh(meshes[index]);
  39790. }
  39791. this._meshes = [];
  39792. this._disposeVertexArrayObjects();
  39793. for (var kind in this._vertexBuffers) {
  39794. this._vertexBuffers[kind].dispose();
  39795. }
  39796. this._vertexBuffers = {};
  39797. this._totalVertices = 0;
  39798. if (this._indexBuffer) {
  39799. this._engine._releaseBuffer(this._indexBuffer);
  39800. }
  39801. this._indexBuffer = null;
  39802. this._indices = [];
  39803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39804. this.delayLoadingFile = null;
  39805. this._delayLoadingFunction = null;
  39806. this._delayInfo = [];
  39807. this._boundingInfo = null;
  39808. this._scene.removeGeometry(this);
  39809. this._isDisposed = true;
  39810. };
  39811. Geometry.prototype.copy = function (id) {
  39812. var vertexData = new BABYLON.VertexData();
  39813. vertexData.indices = [];
  39814. var indices = this.getIndices();
  39815. for (var index = 0; index < indices.length; index++) {
  39816. vertexData.indices.push(indices[index]);
  39817. }
  39818. var updatable = false;
  39819. var stopChecking = false;
  39820. var kind;
  39821. for (kind in this._vertexBuffers) {
  39822. // using slice() to make a copy of the array and not just reference it
  39823. var data = this.getVerticesData(kind);
  39824. if (data instanceof Float32Array) {
  39825. vertexData.set(new Float32Array(data), kind);
  39826. }
  39827. else {
  39828. vertexData.set(data.slice(0), kind);
  39829. }
  39830. if (!stopChecking) {
  39831. updatable = this.getVertexBuffer(kind).isUpdatable();
  39832. stopChecking = !updatable;
  39833. }
  39834. }
  39835. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  39836. geometry.delayLoadState = this.delayLoadState;
  39837. geometry.delayLoadingFile = this.delayLoadingFile;
  39838. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39839. for (kind in this._delayInfo) {
  39840. geometry._delayInfo = geometry._delayInfo || [];
  39841. geometry._delayInfo.push(kind);
  39842. }
  39843. // Bounding info
  39844. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39845. return geometry;
  39846. };
  39847. Geometry.prototype.serialize = function () {
  39848. var serializationObject = {};
  39849. serializationObject.id = this.id;
  39850. if (BABYLON.Tags.HasTags(this)) {
  39851. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39852. }
  39853. return serializationObject;
  39854. };
  39855. Geometry.prototype.serializeVerticeData = function () {
  39856. var serializationObject = this.serialize();
  39857. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39858. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39859. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  39860. serializationObject.positions._updatable = true;
  39861. }
  39862. }
  39863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39864. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39865. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  39866. serializationObject.normals._updatable = true;
  39867. }
  39868. }
  39869. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39870. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39871. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  39872. serializationObject.uvs._updatable = true;
  39873. }
  39874. }
  39875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39876. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  39877. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  39878. serializationObject.uv2s._updatable = true;
  39879. }
  39880. }
  39881. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39882. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  39883. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  39884. serializationObject.uv3s._updatable = true;
  39885. }
  39886. }
  39887. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39888. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  39889. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  39890. serializationObject.uv4s._updatable = true;
  39891. }
  39892. }
  39893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39894. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  39895. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  39896. serializationObject.uv5s._updatable = true;
  39897. }
  39898. }
  39899. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39900. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  39901. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  39902. serializationObject.uv6s._updatable = true;
  39903. }
  39904. }
  39905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39906. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39907. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  39908. serializationObject.colors._updatable = true;
  39909. }
  39910. }
  39911. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39912. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39913. serializationObject.matricesIndices._isExpanded = true;
  39914. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  39915. serializationObject.matricesIndices._updatable = true;
  39916. }
  39917. }
  39918. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39919. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  39920. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  39921. serializationObject.matricesWeights._updatable = true;
  39922. }
  39923. }
  39924. serializationObject.indices = this.getIndices();
  39925. return serializationObject;
  39926. };
  39927. // Statics
  39928. Geometry.ExtractFromMesh = function (mesh, id) {
  39929. var geometry = mesh._geometry;
  39930. if (!geometry) {
  39931. return null;
  39932. }
  39933. return geometry.copy(id);
  39934. };
  39935. /**
  39936. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39937. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39938. * Be aware Math.random() could cause collisions, but:
  39939. * "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"
  39940. */
  39941. Geometry.RandomId = function () {
  39942. return BABYLON.Tools.RandomId();
  39943. };
  39944. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  39945. var scene = mesh.getScene();
  39946. // Geometry
  39947. var geometryId = parsedGeometry.geometryId;
  39948. if (geometryId) {
  39949. var geometry = scene.getGeometryByID(geometryId);
  39950. if (geometry) {
  39951. geometry.applyToMesh(mesh);
  39952. }
  39953. }
  39954. else if (parsedGeometry instanceof ArrayBuffer) {
  39955. var binaryInfo = mesh._binaryInfo;
  39956. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39957. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39959. }
  39960. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39961. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39963. }
  39964. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39965. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39967. }
  39968. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39969. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39971. }
  39972. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39973. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39974. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39975. }
  39976. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39977. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39979. }
  39980. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39981. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39983. }
  39984. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39985. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39986. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39987. }
  39988. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39989. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39991. }
  39992. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39993. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39995. }
  39996. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39997. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39998. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39999. }
  40000. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40001. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40002. mesh.setIndices(indicesData);
  40003. }
  40004. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40005. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40006. mesh.subMeshes = [];
  40007. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40008. var materialIndex = subMeshesData[(i * 5) + 0];
  40009. var verticesStart = subMeshesData[(i * 5) + 1];
  40010. var verticesCount = subMeshesData[(i * 5) + 2];
  40011. var indexStart = subMeshesData[(i * 5) + 3];
  40012. var indexCount = subMeshesData[(i * 5) + 4];
  40013. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40014. }
  40015. }
  40016. }
  40017. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40019. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40020. if (parsedGeometry.uvs) {
  40021. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40022. }
  40023. if (parsedGeometry.uvs2) {
  40024. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40025. }
  40026. if (parsedGeometry.uvs3) {
  40027. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40028. }
  40029. if (parsedGeometry.uvs4) {
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40031. }
  40032. if (parsedGeometry.uvs5) {
  40033. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40034. }
  40035. if (parsedGeometry.uvs6) {
  40036. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40037. }
  40038. if (parsedGeometry.colors) {
  40039. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40040. }
  40041. if (parsedGeometry.matricesIndices) {
  40042. if (!parsedGeometry.matricesIndices._isExpanded) {
  40043. var floatIndices = [];
  40044. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40045. var matricesIndex = parsedGeometry.matricesIndices[i];
  40046. floatIndices.push(matricesIndex & 0x000000FF);
  40047. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40048. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40049. floatIndices.push(matricesIndex >> 24);
  40050. }
  40051. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40052. }
  40053. else {
  40054. delete parsedGeometry.matricesIndices._isExpanded;
  40055. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40056. }
  40057. }
  40058. if (parsedGeometry.matricesIndicesExtra) {
  40059. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40060. var floatIndices = [];
  40061. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40062. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40063. floatIndices.push(matricesIndex & 0x000000FF);
  40064. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40065. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40066. floatIndices.push(matricesIndex >> 24);
  40067. }
  40068. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40069. }
  40070. else {
  40071. delete parsedGeometry.matricesIndices._isExpanded;
  40072. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40073. }
  40074. }
  40075. if (parsedGeometry.matricesWeights) {
  40076. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40077. }
  40078. if (parsedGeometry.matricesWeightsExtra) {
  40079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40080. }
  40081. mesh.setIndices(parsedGeometry.indices);
  40082. }
  40083. // SubMeshes
  40084. if (parsedGeometry.subMeshes) {
  40085. mesh.subMeshes = [];
  40086. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40087. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40088. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40089. }
  40090. }
  40091. // Flat shading
  40092. if (mesh._shouldGenerateFlatShading) {
  40093. mesh.convertToFlatShadedMesh();
  40094. delete mesh._shouldGenerateFlatShading;
  40095. }
  40096. // Update
  40097. mesh.computeWorldMatrix(true);
  40098. // Octree
  40099. if (scene['_selectionOctree']) {
  40100. scene['_selectionOctree'].addMesh(mesh);
  40101. }
  40102. };
  40103. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40104. if (scene.getGeometryByID(parsedVertexData.id)) {
  40105. return null; // null since geometry could be something else than a box...
  40106. }
  40107. var geometry = new Geometry(parsedVertexData.id, scene);
  40108. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40109. if (parsedVertexData.delayLoadingFile) {
  40110. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40111. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40112. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40113. geometry._delayInfo = [];
  40114. if (parsedVertexData.hasUVs) {
  40115. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40116. }
  40117. if (parsedVertexData.hasUVs2) {
  40118. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40119. }
  40120. if (parsedVertexData.hasUVs3) {
  40121. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40122. }
  40123. if (parsedVertexData.hasUVs4) {
  40124. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40125. }
  40126. if (parsedVertexData.hasUVs5) {
  40127. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40128. }
  40129. if (parsedVertexData.hasUVs6) {
  40130. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40131. }
  40132. if (parsedVertexData.hasColors) {
  40133. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40134. }
  40135. if (parsedVertexData.hasMatricesIndices) {
  40136. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40137. }
  40138. if (parsedVertexData.hasMatricesWeights) {
  40139. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40140. }
  40141. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40142. }
  40143. else {
  40144. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40145. }
  40146. scene.pushGeometry(geometry, true);
  40147. return geometry;
  40148. };
  40149. return Geometry;
  40150. }());
  40151. BABYLON.Geometry = Geometry;
  40152. /////// Primitives //////////////////////////////////////////////
  40153. (function (Geometry) {
  40154. var Primitives;
  40155. (function (Primitives) {
  40156. /// Abstract class
  40157. var _Primitive = (function (_super) {
  40158. __extends(_Primitive, _super);
  40159. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  40160. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  40161. _this._canBeRegenerated = _canBeRegenerated;
  40162. _this._beingRegenerated = true;
  40163. _this.regenerate();
  40164. _this._beingRegenerated = false;
  40165. return _this;
  40166. }
  40167. _Primitive.prototype.canBeRegenerated = function () {
  40168. return this._canBeRegenerated;
  40169. };
  40170. _Primitive.prototype.regenerate = function () {
  40171. if (!this._canBeRegenerated) {
  40172. return;
  40173. }
  40174. this._beingRegenerated = true;
  40175. this.setAllVerticesData(this._regenerateVertexData(), false);
  40176. this._beingRegenerated = false;
  40177. };
  40178. _Primitive.prototype.asNewGeometry = function (id) {
  40179. return _super.prototype.copy.call(this, id);
  40180. };
  40181. // overrides
  40182. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  40183. if (!this._beingRegenerated) {
  40184. return;
  40185. }
  40186. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40187. };
  40188. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  40189. if (!this._beingRegenerated) {
  40190. return;
  40191. }
  40192. _super.prototype.setVerticesData.call(this, kind, data, false);
  40193. };
  40194. // to override
  40195. // protected
  40196. _Primitive.prototype._regenerateVertexData = function () {
  40197. throw new Error("Abstract method");
  40198. };
  40199. _Primitive.prototype.copy = function (id) {
  40200. throw new Error("Must be overriden in sub-classes.");
  40201. };
  40202. _Primitive.prototype.serialize = function () {
  40203. var serializationObject = _super.prototype.serialize.call(this);
  40204. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40205. return serializationObject;
  40206. };
  40207. return _Primitive;
  40208. }(Geometry));
  40209. Primitives._Primitive = _Primitive;
  40210. var Ribbon = (function (_super) {
  40211. __extends(Ribbon, _super);
  40212. // Members
  40213. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  40214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40216. _this.pathArray = pathArray;
  40217. _this.closeArray = closeArray;
  40218. _this.closePath = closePath;
  40219. _this.offset = offset;
  40220. _this.side = side;
  40221. return _this;
  40222. }
  40223. Ribbon.prototype._regenerateVertexData = function () {
  40224. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40225. };
  40226. Ribbon.prototype.copy = function (id) {
  40227. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  40228. };
  40229. return Ribbon;
  40230. }(_Primitive));
  40231. Primitives.Ribbon = Ribbon;
  40232. var Box = (function (_super) {
  40233. __extends(Box, _super);
  40234. // Members
  40235. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  40236. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40237. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40238. _this.size = size;
  40239. _this.side = side;
  40240. return _this;
  40241. }
  40242. Box.prototype._regenerateVertexData = function () {
  40243. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40244. };
  40245. Box.prototype.copy = function (id) {
  40246. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40247. };
  40248. Box.prototype.serialize = function () {
  40249. var serializationObject = _super.prototype.serialize.call(this);
  40250. serializationObject.size = this.size;
  40251. return serializationObject;
  40252. };
  40253. Box.Parse = function (parsedBox, scene) {
  40254. if (scene.getGeometryByID(parsedBox.id)) {
  40255. return null; // null since geometry could be something else than a box...
  40256. }
  40257. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40258. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40259. scene.pushGeometry(box, true);
  40260. return box;
  40261. };
  40262. return Box;
  40263. }(_Primitive));
  40264. Primitives.Box = Box;
  40265. var Sphere = (function (_super) {
  40266. __extends(Sphere, _super);
  40267. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  40268. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40269. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40270. _this.segments = segments;
  40271. _this.diameter = diameter;
  40272. _this.side = side;
  40273. return _this;
  40274. }
  40275. Sphere.prototype._regenerateVertexData = function () {
  40276. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40277. };
  40278. Sphere.prototype.copy = function (id) {
  40279. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40280. };
  40281. Sphere.prototype.serialize = function () {
  40282. var serializationObject = _super.prototype.serialize.call(this);
  40283. serializationObject.segments = this.segments;
  40284. serializationObject.diameter = this.diameter;
  40285. return serializationObject;
  40286. };
  40287. Sphere.Parse = function (parsedSphere, scene) {
  40288. if (scene.getGeometryByID(parsedSphere.id)) {
  40289. return null; // null since geometry could be something else than a sphere...
  40290. }
  40291. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40292. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40293. scene.pushGeometry(sphere, true);
  40294. return sphere;
  40295. };
  40296. return Sphere;
  40297. }(_Primitive));
  40298. Primitives.Sphere = Sphere;
  40299. var Disc = (function (_super) {
  40300. __extends(Disc, _super);
  40301. // Members
  40302. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  40303. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40304. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40305. _this.radius = radius;
  40306. _this.tessellation = tessellation;
  40307. _this.side = side;
  40308. return _this;
  40309. }
  40310. Disc.prototype._regenerateVertexData = function () {
  40311. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40312. };
  40313. Disc.prototype.copy = function (id) {
  40314. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40315. };
  40316. return Disc;
  40317. }(_Primitive));
  40318. Primitives.Disc = Disc;
  40319. var Cylinder = (function (_super) {
  40320. __extends(Cylinder, _super);
  40321. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  40322. if (subdivisions === void 0) { subdivisions = 1; }
  40323. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40324. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40325. _this.height = height;
  40326. _this.diameterTop = diameterTop;
  40327. _this.diameterBottom = diameterBottom;
  40328. _this.tessellation = tessellation;
  40329. _this.subdivisions = subdivisions;
  40330. _this.side = side;
  40331. return _this;
  40332. }
  40333. Cylinder.prototype._regenerateVertexData = function () {
  40334. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40335. };
  40336. Cylinder.prototype.copy = function (id) {
  40337. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40338. };
  40339. Cylinder.prototype.serialize = function () {
  40340. var serializationObject = _super.prototype.serialize.call(this);
  40341. serializationObject.height = this.height;
  40342. serializationObject.diameterTop = this.diameterTop;
  40343. serializationObject.diameterBottom = this.diameterBottom;
  40344. serializationObject.tessellation = this.tessellation;
  40345. return serializationObject;
  40346. };
  40347. Cylinder.Parse = function (parsedCylinder, scene) {
  40348. if (scene.getGeometryByID(parsedCylinder.id)) {
  40349. return null; // null since geometry could be something else than a cylinder...
  40350. }
  40351. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40352. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40353. scene.pushGeometry(cylinder, true);
  40354. return cylinder;
  40355. };
  40356. return Cylinder;
  40357. }(_Primitive));
  40358. Primitives.Cylinder = Cylinder;
  40359. var Torus = (function (_super) {
  40360. __extends(Torus, _super);
  40361. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  40362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40364. _this.diameter = diameter;
  40365. _this.thickness = thickness;
  40366. _this.tessellation = tessellation;
  40367. _this.side = side;
  40368. return _this;
  40369. }
  40370. Torus.prototype._regenerateVertexData = function () {
  40371. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40372. };
  40373. Torus.prototype.copy = function (id) {
  40374. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40375. };
  40376. Torus.prototype.serialize = function () {
  40377. var serializationObject = _super.prototype.serialize.call(this);
  40378. serializationObject.diameter = this.diameter;
  40379. serializationObject.thickness = this.thickness;
  40380. serializationObject.tessellation = this.tessellation;
  40381. return serializationObject;
  40382. };
  40383. Torus.Parse = function (parsedTorus, scene) {
  40384. if (scene.getGeometryByID(parsedTorus.id)) {
  40385. return null; // null since geometry could be something else than a torus...
  40386. }
  40387. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40388. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40389. scene.pushGeometry(torus, true);
  40390. return torus;
  40391. };
  40392. return Torus;
  40393. }(_Primitive));
  40394. Primitives.Torus = Torus;
  40395. var Ground = (function (_super) {
  40396. __extends(Ground, _super);
  40397. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  40398. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40399. _this.width = width;
  40400. _this.height = height;
  40401. _this.subdivisions = subdivisions;
  40402. return _this;
  40403. }
  40404. Ground.prototype._regenerateVertexData = function () {
  40405. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40406. };
  40407. Ground.prototype.copy = function (id) {
  40408. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40409. };
  40410. Ground.prototype.serialize = function () {
  40411. var serializationObject = _super.prototype.serialize.call(this);
  40412. serializationObject.width = this.width;
  40413. serializationObject.height = this.height;
  40414. serializationObject.subdivisions = this.subdivisions;
  40415. return serializationObject;
  40416. };
  40417. Ground.Parse = function (parsedGround, scene) {
  40418. if (scene.getGeometryByID(parsedGround.id)) {
  40419. return null; // null since geometry could be something else than a ground...
  40420. }
  40421. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40422. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40423. scene.pushGeometry(ground, true);
  40424. return ground;
  40425. };
  40426. return Ground;
  40427. }(_Primitive));
  40428. Primitives.Ground = Ground;
  40429. var TiledGround = (function (_super) {
  40430. __extends(TiledGround, _super);
  40431. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  40432. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40433. _this.xmin = xmin;
  40434. _this.zmin = zmin;
  40435. _this.xmax = xmax;
  40436. _this.zmax = zmax;
  40437. _this.subdivisions = subdivisions;
  40438. _this.precision = precision;
  40439. return _this;
  40440. }
  40441. TiledGround.prototype._regenerateVertexData = function () {
  40442. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40443. };
  40444. TiledGround.prototype.copy = function (id) {
  40445. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40446. };
  40447. return TiledGround;
  40448. }(_Primitive));
  40449. Primitives.TiledGround = TiledGround;
  40450. var Plane = (function (_super) {
  40451. __extends(Plane, _super);
  40452. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  40453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40455. _this.size = size;
  40456. _this.side = side;
  40457. return _this;
  40458. }
  40459. Plane.prototype._regenerateVertexData = function () {
  40460. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40461. };
  40462. Plane.prototype.copy = function (id) {
  40463. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40464. };
  40465. Plane.prototype.serialize = function () {
  40466. var serializationObject = _super.prototype.serialize.call(this);
  40467. serializationObject.size = this.size;
  40468. return serializationObject;
  40469. };
  40470. Plane.Parse = function (parsedPlane, scene) {
  40471. if (scene.getGeometryByID(parsedPlane.id)) {
  40472. return null; // null since geometry could be something else than a ground...
  40473. }
  40474. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40475. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40476. scene.pushGeometry(plane, true);
  40477. return plane;
  40478. };
  40479. return Plane;
  40480. }(_Primitive));
  40481. Primitives.Plane = Plane;
  40482. var TorusKnot = (function (_super) {
  40483. __extends(TorusKnot, _super);
  40484. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  40485. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40486. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40487. _this.radius = radius;
  40488. _this.tube = tube;
  40489. _this.radialSegments = radialSegments;
  40490. _this.tubularSegments = tubularSegments;
  40491. _this.p = p;
  40492. _this.q = q;
  40493. _this.side = side;
  40494. return _this;
  40495. }
  40496. TorusKnot.prototype._regenerateVertexData = function () {
  40497. 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 });
  40498. };
  40499. TorusKnot.prototype.copy = function (id) {
  40500. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40501. };
  40502. TorusKnot.prototype.serialize = function () {
  40503. var serializationObject = _super.prototype.serialize.call(this);
  40504. serializationObject.radius = this.radius;
  40505. serializationObject.tube = this.tube;
  40506. serializationObject.radialSegments = this.radialSegments;
  40507. serializationObject.tubularSegments = this.tubularSegments;
  40508. serializationObject.p = this.p;
  40509. serializationObject.q = this.q;
  40510. return serializationObject;
  40511. };
  40512. ;
  40513. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  40514. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40515. return null; // null since geometry could be something else than a ground...
  40516. }
  40517. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40518. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40519. scene.pushGeometry(torusKnot, true);
  40520. return torusKnot;
  40521. };
  40522. return TorusKnot;
  40523. }(_Primitive));
  40524. Primitives.TorusKnot = TorusKnot;
  40525. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  40526. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  40527. })(BABYLON || (BABYLON = {}));
  40528. //# sourceMappingURL=babylon.geometry.js.map
  40529. /// <reference path="babylon.mesh.ts" />
  40530. var BABYLON;
  40531. (function (BABYLON) {
  40532. var GroundMesh = (function (_super) {
  40533. __extends(GroundMesh, _super);
  40534. function GroundMesh(name, scene) {
  40535. var _this = _super.call(this, name, scene) || this;
  40536. _this.generateOctree = false;
  40537. _this._worldInverse = new BABYLON.Matrix();
  40538. return _this;
  40539. }
  40540. GroundMesh.prototype.getClassName = function () {
  40541. return "GroundMesh";
  40542. };
  40543. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40544. get: function () {
  40545. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40551. get: function () {
  40552. return this._subdivisionsX;
  40553. },
  40554. enumerable: true,
  40555. configurable: true
  40556. });
  40557. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40558. get: function () {
  40559. return this._subdivisionsY;
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40565. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40566. this._subdivisionsX = chunksCount;
  40567. this._subdivisionsY = chunksCount;
  40568. this.subdivide(chunksCount);
  40569. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40570. };
  40571. /**
  40572. * Returns a height (y) value in the Worl system :
  40573. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40574. * Returns the ground y position if (x, z) are outside the ground surface.
  40575. */
  40576. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40577. var world = this.getWorldMatrix();
  40578. var invMat = BABYLON.Tmp.Matrix[5];
  40579. world.invertToRef(invMat);
  40580. var tmpVect = BABYLON.Tmp.Vector3[8];
  40581. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40582. x = tmpVect.x;
  40583. z = tmpVect.z;
  40584. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40585. return this.position.y;
  40586. }
  40587. if (!this._heightQuads || this._heightQuads.length == 0) {
  40588. this._initHeightQuads();
  40589. this._computeHeightQuads();
  40590. }
  40591. var facet = this._getFacetAt(x, z);
  40592. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40593. // return y in the World system
  40594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40595. return tmpVect.y;
  40596. };
  40597. /**
  40598. * Returns a normalized vector (Vector3) orthogonal to the ground
  40599. * at the ground coordinates (x, z) expressed in the World system.
  40600. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40601. */
  40602. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40603. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40604. this.getNormalAtCoordinatesToRef(x, z, normal);
  40605. return normal;
  40606. };
  40607. /**
  40608. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40609. * at the ground coordinates (x, z) expressed in the World system.
  40610. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40611. * Returns the GroundMesh.
  40612. */
  40613. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40614. var world = this.getWorldMatrix();
  40615. var tmpMat = BABYLON.Tmp.Matrix[5];
  40616. world.invertToRef(tmpMat);
  40617. var tmpVect = BABYLON.Tmp.Vector3[8];
  40618. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40619. x = tmpVect.x;
  40620. z = tmpVect.z;
  40621. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40622. return this;
  40623. }
  40624. if (!this._heightQuads || this._heightQuads.length == 0) {
  40625. this._initHeightQuads();
  40626. this._computeHeightQuads();
  40627. }
  40628. var facet = this._getFacetAt(x, z);
  40629. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40630. return this;
  40631. };
  40632. /**
  40633. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40634. * if the ground has been updated.
  40635. * This can be used in the render loop.
  40636. * Returns the GroundMesh.
  40637. */
  40638. GroundMesh.prototype.updateCoordinateHeights = function () {
  40639. if (!this._heightQuads || this._heightQuads.length == 0) {
  40640. this._initHeightQuads();
  40641. }
  40642. this._computeHeightQuads();
  40643. return this;
  40644. };
  40645. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40646. GroundMesh.prototype._getFacetAt = function (x, z) {
  40647. // retrieve col and row from x, z coordinates in the ground local system
  40648. var subdivisionsX = this._subdivisionsX;
  40649. var subdivisionsY = this._subdivisionsY;
  40650. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40651. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40652. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40653. var facet;
  40654. if (z < quad.slope.x * x + quad.slope.y) {
  40655. facet = quad.facet1;
  40656. }
  40657. else {
  40658. facet = quad.facet2;
  40659. }
  40660. return facet;
  40661. };
  40662. // Creates and populates the heightMap array with "facet" elements :
  40663. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40664. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40665. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40666. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40667. // Returns the GroundMesh.
  40668. GroundMesh.prototype._initHeightQuads = function () {
  40669. var subdivisionsX = this._subdivisionsX;
  40670. var subdivisionsY = this._subdivisionsY;
  40671. this._heightQuads = new Array();
  40672. for (var row = 0; row < subdivisionsY; row++) {
  40673. for (var col = 0; col < subdivisionsX; col++) {
  40674. 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) };
  40675. this._heightQuads[row * subdivisionsX + col] = quad;
  40676. }
  40677. }
  40678. return this;
  40679. };
  40680. // Compute each quad element values and update the the heightMap array :
  40681. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40682. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40683. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40684. // Returns the GroundMesh.
  40685. GroundMesh.prototype._computeHeightQuads = function () {
  40686. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40687. var v1 = BABYLON.Tmp.Vector3[3];
  40688. var v2 = BABYLON.Tmp.Vector3[2];
  40689. var v3 = BABYLON.Tmp.Vector3[1];
  40690. var v4 = BABYLON.Tmp.Vector3[0];
  40691. var v1v2 = BABYLON.Tmp.Vector3[4];
  40692. var v1v3 = BABYLON.Tmp.Vector3[5];
  40693. var v1v4 = BABYLON.Tmp.Vector3[6];
  40694. var norm1 = BABYLON.Tmp.Vector3[7];
  40695. var norm2 = BABYLON.Tmp.Vector3[8];
  40696. var i = 0;
  40697. var j = 0;
  40698. var k = 0;
  40699. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40700. var h = 0;
  40701. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40702. var d2 = 0;
  40703. var subdivisionsX = this._subdivisionsX;
  40704. var subdivisionsY = this._subdivisionsY;
  40705. for (var row = 0; row < subdivisionsY; row++) {
  40706. for (var col = 0; col < subdivisionsX; col++) {
  40707. i = col * 3;
  40708. j = row * (subdivisionsX + 1) * 3;
  40709. k = (row + 1) * (subdivisionsX + 1) * 3;
  40710. v1.x = positions[j + i];
  40711. v1.y = positions[j + i + 1];
  40712. v1.z = positions[j + i + 2];
  40713. v2.x = positions[j + i + 3];
  40714. v2.y = positions[j + i + 4];
  40715. v2.z = positions[j + i + 5];
  40716. v3.x = positions[k + i];
  40717. v3.y = positions[k + i + 1];
  40718. v3.z = positions[k + i + 2];
  40719. v4.x = positions[k + i + 3];
  40720. v4.y = positions[k + i + 4];
  40721. v4.z = positions[k + i + 5];
  40722. // 2D slope V1V4
  40723. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40724. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40725. // facet equations :
  40726. // we compute each facet normal vector
  40727. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40728. // we compute the value d by applying the equation to v1 which belongs to the plane
  40729. // then we store the facet equation in a Vector4
  40730. v2.subtractToRef(v1, v1v2);
  40731. v3.subtractToRef(v1, v1v3);
  40732. v4.subtractToRef(v1, v1v4);
  40733. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40734. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40735. norm1.normalize();
  40736. norm2.normalize();
  40737. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40738. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40739. var quad = this._heightQuads[row * subdivisionsX + col];
  40740. quad.slope.copyFromFloats(cd, h);
  40741. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40742. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40743. }
  40744. }
  40745. return this;
  40746. };
  40747. return GroundMesh;
  40748. }(BABYLON.Mesh));
  40749. BABYLON.GroundMesh = GroundMesh;
  40750. })(BABYLON || (BABYLON = {}));
  40751. //# sourceMappingURL=babylon.groundMesh.js.map
  40752. /// <reference path="babylon.mesh.ts" />
  40753. var BABYLON;
  40754. (function (BABYLON) {
  40755. var LinesMesh = (function (_super) {
  40756. __extends(LinesMesh, _super);
  40757. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  40758. if (parent === void 0) { parent = null; }
  40759. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40760. _this.color = new BABYLON.Color3(1, 1, 1);
  40761. _this.alpha = 1;
  40762. _this._positionBuffer = {};
  40763. if (source) {
  40764. _this.color = source.color.clone();
  40765. _this.alpha = source.alpha;
  40766. }
  40767. _this._intersectionThreshold = 0.1;
  40768. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  40769. attributes: [BABYLON.VertexBuffer.PositionKind],
  40770. uniforms: ["worldViewProjection", "color"],
  40771. needAlphaBlending: true
  40772. });
  40773. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  40774. return _this;
  40775. }
  40776. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40777. /**
  40778. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40779. * This margin is expressed in world space coordinates, so its value may vary.
  40780. * Default value is 0.1
  40781. * @returns the intersection Threshold value.
  40782. */
  40783. get: function () {
  40784. return this._intersectionThreshold;
  40785. },
  40786. /**
  40787. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40788. * This margin is expressed in world space coordinates, so its value may vary.
  40789. * @param value the new threshold to apply
  40790. */
  40791. set: function (value) {
  40792. if (this._intersectionThreshold === value) {
  40793. return;
  40794. }
  40795. this._intersectionThreshold = value;
  40796. if (this.geometry) {
  40797. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40798. }
  40799. },
  40800. enumerable: true,
  40801. configurable: true
  40802. });
  40803. /**
  40804. * Returns the string "LineMesh"
  40805. */
  40806. LinesMesh.prototype.getClassName = function () {
  40807. return "LinesMesh";
  40808. };
  40809. Object.defineProperty(LinesMesh.prototype, "material", {
  40810. get: function () {
  40811. return this._colorShader;
  40812. },
  40813. enumerable: true,
  40814. configurable: true
  40815. });
  40816. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40817. get: function () {
  40818. return false;
  40819. },
  40820. enumerable: true,
  40821. configurable: true
  40822. });
  40823. LinesMesh.prototype.createInstance = function (name) {
  40824. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40825. return null;
  40826. };
  40827. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40828. var engine = this.getScene().getEngine();
  40829. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  40830. // VBOs
  40831. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  40832. // Color
  40833. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40834. return this;
  40835. };
  40836. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40837. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40838. return this;
  40839. }
  40840. var engine = this.getScene().getEngine();
  40841. // Draw order
  40842. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40843. return this;
  40844. };
  40845. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40846. this._colorShader.dispose();
  40847. _super.prototype.dispose.call(this, doNotRecurse);
  40848. };
  40849. /**
  40850. * Returns a new LineMesh object cloned from the current one.
  40851. */
  40852. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40853. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40854. };
  40855. return LinesMesh;
  40856. }(BABYLON.Mesh));
  40857. BABYLON.LinesMesh = LinesMesh;
  40858. })(BABYLON || (BABYLON = {}));
  40859. //# sourceMappingURL=babylon.linesMesh.js.map
  40860. var BABYLON;
  40861. (function (BABYLON) {
  40862. var DefaultLoadingScreen = (function () {
  40863. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  40864. if (_loadingText === void 0) { _loadingText = ""; }
  40865. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  40866. var _this = this;
  40867. this._renderingCanvas = _renderingCanvas;
  40868. this._loadingText = _loadingText;
  40869. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  40870. // Resize
  40871. this._resizeLoadingUI = function () {
  40872. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  40873. _this._loadingDiv.style.position = "absolute";
  40874. _this._loadingDiv.style.left = canvasRect.left + "px";
  40875. _this._loadingDiv.style.top = canvasRect.top + "px";
  40876. _this._loadingDiv.style.width = canvasRect.width + "px";
  40877. _this._loadingDiv.style.height = canvasRect.height + "px";
  40878. };
  40879. }
  40880. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  40881. var _this = this;
  40882. if (this._loadingDiv) {
  40883. // Do not add a loading screen if there is already one
  40884. return;
  40885. }
  40886. this._loadingDiv = document.createElement("div");
  40887. this._loadingDiv.id = "babylonjsLoadingDiv";
  40888. this._loadingDiv.style.opacity = "0";
  40889. this._loadingDiv.style.transition = "opacity 1.5s ease";
  40890. // Loading text
  40891. this._loadingTextDiv = document.createElement("div");
  40892. this._loadingTextDiv.style.position = "absolute";
  40893. this._loadingTextDiv.style.left = "0";
  40894. this._loadingTextDiv.style.top = "50%";
  40895. this._loadingTextDiv.style.marginTop = "80px";
  40896. this._loadingTextDiv.style.width = "100%";
  40897. this._loadingTextDiv.style.height = "20px";
  40898. this._loadingTextDiv.style.fontFamily = "Arial";
  40899. this._loadingTextDiv.style.fontSize = "14px";
  40900. this._loadingTextDiv.style.color = "white";
  40901. this._loadingTextDiv.style.textAlign = "center";
  40902. this._loadingTextDiv.innerHTML = "Loading";
  40903. this._loadingDiv.appendChild(this._loadingTextDiv);
  40904. //set the predefined text
  40905. this._loadingTextDiv.innerHTML = this._loadingText;
  40906. // Loading img
  40907. var imgBack = new Image();
  40908. 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==";
  40909. imgBack.style.position = "absolute";
  40910. imgBack.style.left = "50%";
  40911. imgBack.style.top = "50%";
  40912. imgBack.style.marginLeft = "-50px";
  40913. imgBack.style.marginTop = "-50px";
  40914. imgBack.style.transition = "transform 1.0s ease";
  40915. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  40916. var deg = 360;
  40917. var onTransitionEnd = function () {
  40918. deg += 360;
  40919. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  40920. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  40921. };
  40922. imgBack.addEventListener("transitionend", onTransitionEnd);
  40923. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  40924. this._loadingDiv.appendChild(imgBack);
  40925. // front image
  40926. var imgFront = new Image();
  40927. 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=";
  40928. imgFront.style.position = "absolute";
  40929. imgFront.style.left = "50%";
  40930. imgFront.style.top = "50%";
  40931. imgFront.style.marginLeft = "-50px";
  40932. imgFront.style.marginTop = "-50px";
  40933. this._loadingDiv.appendChild(imgFront);
  40934. this._resizeLoadingUI();
  40935. window.addEventListener("resize", this._resizeLoadingUI);
  40936. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  40937. document.body.appendChild(this._loadingDiv);
  40938. setTimeout(function () {
  40939. _this._loadingDiv.style.opacity = "1";
  40940. imgBack.style.transform = "rotateZ(360deg)";
  40941. imgBack.style.webkitTransform = "rotateZ(360deg)";
  40942. }, 0);
  40943. };
  40944. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  40945. var _this = this;
  40946. if (!this._loadingDiv) {
  40947. return;
  40948. }
  40949. var onTransitionEnd = function () {
  40950. if (!_this._loadingDiv) {
  40951. return;
  40952. }
  40953. document.body.removeChild(_this._loadingDiv);
  40954. window.removeEventListener("resize", _this._resizeLoadingUI);
  40955. _this._loadingDiv = null;
  40956. };
  40957. this._loadingDiv.style.opacity = "0";
  40958. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  40959. };
  40960. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  40961. set: function (text) {
  40962. this._loadingText = text;
  40963. if (this._loadingTextDiv) {
  40964. this._loadingTextDiv.innerHTML = this._loadingText;
  40965. }
  40966. },
  40967. enumerable: true,
  40968. configurable: true
  40969. });
  40970. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  40971. get: function () {
  40972. return this._loadingDivBackgroundColor;
  40973. },
  40974. set: function (color) {
  40975. this._loadingDivBackgroundColor = color;
  40976. if (!this._loadingDiv) {
  40977. return;
  40978. }
  40979. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  40980. },
  40981. enumerable: true,
  40982. configurable: true
  40983. });
  40984. return DefaultLoadingScreen;
  40985. }());
  40986. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  40987. })(BABYLON || (BABYLON = {}));
  40988. //# sourceMappingURL=babylon.loadingScreen.js.map
  40989. var BABYLON;
  40990. (function (BABYLON) {
  40991. var AudioEngine = (function () {
  40992. function AudioEngine() {
  40993. this._audioContext = null;
  40994. this._audioContextInitialized = false;
  40995. this.canUseWebAudio = false;
  40996. this.WarnedWebAudioUnsupported = false;
  40997. this.unlocked = false;
  40998. this.isMP3supported = false;
  40999. this.isOGGsupported = false;
  41000. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41001. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41002. this.canUseWebAudio = true;
  41003. }
  41004. var audioElem = document.createElement('audio');
  41005. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41006. this.isMP3supported = true;
  41007. }
  41008. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41009. this.isOGGsupported = true;
  41010. }
  41011. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41012. this._unlockiOSaudio();
  41013. }
  41014. else {
  41015. this.unlocked = true;
  41016. }
  41017. }
  41018. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41019. get: function () {
  41020. if (!this._audioContextInitialized) {
  41021. this._initializeAudioContext();
  41022. }
  41023. return this._audioContext;
  41024. },
  41025. enumerable: true,
  41026. configurable: true
  41027. });
  41028. AudioEngine.prototype._unlockiOSaudio = function () {
  41029. var _this = this;
  41030. var unlockaudio = function () {
  41031. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41032. var source = _this.audioContext.createBufferSource();
  41033. source.buffer = buffer;
  41034. source.connect(_this.audioContext.destination);
  41035. source.start(0);
  41036. setTimeout(function () {
  41037. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41038. _this.unlocked = true;
  41039. window.removeEventListener('touchend', unlockaudio, false);
  41040. if (_this.onAudioUnlocked) {
  41041. _this.onAudioUnlocked();
  41042. }
  41043. }
  41044. }, 0);
  41045. };
  41046. window.addEventListener('touchend', unlockaudio, false);
  41047. };
  41048. AudioEngine.prototype._initializeAudioContext = function () {
  41049. try {
  41050. if (this.canUseWebAudio) {
  41051. this._audioContext = new AudioContext();
  41052. // create a global volume gain node
  41053. this.masterGain = this._audioContext.createGain();
  41054. this.masterGain.gain.value = 1;
  41055. this.masterGain.connect(this._audioContext.destination);
  41056. this._audioContextInitialized = true;
  41057. }
  41058. }
  41059. catch (e) {
  41060. this.canUseWebAudio = false;
  41061. BABYLON.Tools.Error("Web Audio: " + e.message);
  41062. }
  41063. };
  41064. AudioEngine.prototype.dispose = function () {
  41065. if (this.canUseWebAudio && this._audioContextInitialized) {
  41066. if (this._connectedAnalyser) {
  41067. this._connectedAnalyser.stopDebugCanvas();
  41068. this._connectedAnalyser.dispose();
  41069. this.masterGain.disconnect();
  41070. this.masterGain.connect(this._audioContext.destination);
  41071. this._connectedAnalyser = null;
  41072. }
  41073. this.masterGain.gain.value = 1;
  41074. }
  41075. this.WarnedWebAudioUnsupported = false;
  41076. };
  41077. AudioEngine.prototype.getGlobalVolume = function () {
  41078. if (this.canUseWebAudio && this._audioContextInitialized) {
  41079. return this.masterGain.gain.value;
  41080. }
  41081. else {
  41082. return -1;
  41083. }
  41084. };
  41085. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41086. if (this.canUseWebAudio && this._audioContextInitialized) {
  41087. this.masterGain.gain.value = newVolume;
  41088. }
  41089. };
  41090. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41091. if (this._connectedAnalyser) {
  41092. this._connectedAnalyser.stopDebugCanvas();
  41093. }
  41094. if (this.canUseWebAudio && this._audioContextInitialized) {
  41095. this._connectedAnalyser = analyser;
  41096. this.masterGain.disconnect();
  41097. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41098. }
  41099. };
  41100. return AudioEngine;
  41101. }());
  41102. BABYLON.AudioEngine = AudioEngine;
  41103. })(BABYLON || (BABYLON = {}));
  41104. //# sourceMappingURL=babylon.audioEngine.js.map
  41105. var BABYLON;
  41106. (function (BABYLON) {
  41107. var Sound = (function () {
  41108. /**
  41109. * Create a sound and attach it to a scene
  41110. * @param name Name of your sound
  41111. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41112. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41113. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41114. */
  41115. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41116. var _this = this;
  41117. this.autoplay = false;
  41118. this.loop = false;
  41119. this.useCustomAttenuation = false;
  41120. this.spatialSound = false;
  41121. this.refDistance = 1;
  41122. this.rolloffFactor = 1;
  41123. this.maxDistance = 100;
  41124. this.distanceModel = "linear";
  41125. this._panningModel = "equalpower";
  41126. this._playbackRate = 1;
  41127. this._streaming = false;
  41128. this._startTime = 0;
  41129. this._startOffset = 0;
  41130. this._position = BABYLON.Vector3.Zero();
  41131. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41132. this._volume = 1;
  41133. this._isLoaded = false;
  41134. this._isReadyToPlay = false;
  41135. this.isPlaying = false;
  41136. this.isPaused = false;
  41137. this._isDirectional = false;
  41138. // Used if you'd like to create a directional sound.
  41139. // If not set, the sound will be omnidirectional
  41140. this._coneInnerAngle = 360;
  41141. this._coneOuterAngle = 360;
  41142. this._coneOuterGain = 0;
  41143. this._isOutputConnected = false;
  41144. this._urlType = "Unknown";
  41145. this.name = name;
  41146. this._scene = scene;
  41147. this._readyToPlayCallback = readyToPlayCallback;
  41148. // Default custom attenuation function is a linear attenuation
  41149. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41150. if (currentDistance < maxDistance) {
  41151. return currentVolume * (1 - currentDistance / maxDistance);
  41152. }
  41153. else {
  41154. return 0;
  41155. }
  41156. };
  41157. if (options) {
  41158. this.autoplay = options.autoplay || false;
  41159. this.loop = options.loop || false;
  41160. // if volume === 0, we need another way to check this option
  41161. if (options.volume !== undefined) {
  41162. this._volume = options.volume;
  41163. }
  41164. this.spatialSound = options.spatialSound || false;
  41165. this.maxDistance = options.maxDistance || 100;
  41166. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41167. this.rolloffFactor = options.rolloffFactor || 1;
  41168. this.refDistance = options.refDistance || 1;
  41169. this.distanceModel = options.distanceModel || "linear";
  41170. this._playbackRate = options.playbackRate || 1;
  41171. this._streaming = options.streaming || false;
  41172. }
  41173. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41174. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41175. this._soundGain.gain.value = this._volume;
  41176. this._inputAudioNode = this._soundGain;
  41177. this._ouputAudioNode = this._soundGain;
  41178. if (this.spatialSound) {
  41179. this._createSpatialParameters();
  41180. }
  41181. this._scene.mainSoundTrack.AddSound(this);
  41182. var validParameter = true;
  41183. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41184. if (urlOrArrayBuffer) {
  41185. if (typeof (urlOrArrayBuffer) === "string")
  41186. this._urlType = "String";
  41187. if (Array.isArray(urlOrArrayBuffer))
  41188. this._urlType = "Array";
  41189. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41190. this._urlType = "ArrayBuffer";
  41191. var urls = [];
  41192. var codecSupportedFound = false;
  41193. switch (this._urlType) {
  41194. case "ArrayBuffer":
  41195. if (urlOrArrayBuffer.byteLength > 0) {
  41196. codecSupportedFound = true;
  41197. this._soundLoaded(urlOrArrayBuffer);
  41198. }
  41199. break;
  41200. case "String":
  41201. urls.push(urlOrArrayBuffer);
  41202. case "Array":
  41203. if (urls.length === 0)
  41204. urls = urlOrArrayBuffer;
  41205. // If we found a supported format, we load it immediately and stop the loop
  41206. for (var i = 0; i < urls.length; i++) {
  41207. var url = urls[i];
  41208. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41209. codecSupportedFound = true;
  41210. }
  41211. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41212. codecSupportedFound = true;
  41213. }
  41214. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41215. codecSupportedFound = true;
  41216. }
  41217. if (codecSupportedFound) {
  41218. // Loading sound using XHR2
  41219. if (!this._streaming) {
  41220. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41221. }
  41222. else {
  41223. this._htmlAudioElement = new Audio(url);
  41224. this._htmlAudioElement.controls = false;
  41225. this._htmlAudioElement.loop = this.loop;
  41226. this._htmlAudioElement.crossOrigin = "anonymous";
  41227. this._htmlAudioElement.preload = "auto";
  41228. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41229. _this._isReadyToPlay = true;
  41230. if (_this.autoplay) {
  41231. _this.play();
  41232. }
  41233. if (_this._readyToPlayCallback) {
  41234. _this._readyToPlayCallback();
  41235. }
  41236. });
  41237. document.body.appendChild(this._htmlAudioElement);
  41238. }
  41239. break;
  41240. }
  41241. }
  41242. break;
  41243. default:
  41244. validParameter = false;
  41245. break;
  41246. }
  41247. if (!validParameter) {
  41248. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41249. }
  41250. else {
  41251. if (!codecSupportedFound) {
  41252. this._isReadyToPlay = true;
  41253. // Simulating a ready to play event to avoid breaking code path
  41254. if (this._readyToPlayCallback) {
  41255. window.setTimeout(function () {
  41256. _this._readyToPlayCallback();
  41257. }, 1000);
  41258. }
  41259. }
  41260. }
  41261. }
  41262. }
  41263. else {
  41264. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41265. this._scene.mainSoundTrack.AddSound(this);
  41266. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41267. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41268. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41269. }
  41270. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41271. if (this._readyToPlayCallback) {
  41272. window.setTimeout(function () {
  41273. _this._readyToPlayCallback();
  41274. }, 1000);
  41275. }
  41276. }
  41277. }
  41278. Sound.prototype.dispose = function () {
  41279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41280. if (this.isPlaying) {
  41281. this.stop();
  41282. }
  41283. this._isReadyToPlay = false;
  41284. if (this.soundTrackId === -1) {
  41285. this._scene.mainSoundTrack.RemoveSound(this);
  41286. }
  41287. else {
  41288. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41289. }
  41290. if (this._soundGain) {
  41291. this._soundGain.disconnect();
  41292. this._soundGain = null;
  41293. }
  41294. if (this._soundPanner) {
  41295. this._soundPanner.disconnect();
  41296. this._soundPanner = null;
  41297. }
  41298. if (this._soundSource) {
  41299. this._soundSource.disconnect();
  41300. this._soundSource = null;
  41301. }
  41302. this._audioBuffer = null;
  41303. if (this._htmlAudioElement) {
  41304. this._htmlAudioElement.pause();
  41305. this._htmlAudioElement.src = "";
  41306. document.body.removeChild(this._htmlAudioElement);
  41307. }
  41308. if (this._connectedMesh) {
  41309. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41310. this._connectedMesh = null;
  41311. }
  41312. }
  41313. };
  41314. Sound.prototype.isReady = function () {
  41315. return this._isReadyToPlay;
  41316. };
  41317. Sound.prototype._soundLoaded = function (audioData) {
  41318. var _this = this;
  41319. this._isLoaded = true;
  41320. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41321. _this._audioBuffer = buffer;
  41322. _this._isReadyToPlay = true;
  41323. if (_this.autoplay) {
  41324. _this.play();
  41325. }
  41326. if (_this._readyToPlayCallback) {
  41327. _this._readyToPlayCallback();
  41328. }
  41329. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41330. };
  41331. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41333. this._audioBuffer = audioBuffer;
  41334. this._isReadyToPlay = true;
  41335. }
  41336. };
  41337. Sound.prototype.updateOptions = function (options) {
  41338. if (options) {
  41339. this.loop = options.loop || this.loop;
  41340. this.maxDistance = options.maxDistance || this.maxDistance;
  41341. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41342. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41343. this.refDistance = options.refDistance || this.refDistance;
  41344. this.distanceModel = options.distanceModel || this.distanceModel;
  41345. this._playbackRate = options.playbackRate || this._playbackRate;
  41346. this._updateSpatialParameters();
  41347. if (this.isPlaying) {
  41348. if (this._streaming) {
  41349. this._htmlAudioElement.playbackRate = this._playbackRate;
  41350. }
  41351. else {
  41352. this._soundSource.playbackRate.value = this._playbackRate;
  41353. }
  41354. }
  41355. }
  41356. };
  41357. Sound.prototype._createSpatialParameters = function () {
  41358. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41359. if (this._scene.headphone) {
  41360. this._panningModel = "HRTF";
  41361. }
  41362. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41363. this._updateSpatialParameters();
  41364. this._soundPanner.connect(this._ouputAudioNode);
  41365. this._inputAudioNode = this._soundPanner;
  41366. }
  41367. };
  41368. Sound.prototype._updateSpatialParameters = function () {
  41369. if (this.spatialSound) {
  41370. if (this.useCustomAttenuation) {
  41371. // Tricks to disable in a way embedded Web Audio attenuation
  41372. this._soundPanner.distanceModel = "linear";
  41373. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41374. this._soundPanner.refDistance = 1;
  41375. this._soundPanner.rolloffFactor = 1;
  41376. this._soundPanner.panningModel = this._panningModel;
  41377. }
  41378. else {
  41379. this._soundPanner.distanceModel = this.distanceModel;
  41380. this._soundPanner.maxDistance = this.maxDistance;
  41381. this._soundPanner.refDistance = this.refDistance;
  41382. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41383. this._soundPanner.panningModel = this._panningModel;
  41384. }
  41385. }
  41386. };
  41387. Sound.prototype.switchPanningModelToHRTF = function () {
  41388. this._panningModel = "HRTF";
  41389. this._switchPanningModel();
  41390. };
  41391. Sound.prototype.switchPanningModelToEqualPower = function () {
  41392. this._panningModel = "equalpower";
  41393. this._switchPanningModel();
  41394. };
  41395. Sound.prototype._switchPanningModel = function () {
  41396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41397. this._soundPanner.panningModel = this._panningModel;
  41398. }
  41399. };
  41400. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41401. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41402. if (this._isOutputConnected) {
  41403. this._ouputAudioNode.disconnect();
  41404. }
  41405. this._ouputAudioNode.connect(soundTrackAudioNode);
  41406. this._isOutputConnected = true;
  41407. }
  41408. };
  41409. /**
  41410. * Transform this sound into a directional source
  41411. * @param coneInnerAngle Size of the inner cone in degree
  41412. * @param coneOuterAngle Size of the outer cone in degree
  41413. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41414. */
  41415. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41416. if (coneOuterAngle < coneInnerAngle) {
  41417. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41418. return;
  41419. }
  41420. this._coneInnerAngle = coneInnerAngle;
  41421. this._coneOuterAngle = coneOuterAngle;
  41422. this._coneOuterGain = coneOuterGain;
  41423. this._isDirectional = true;
  41424. if (this.isPlaying && this.loop) {
  41425. this.stop();
  41426. this.play();
  41427. }
  41428. };
  41429. Sound.prototype.setPosition = function (newPosition) {
  41430. this._position = newPosition;
  41431. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41432. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41433. }
  41434. };
  41435. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41436. this._localDirection = newLocalDirection;
  41437. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41438. this._updateDirection();
  41439. }
  41440. };
  41441. Sound.prototype._updateDirection = function () {
  41442. var mat = this._connectedMesh.getWorldMatrix();
  41443. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41444. direction.normalize();
  41445. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41446. };
  41447. Sound.prototype.updateDistanceFromListener = function () {
  41448. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41449. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41450. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41451. }
  41452. };
  41453. Sound.prototype.setAttenuationFunction = function (callback) {
  41454. this._customAttenuationFunction = callback;
  41455. };
  41456. /**
  41457. * Play the sound
  41458. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41459. * @param offset (optional) Start the sound setting it at a specific time
  41460. */
  41461. Sound.prototype.play = function (time, offset) {
  41462. var _this = this;
  41463. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41464. try {
  41465. if (this._startOffset < 0) {
  41466. time = -this._startOffset;
  41467. this._startOffset = 0;
  41468. }
  41469. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41470. if (!this._soundSource || !this._streamingSource) {
  41471. if (this.spatialSound) {
  41472. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41473. if (this._isDirectional) {
  41474. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41475. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41476. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41477. if (this._connectedMesh) {
  41478. this._updateDirection();
  41479. }
  41480. else {
  41481. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41482. }
  41483. }
  41484. }
  41485. }
  41486. if (this._streaming) {
  41487. if (!this._streamingSource) {
  41488. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41489. this._htmlAudioElement.onended = function () { _this._onended(); };
  41490. this._htmlAudioElement.playbackRate = this._playbackRate;
  41491. }
  41492. this._streamingSource.disconnect();
  41493. this._streamingSource.connect(this._inputAudioNode);
  41494. this._htmlAudioElement.play();
  41495. }
  41496. else {
  41497. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41498. this._soundSource.buffer = this._audioBuffer;
  41499. this._soundSource.connect(this._inputAudioNode);
  41500. this._soundSource.loop = this.loop;
  41501. this._soundSource.playbackRate.value = this._playbackRate;
  41502. this._soundSource.onended = function () { _this._onended(); };
  41503. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  41504. }
  41505. this._startTime = startTime;
  41506. this.isPlaying = true;
  41507. this.isPaused = false;
  41508. }
  41509. catch (ex) {
  41510. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  41511. }
  41512. }
  41513. };
  41514. Sound.prototype._onended = function () {
  41515. this.isPlaying = false;
  41516. if (this.onended) {
  41517. this.onended();
  41518. }
  41519. };
  41520. /**
  41521. * Stop the sound
  41522. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  41523. */
  41524. Sound.prototype.stop = function (time) {
  41525. if (this.isPlaying) {
  41526. if (this._streaming) {
  41527. this._htmlAudioElement.pause();
  41528. // Test needed for Firefox or it will generate an Invalid State Error
  41529. if (this._htmlAudioElement.currentTime > 0) {
  41530. this._htmlAudioElement.currentTime = 0;
  41531. }
  41532. }
  41533. else {
  41534. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41535. this._soundSource.stop(stopTime);
  41536. this._soundSource.onended = null;
  41537. if (!this.isPaused) {
  41538. this._startOffset = 0;
  41539. }
  41540. }
  41541. this.isPlaying = false;
  41542. }
  41543. };
  41544. Sound.prototype.pause = function () {
  41545. if (this.isPlaying) {
  41546. this.isPaused = true;
  41547. if (this._streaming) {
  41548. this._htmlAudioElement.pause();
  41549. }
  41550. else {
  41551. this.stop(0);
  41552. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  41553. }
  41554. }
  41555. };
  41556. Sound.prototype.setVolume = function (newVolume, time) {
  41557. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41558. if (time) {
  41559. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  41560. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  41561. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  41562. }
  41563. else {
  41564. this._soundGain.gain.value = newVolume;
  41565. }
  41566. }
  41567. this._volume = newVolume;
  41568. };
  41569. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  41570. this._playbackRate = newPlaybackRate;
  41571. if (this.isPlaying) {
  41572. if (this._streaming) {
  41573. this._htmlAudioElement.playbackRate = this._playbackRate;
  41574. }
  41575. else {
  41576. this._soundSource.playbackRate.value = this._playbackRate;
  41577. }
  41578. }
  41579. };
  41580. Sound.prototype.getVolume = function () {
  41581. return this._volume;
  41582. };
  41583. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  41584. var _this = this;
  41585. if (this._connectedMesh) {
  41586. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41587. this._registerFunc = null;
  41588. }
  41589. this._connectedMesh = meshToConnectTo;
  41590. if (!this.spatialSound) {
  41591. this.spatialSound = true;
  41592. this._createSpatialParameters();
  41593. if (this.isPlaying && this.loop) {
  41594. this.stop();
  41595. this.play();
  41596. }
  41597. }
  41598. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  41599. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  41600. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  41601. };
  41602. Sound.prototype.detachFromMesh = function () {
  41603. if (this._connectedMesh) {
  41604. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41605. this._registerFunc = null;
  41606. this._connectedMesh = null;
  41607. }
  41608. };
  41609. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  41610. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  41611. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  41612. this._updateDirection();
  41613. }
  41614. };
  41615. Sound.prototype.clone = function () {
  41616. var _this = this;
  41617. if (!this._streaming) {
  41618. var setBufferAndRun = function () {
  41619. if (_this._isReadyToPlay) {
  41620. clonedSound._audioBuffer = _this.getAudioBuffer();
  41621. clonedSound._isReadyToPlay = true;
  41622. if (clonedSound.autoplay) {
  41623. clonedSound.play();
  41624. }
  41625. }
  41626. else {
  41627. window.setTimeout(setBufferAndRun, 300);
  41628. }
  41629. };
  41630. var currentOptions = {
  41631. autoplay: this.autoplay, loop: this.loop,
  41632. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  41633. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  41634. refDistance: this.refDistance, distanceModel: this.distanceModel
  41635. };
  41636. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  41637. if (this.useCustomAttenuation) {
  41638. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  41639. }
  41640. clonedSound.setPosition(this._position);
  41641. clonedSound.setPlaybackRate(this._playbackRate);
  41642. setBufferAndRun();
  41643. return clonedSound;
  41644. }
  41645. else {
  41646. return null;
  41647. }
  41648. };
  41649. Sound.prototype.getAudioBuffer = function () {
  41650. return this._audioBuffer;
  41651. };
  41652. Sound.prototype.serialize = function () {
  41653. var serializationObject = {
  41654. name: this.name,
  41655. url: this.name,
  41656. autoplay: this.autoplay,
  41657. loop: this.loop,
  41658. volume: this._volume,
  41659. spatialSound: this.spatialSound,
  41660. maxDistance: this.maxDistance,
  41661. rolloffFactor: this.rolloffFactor,
  41662. refDistance: this.refDistance,
  41663. distanceModel: this.distanceModel,
  41664. playbackRate: this._playbackRate,
  41665. panningModel: this._panningModel,
  41666. soundTrackId: this.soundTrackId
  41667. };
  41668. if (this.spatialSound) {
  41669. if (this._connectedMesh)
  41670. serializationObject.connectedMeshId = this._connectedMesh.id;
  41671. serializationObject.position = this._position.asArray();
  41672. serializationObject.refDistance = this.refDistance;
  41673. serializationObject.distanceModel = this.distanceModel;
  41674. serializationObject.isDirectional = this._isDirectional;
  41675. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  41676. serializationObject.coneInnerAngle = this._coneInnerAngle;
  41677. serializationObject.coneOuterAngle = this._coneOuterAngle;
  41678. serializationObject.coneOuterGain = this._coneOuterGain;
  41679. }
  41680. return serializationObject;
  41681. };
  41682. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  41683. var soundName = parsedSound.name;
  41684. var soundUrl;
  41685. if (parsedSound.url) {
  41686. soundUrl = rootUrl + parsedSound.url;
  41687. }
  41688. else {
  41689. soundUrl = rootUrl + soundName;
  41690. }
  41691. var options = {
  41692. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  41693. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  41694. rolloffFactor: parsedSound.rolloffFactor,
  41695. refDistance: parsedSound.refDistance,
  41696. distanceModel: parsedSound.distanceModel,
  41697. playbackRate: parsedSound.playbackRate
  41698. };
  41699. var newSound;
  41700. if (!sourceSound) {
  41701. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  41702. scene._addPendingData(newSound);
  41703. }
  41704. else {
  41705. var setBufferAndRun = function () {
  41706. if (sourceSound._isReadyToPlay) {
  41707. newSound._audioBuffer = sourceSound.getAudioBuffer();
  41708. newSound._isReadyToPlay = true;
  41709. if (newSound.autoplay) {
  41710. newSound.play();
  41711. }
  41712. }
  41713. else {
  41714. window.setTimeout(setBufferAndRun, 300);
  41715. }
  41716. };
  41717. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  41718. setBufferAndRun();
  41719. }
  41720. if (parsedSound.position) {
  41721. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  41722. newSound.setPosition(soundPosition);
  41723. }
  41724. if (parsedSound.isDirectional) {
  41725. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  41726. if (parsedSound.localDirectionToMesh) {
  41727. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  41728. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  41729. }
  41730. }
  41731. if (parsedSound.connectedMeshId) {
  41732. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  41733. if (connectedMesh) {
  41734. newSound.attachToMesh(connectedMesh);
  41735. }
  41736. }
  41737. return newSound;
  41738. };
  41739. return Sound;
  41740. }());
  41741. BABYLON.Sound = Sound;
  41742. })(BABYLON || (BABYLON = {}));
  41743. //# sourceMappingURL=babylon.sound.js.map
  41744. var BABYLON;
  41745. (function (BABYLON) {
  41746. var SoundTrack = (function () {
  41747. function SoundTrack(scene, options) {
  41748. this.id = -1;
  41749. this._isMainTrack = false;
  41750. this._isInitialized = false;
  41751. this._scene = scene;
  41752. this.soundCollection = new Array();
  41753. this._options = options;
  41754. if (!this._isMainTrack) {
  41755. this._scene.soundTracks.push(this);
  41756. this.id = this._scene.soundTracks.length - 1;
  41757. }
  41758. }
  41759. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  41760. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41761. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  41762. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  41763. if (this._options) {
  41764. if (this._options.volume) {
  41765. this._outputAudioNode.gain.value = this._options.volume;
  41766. }
  41767. if (this._options.mainTrack) {
  41768. this._isMainTrack = this._options.mainTrack;
  41769. }
  41770. }
  41771. this._isInitialized = true;
  41772. }
  41773. };
  41774. SoundTrack.prototype.dispose = function () {
  41775. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41776. if (this._connectedAnalyser) {
  41777. this._connectedAnalyser.stopDebugCanvas();
  41778. }
  41779. while (this.soundCollection.length) {
  41780. this.soundCollection[0].dispose();
  41781. }
  41782. if (this._outputAudioNode) {
  41783. this._outputAudioNode.disconnect();
  41784. }
  41785. this._outputAudioNode = null;
  41786. }
  41787. };
  41788. SoundTrack.prototype.AddSound = function (sound) {
  41789. if (!this._isInitialized) {
  41790. this._initializeSoundTrackAudioGraph();
  41791. }
  41792. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41793. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  41794. }
  41795. if (sound.soundTrackId) {
  41796. if (sound.soundTrackId === -1) {
  41797. this._scene.mainSoundTrack.RemoveSound(sound);
  41798. }
  41799. else {
  41800. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  41801. }
  41802. }
  41803. this.soundCollection.push(sound);
  41804. sound.soundTrackId = this.id;
  41805. };
  41806. SoundTrack.prototype.RemoveSound = function (sound) {
  41807. var index = this.soundCollection.indexOf(sound);
  41808. if (index !== -1) {
  41809. this.soundCollection.splice(index, 1);
  41810. }
  41811. };
  41812. SoundTrack.prototype.setVolume = function (newVolume) {
  41813. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41814. this._outputAudioNode.gain.value = newVolume;
  41815. }
  41816. };
  41817. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  41818. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41819. for (var i = 0; i < this.soundCollection.length; i++) {
  41820. this.soundCollection[i].switchPanningModelToHRTF();
  41821. }
  41822. }
  41823. };
  41824. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  41825. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41826. for (var i = 0; i < this.soundCollection.length; i++) {
  41827. this.soundCollection[i].switchPanningModelToEqualPower();
  41828. }
  41829. }
  41830. };
  41831. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  41832. if (this._connectedAnalyser) {
  41833. this._connectedAnalyser.stopDebugCanvas();
  41834. }
  41835. this._connectedAnalyser = analyser;
  41836. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41837. this._outputAudioNode.disconnect();
  41838. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  41839. }
  41840. };
  41841. return SoundTrack;
  41842. }());
  41843. BABYLON.SoundTrack = SoundTrack;
  41844. })(BABYLON || (BABYLON = {}));
  41845. //# sourceMappingURL=babylon.soundtrack.js.map
  41846. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  41847. /// <reference path="..\Math\babylon.math.ts" />
  41848. var BABYLON;
  41849. (function (BABYLON) {
  41850. /**
  41851. * Special Glow Blur post process only blurring the alpha channel
  41852. * It enforces keeping the most luminous color in the color channel.
  41853. */
  41854. var GlowBlurPostProcess = (function (_super) {
  41855. __extends(GlowBlurPostProcess, _super);
  41856. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  41857. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41858. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  41859. _this.direction = direction;
  41860. _this.blurWidth = blurWidth;
  41861. _this.onApplyObservable.add(function (effect) {
  41862. effect.setFloat2("screenSize", _this.width, _this.height);
  41863. effect.setVector2("direction", _this.direction);
  41864. effect.setFloat("blurWidth", _this.blurWidth);
  41865. });
  41866. return _this;
  41867. }
  41868. return GlowBlurPostProcess;
  41869. }(BABYLON.PostProcess));
  41870. /**
  41871. * The highlight layer Helps adding a glow effect around a mesh.
  41872. *
  41873. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  41874. * glowy meshes to your scene.
  41875. *
  41876. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  41877. */
  41878. var HighlightLayer = (function () {
  41879. /**
  41880. * Instantiates a new highlight Layer and references it to the scene..
  41881. * @param name The name of the layer
  41882. * @param scene The scene to use the layer in
  41883. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  41884. */
  41885. function HighlightLayer(name, scene, options) {
  41886. this._vertexBuffers = {};
  41887. this._mainTextureDesiredSize = { width: 0, height: 0 };
  41888. this._meshes = {};
  41889. this._maxSize = 0;
  41890. this._shouldRender = false;
  41891. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  41892. this._excludedMeshes = {};
  41893. /**
  41894. * Specifies whether or not the inner glow is ACTIVE in the layer.
  41895. */
  41896. this.innerGlow = true;
  41897. /**
  41898. * Specifies whether or not the outer glow is ACTIVE in the layer.
  41899. */
  41900. this.outerGlow = true;
  41901. /**
  41902. * Specifies wether the highlight layer is enabled or not.
  41903. */
  41904. this.isEnabled = true;
  41905. /**
  41906. * An event triggered when the highlight layer has been disposed.
  41907. * @type {BABYLON.Observable}
  41908. */
  41909. this.onDisposeObservable = new BABYLON.Observable();
  41910. /**
  41911. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  41912. * @type {BABYLON.Observable}
  41913. */
  41914. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  41915. /**
  41916. * An event triggered when the highlight layer is being blurred.
  41917. * @type {BABYLON.Observable}
  41918. */
  41919. this.onBeforeBlurObservable = new BABYLON.Observable();
  41920. /**
  41921. * An event triggered when the highlight layer has been blurred.
  41922. * @type {BABYLON.Observable}
  41923. */
  41924. this.onAfterBlurObservable = new BABYLON.Observable();
  41925. /**
  41926. * An event triggered when the glowing blurred texture is being merged in the scene.
  41927. * @type {BABYLON.Observable}
  41928. */
  41929. this.onBeforeComposeObservable = new BABYLON.Observable();
  41930. /**
  41931. * An event triggered when the glowing blurred texture has been merged in the scene.
  41932. * @type {BABYLON.Observable}
  41933. */
  41934. this.onAfterComposeObservable = new BABYLON.Observable();
  41935. /**
  41936. * An event triggered when the highlight layer changes its size.
  41937. * @type {BABYLON.Observable}
  41938. */
  41939. this.onSizeChangedObservable = new BABYLON.Observable();
  41940. this._scene = scene;
  41941. var engine = scene.getEngine();
  41942. this._engine = engine;
  41943. this._maxSize = this._engine.getCaps().maxTextureSize;
  41944. this._scene.highlightLayers.push(this);
  41945. // Warn on stencil.
  41946. if (!this._engine.isStencilEnable) {
  41947. 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 }");
  41948. }
  41949. // Adapt options
  41950. this._options = options || {
  41951. mainTextureRatio: 0.25,
  41952. blurTextureSizeRatio: 0.5,
  41953. blurHorizontalSize: 1,
  41954. blurVerticalSize: 1,
  41955. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  41956. };
  41957. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  41958. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  41959. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  41960. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  41961. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  41962. // VBO
  41963. var vertices = [];
  41964. vertices.push(1, 1);
  41965. vertices.push(-1, 1);
  41966. vertices.push(-1, -1);
  41967. vertices.push(1, -1);
  41968. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  41969. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  41970. // Indices
  41971. var indices = [];
  41972. indices.push(0);
  41973. indices.push(1);
  41974. indices.push(2);
  41975. indices.push(0);
  41976. indices.push(2);
  41977. indices.push(3);
  41978. this._indexBuffer = engine.createIndexBuffer(indices);
  41979. // Effect
  41980. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  41981. // Render target
  41982. this.setMainTextureSize();
  41983. // Create Textures and post processes
  41984. this.createTextureAndPostProcesses();
  41985. }
  41986. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  41987. /**
  41988. * Gets the horizontal size of the blur.
  41989. */
  41990. get: function () {
  41991. return this._horizontalBlurPostprocess.blurWidth;
  41992. },
  41993. /**
  41994. * Specifies the horizontal size of the blur.
  41995. */
  41996. set: function (value) {
  41997. this._horizontalBlurPostprocess.blurWidth = value;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  42003. /**
  42004. * Gets the vertical size of the blur.
  42005. */
  42006. get: function () {
  42007. return this._verticalBlurPostprocess.blurWidth;
  42008. },
  42009. /**
  42010. * Specifies the vertical size of the blur.
  42011. */
  42012. set: function (value) {
  42013. this._verticalBlurPostprocess.blurWidth = value;
  42014. },
  42015. enumerable: true,
  42016. configurable: true
  42017. });
  42018. Object.defineProperty(HighlightLayer.prototype, "camera", {
  42019. /**
  42020. * Gets the camera attached to the layer.
  42021. */
  42022. get: function () {
  42023. return this._options.camera;
  42024. },
  42025. enumerable: true,
  42026. configurable: true
  42027. });
  42028. /**
  42029. * Creates the render target textures and post processes used in the highlight layer.
  42030. */
  42031. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  42032. var _this = this;
  42033. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  42034. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  42035. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  42036. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  42037. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  42038. width: this._mainTextureDesiredSize.width,
  42039. height: this._mainTextureDesiredSize.height
  42040. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42041. this._mainTexture.activeCamera = this._options.camera;
  42042. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42043. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42044. this._mainTexture.anisotropicFilteringLevel = 1;
  42045. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42046. this._mainTexture.renderParticles = false;
  42047. this._mainTexture.renderList = null;
  42048. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  42049. width: blurTextureWidth,
  42050. height: blurTextureHeight
  42051. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42052. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42053. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42054. this._blurTexture.anisotropicFilteringLevel = 16;
  42055. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  42056. this._blurTexture.renderParticles = false;
  42057. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42058. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42059. effect.setTexture("textureSampler", _this._mainTexture);
  42060. });
  42061. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  42062. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42063. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42064. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42065. });
  42066. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42067. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42068. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42069. });
  42070. }
  42071. else {
  42072. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42073. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42074. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42075. });
  42076. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42077. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42078. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42079. });
  42080. }
  42081. this._mainTexture.onAfterUnbindObservable.add(function () {
  42082. _this.onBeforeBlurObservable.notifyObservers(_this);
  42083. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  42084. _this.onAfterBlurObservable.notifyObservers(_this);
  42085. });
  42086. // Custom render function
  42087. var renderSubMesh = function (subMesh) {
  42088. var mesh = subMesh.getRenderingMesh();
  42089. var scene = _this._scene;
  42090. var engine = scene.getEngine();
  42091. // Culling
  42092. engine.setState(subMesh.getMaterial().backFaceCulling);
  42093. // Managing instances
  42094. var batch = mesh._getInstancesRenderList(subMesh._id);
  42095. if (batch.mustReturn) {
  42096. return;
  42097. }
  42098. // Excluded Mesh
  42099. if (_this._excludedMeshes[mesh.uniqueId]) {
  42100. return;
  42101. }
  42102. ;
  42103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42104. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  42105. var material = subMesh.getMaterial();
  42106. var emissiveTexture = null;
  42107. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  42108. emissiveTexture = material.emissiveTexture;
  42109. }
  42110. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  42111. engine.enableEffect(_this._glowMapGenerationEffect);
  42112. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  42113. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  42114. if (highlightLayerMesh) {
  42115. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  42116. }
  42117. else {
  42118. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  42119. }
  42120. // Alpha test
  42121. if (material && material.needAlphaTesting()) {
  42122. var alphaTexture = material.getAlphaTestTexture();
  42123. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  42124. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42125. }
  42126. // Glow emissive only
  42127. if (emissiveTexture) {
  42128. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  42129. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  42130. }
  42131. // Bones
  42132. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42133. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42134. }
  42135. // Draw
  42136. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  42137. }
  42138. else {
  42139. // Need to reset refresh rate of the shadowMap
  42140. _this._mainTexture.resetRefreshCounter();
  42141. }
  42142. };
  42143. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42144. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  42145. var index;
  42146. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42147. renderSubMesh(opaqueSubMeshes.data[index]);
  42148. }
  42149. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42150. renderSubMesh(alphaTestSubMeshes.data[index]);
  42151. }
  42152. for (index = 0; index < transparentSubMeshes.length; index++) {
  42153. renderSubMesh(transparentSubMeshes.data[index]);
  42154. }
  42155. };
  42156. this._mainTexture.onClearObservable.add(function (engine) {
  42157. engine.clear(HighlightLayer.neutralColor, true, true, true);
  42158. });
  42159. };
  42160. /**
  42161. * Checks for the readiness of the element composing the layer.
  42162. * @param subMesh the mesh to check for
  42163. * @param useInstances specify wether or not to use instances to render the mesh
  42164. * @param emissiveTexture the associated emissive texture used to generate the glow
  42165. * @return true if ready otherwise, false
  42166. */
  42167. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  42168. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  42169. return false;
  42170. }
  42171. var defines = [];
  42172. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42173. var mesh = subMesh.getMesh();
  42174. var material = subMesh.getMaterial();
  42175. var uv1 = false;
  42176. var uv2 = false;
  42177. // Alpha test
  42178. if (material && material.needAlphaTesting()) {
  42179. var alphaTexture = material.getAlphaTestTexture();
  42180. if (alphaTexture) {
  42181. defines.push("#define ALPHATEST");
  42182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42183. alphaTexture.coordinatesIndex === 1) {
  42184. defines.push("#define DIFFUSEUV2");
  42185. uv2 = true;
  42186. }
  42187. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42188. defines.push("#define DIFFUSEUV1");
  42189. uv1 = true;
  42190. }
  42191. }
  42192. }
  42193. // Emissive
  42194. if (emissiveTexture) {
  42195. defines.push("#define EMISSIVE");
  42196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42197. emissiveTexture.coordinatesIndex === 1) {
  42198. defines.push("#define EMISSIVEUV2");
  42199. uv2 = true;
  42200. }
  42201. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42202. defines.push("#define EMISSIVEUV1");
  42203. uv1 = true;
  42204. }
  42205. }
  42206. if (uv1) {
  42207. attribs.push(BABYLON.VertexBuffer.UVKind);
  42208. defines.push("#define UV1");
  42209. }
  42210. if (uv2) {
  42211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42212. defines.push("#define UV2");
  42213. }
  42214. // Bones
  42215. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42218. if (mesh.numBoneInfluencers > 4) {
  42219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42221. }
  42222. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42223. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42224. }
  42225. else {
  42226. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42227. }
  42228. // Instances
  42229. if (useInstances) {
  42230. defines.push("#define INSTANCES");
  42231. attribs.push("world0");
  42232. attribs.push("world1");
  42233. attribs.push("world2");
  42234. attribs.push("world3");
  42235. }
  42236. // Get correct effect
  42237. var join = defines.join("\n");
  42238. if (this._cachedDefines !== join) {
  42239. this._cachedDefines = join;
  42240. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  42241. }
  42242. return this._glowMapGenerationEffect.isReady();
  42243. };
  42244. /**
  42245. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  42246. */
  42247. HighlightLayer.prototype.render = function () {
  42248. var currentEffect = this._glowMapMergeEffect;
  42249. // Check
  42250. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  42251. return;
  42252. var engine = this._scene.getEngine();
  42253. this.onBeforeComposeObservable.notifyObservers(this);
  42254. // Render
  42255. engine.enableEffect(currentEffect);
  42256. engine.setState(false);
  42257. // Cache
  42258. var previousStencilBuffer = engine.getStencilBuffer();
  42259. var previousStencilFunction = engine.getStencilFunction();
  42260. var previousStencilMask = engine.getStencilMask();
  42261. var previousAlphaMode = engine.getAlphaMode();
  42262. // Texture
  42263. currentEffect.setTexture("textureSampler", this._blurTexture);
  42264. // VBOs
  42265. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  42266. // Draw order
  42267. engine.setAlphaMode(this._options.alphaBlendingMode);
  42268. engine.setStencilMask(0x00);
  42269. engine.setStencilBuffer(true);
  42270. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  42271. if (this.outerGlow) {
  42272. currentEffect.setFloat("offset", 0);
  42273. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  42274. engine.draw(true, 0, 6);
  42275. }
  42276. if (this.innerGlow) {
  42277. currentEffect.setFloat("offset", 1);
  42278. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  42279. engine.draw(true, 0, 6);
  42280. }
  42281. // Restore Cache
  42282. engine.setStencilFunction(previousStencilFunction);
  42283. engine.setStencilMask(previousStencilMask);
  42284. engine.setAlphaMode(previousAlphaMode);
  42285. engine.setStencilBuffer(previousStencilBuffer);
  42286. this.onAfterComposeObservable.notifyObservers(this);
  42287. // Handle size changes.
  42288. var size = this._mainTexture.getSize();
  42289. this.setMainTextureSize();
  42290. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  42291. // Recreate RTT and post processes on size change.
  42292. this.onSizeChangedObservable.notifyObservers(this);
  42293. this.disposeTextureAndPostProcesses();
  42294. this.createTextureAndPostProcesses();
  42295. }
  42296. };
  42297. /**
  42298. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  42299. * @param mesh The mesh to exclude from the highlight layer
  42300. */
  42301. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  42302. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42303. if (!meshExcluded) {
  42304. this._excludedMeshes[mesh.uniqueId] = {
  42305. mesh: mesh,
  42306. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  42307. mesh.getEngine().setStencilBuffer(false);
  42308. }),
  42309. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  42310. mesh.getEngine().setStencilBuffer(true);
  42311. }),
  42312. };
  42313. }
  42314. };
  42315. /**
  42316. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  42317. * @param mesh The mesh to highlight
  42318. */
  42319. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  42320. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42321. if (meshExcluded) {
  42322. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  42323. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  42324. }
  42325. this._excludedMeshes[mesh.uniqueId] = undefined;
  42326. };
  42327. /**
  42328. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  42329. * @param mesh The mesh to highlight
  42330. * @param color The color of the highlight
  42331. * @param glowEmissiveOnly Extract the glow from the emissive texture
  42332. */
  42333. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  42334. var _this = this;
  42335. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  42336. var meshHighlight = this._meshes[mesh.uniqueId];
  42337. if (meshHighlight) {
  42338. meshHighlight.color = color;
  42339. }
  42340. else {
  42341. this._meshes[mesh.uniqueId] = {
  42342. mesh: mesh,
  42343. color: color,
  42344. // Lambda required for capture due to Observable this context
  42345. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  42346. if (_this._excludedMeshes[mesh.uniqueId]) {
  42347. _this.defaultStencilReference(mesh);
  42348. }
  42349. else {
  42350. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  42351. }
  42352. }),
  42353. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  42354. glowEmissiveOnly: glowEmissiveOnly
  42355. };
  42356. }
  42357. this._shouldRender = true;
  42358. };
  42359. /**
  42360. * Remove a mesh from the highlight layer in order to make it stop glowing.
  42361. * @param mesh The mesh to highlight
  42362. */
  42363. HighlightLayer.prototype.removeMesh = function (mesh) {
  42364. var meshHighlight = this._meshes[mesh.uniqueId];
  42365. if (meshHighlight) {
  42366. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42367. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42368. }
  42369. this._meshes[mesh.uniqueId] = undefined;
  42370. this._shouldRender = false;
  42371. for (var meshHighlightToCheck in this._meshes) {
  42372. if (meshHighlightToCheck) {
  42373. this._shouldRender = true;
  42374. break;
  42375. }
  42376. }
  42377. };
  42378. /**
  42379. * Returns true if the layer contains information to display, otherwise false.
  42380. */
  42381. HighlightLayer.prototype.shouldRender = function () {
  42382. return this.isEnabled && this._shouldRender;
  42383. };
  42384. /**
  42385. * Sets the main texture desired size which is the closest power of two
  42386. * of the engine canvas size.
  42387. */
  42388. HighlightLayer.prototype.setMainTextureSize = function () {
  42389. if (this._options.mainTextureFixedSize) {
  42390. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  42391. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  42392. }
  42393. else {
  42394. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  42395. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  42396. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  42397. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  42398. }
  42399. };
  42400. /**
  42401. * Force the stencil to the normal expected value for none glowing parts
  42402. */
  42403. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  42404. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  42405. };
  42406. /**
  42407. * Dispose only the render target textures and post process.
  42408. */
  42409. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  42410. this._blurTexture.dispose();
  42411. this._mainTexture.dispose();
  42412. this._downSamplePostprocess.dispose();
  42413. this._horizontalBlurPostprocess.dispose();
  42414. this._verticalBlurPostprocess.dispose();
  42415. };
  42416. /**
  42417. * Dispose the highlight layer and free resources.
  42418. */
  42419. HighlightLayer.prototype.dispose = function () {
  42420. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  42421. if (vertexBuffer) {
  42422. vertexBuffer.dispose();
  42423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  42424. }
  42425. if (this._indexBuffer) {
  42426. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42427. this._indexBuffer = null;
  42428. }
  42429. // Clean textures and post processes
  42430. this.disposeTextureAndPostProcesses();
  42431. // Clean mesh references
  42432. for (var id in this._meshes) {
  42433. var meshHighlight = this._meshes[id];
  42434. if (meshHighlight && meshHighlight.mesh) {
  42435. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42436. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42437. }
  42438. }
  42439. this._meshes = null;
  42440. for (var id in this._excludedMeshes) {
  42441. var meshHighlight = this._excludedMeshes[id];
  42442. if (meshHighlight) {
  42443. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  42444. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  42445. }
  42446. }
  42447. this._excludedMeshes = null;
  42448. // Remove from scene
  42449. var index = this._scene.highlightLayers.indexOf(this, 0);
  42450. if (index > -1) {
  42451. this._scene.highlightLayers.splice(index, 1);
  42452. }
  42453. // Callback
  42454. this.onDisposeObservable.notifyObservers(this);
  42455. this.onDisposeObservable.clear();
  42456. this.onBeforeRenderMainTextureObservable.clear();
  42457. this.onBeforeBlurObservable.clear();
  42458. this.onBeforeComposeObservable.clear();
  42459. this.onAfterComposeObservable.clear();
  42460. this.onSizeChangedObservable.clear();
  42461. };
  42462. return HighlightLayer;
  42463. }());
  42464. /**
  42465. * The neutral color used during the preparation of the glow effect.
  42466. * This is black by default as the blend operation is a blend operation.
  42467. */
  42468. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  42469. /**
  42470. * Stencil value used for glowing meshes.
  42471. */
  42472. HighlightLayer.glowingMeshStencilReference = 0x02;
  42473. /**
  42474. * Stencil value used for the other meshes in the scene.
  42475. */
  42476. HighlightLayer.normalMeshStencilReference = 0x01;
  42477. BABYLON.HighlightLayer = HighlightLayer;
  42478. })(BABYLON || (BABYLON = {}));
  42479. //# sourceMappingURL=babylon.highlightlayer.js.map
  42480. var BABYLON;
  42481. (function (BABYLON) {
  42482. var SIMDVector3 = (function () {
  42483. function SIMDVector3() {
  42484. }
  42485. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  42486. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  42487. };
  42488. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  42489. var m = transformation.m;
  42490. var m0 = SIMD.Float32x4.load(m, 0);
  42491. var m1 = SIMD.Float32x4.load(m, 4);
  42492. var m2 = SIMD.Float32x4.load(m, 8);
  42493. var m3 = SIMD.Float32x4.load(m, 12);
  42494. 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));
  42495. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  42496. result.x = SIMD.Float32x4.extractLane(r, 0);
  42497. result.y = SIMD.Float32x4.extractLane(r, 1);
  42498. result.z = SIMD.Float32x4.extractLane(r, 2);
  42499. };
  42500. return SIMDVector3;
  42501. }());
  42502. var SIMDMatrix = (function () {
  42503. function SIMDMatrix() {
  42504. }
  42505. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  42506. var tm = this.m;
  42507. var om = other.m;
  42508. var m0 = SIMD.Float32x4.load(om, 0);
  42509. var m1 = SIMD.Float32x4.load(om, 4);
  42510. var m2 = SIMD.Float32x4.load(om, 8);
  42511. var m3 = SIMD.Float32x4.load(om, 12);
  42512. for (var i = 0; i < 16; i += 4) {
  42513. 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)))));
  42514. }
  42515. return this;
  42516. };
  42517. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  42518. var src = this.m;
  42519. var dest = other.m;
  42520. // Load the 4 rows
  42521. var src0 = SIMD.Float32x4.load(src, 0);
  42522. var src1 = SIMD.Float32x4.load(src, 4);
  42523. var src2 = SIMD.Float32x4.load(src, 8);
  42524. var src3 = SIMD.Float32x4.load(src, 12);
  42525. // Transpose the source matrix. Sort of. Not a true transpose operation
  42526. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  42527. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  42528. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  42529. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  42530. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  42531. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  42532. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  42533. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  42534. // This is a true transposition, but it will lead to an incorrect result
  42535. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  42536. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  42537. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42538. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42539. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  42540. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  42541. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42542. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42543. // ----
  42544. tmp1 = SIMD.Float32x4.mul(row2, row3);
  42545. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42546. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  42547. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  42548. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42549. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  42550. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  42551. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  42552. // ----
  42553. tmp1 = SIMD.Float32x4.mul(row1, row2);
  42554. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42555. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  42556. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  42557. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42558. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  42559. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  42560. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  42561. // ----
  42562. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  42563. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42564. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  42565. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  42566. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  42567. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42568. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  42569. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  42570. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  42571. // ----
  42572. tmp1 = SIMD.Float32x4.mul(row0, row1);
  42573. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42574. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42575. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  42576. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42577. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42578. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  42579. // ----
  42580. tmp1 = SIMD.Float32x4.mul(row0, row3);
  42581. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42582. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  42583. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  42584. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42585. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  42586. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  42587. // ----
  42588. tmp1 = SIMD.Float32x4.mul(row0, row2);
  42589. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42590. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  42591. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  42592. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42593. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  42594. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  42595. // Compute determinant
  42596. var det = SIMD.Float32x4.mul(row0, minor0);
  42597. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  42598. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  42599. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  42600. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  42601. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  42602. // These shuffles aren't necessary if the faulty transposition is done
  42603. // up at the top of this function.
  42604. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  42605. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  42606. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  42607. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  42608. // Compute final values by multiplying with 1/det
  42609. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  42610. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  42611. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  42612. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  42613. return this;
  42614. };
  42615. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  42616. var out = result.m;
  42617. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  42618. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  42619. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  42620. // cc.kmVec3Subtract(f, pCenter, pEye);
  42621. var f = SIMD.Float32x4.sub(center, eye);
  42622. // cc.kmVec3Normalize(f, f);
  42623. var tmp = SIMD.Float32x4.mul(f, f);
  42624. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42625. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42626. // cc.kmVec3Assign(up, pUp);
  42627. // cc.kmVec3Normalize(up, up);
  42628. tmp = SIMD.Float32x4.mul(up, up);
  42629. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42630. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42631. // cc.kmVec3Cross(s, f, up);
  42632. 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)));
  42633. // cc.kmVec3Normalize(s, s);
  42634. tmp = SIMD.Float32x4.mul(s, s);
  42635. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42636. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42637. // cc.kmVec3Cross(u, s, f);
  42638. 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)));
  42639. // cc.kmVec3Normalize(s, s);
  42640. tmp = SIMD.Float32x4.mul(s, s);
  42641. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42642. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42643. var zero = SIMD.Float32x4.splat(0.0);
  42644. s = SIMD.Float32x4.neg(s);
  42645. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  42646. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  42647. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  42648. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  42649. 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);
  42650. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  42651. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  42652. 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)))));
  42653. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  42654. 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)))));
  42655. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  42656. 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)))));
  42657. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  42658. 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)))));
  42659. };
  42660. return SIMDMatrix;
  42661. }());
  42662. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  42663. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  42664. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  42665. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  42666. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  42667. var SIMDHelper = (function () {
  42668. function SIMDHelper() {
  42669. }
  42670. Object.defineProperty(SIMDHelper, "IsEnabled", {
  42671. get: function () {
  42672. return SIMDHelper._isEnabled;
  42673. },
  42674. enumerable: true,
  42675. configurable: true
  42676. });
  42677. SIMDHelper.DisableSIMD = function () {
  42678. // Replace functions
  42679. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  42680. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  42681. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  42682. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  42683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  42684. SIMDHelper._isEnabled = false;
  42685. };
  42686. SIMDHelper.EnableSIMD = function () {
  42687. if (self.SIMD === undefined) {
  42688. return;
  42689. }
  42690. // check if polyfills needed
  42691. if (!self.Math.fround) {
  42692. self.Math.fround = (function (array) { return function (x) {
  42693. return array[0] = x, array[0];
  42694. }; })(new Float32Array(1));
  42695. }
  42696. if (!self.Math.imul) {
  42697. self.Math.imul = function (a, b) {
  42698. var ah = (a >>> 16) & 0xffff;
  42699. var al = a & 0xffff;
  42700. var bh = (b >>> 16) & 0xffff;
  42701. var bl = b & 0xffff;
  42702. // the shift by 0 fixes the sign on the high part
  42703. // the final |0 converts the unsigned value into a signed value
  42704. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  42705. };
  42706. }
  42707. // Replace functions
  42708. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  42709. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  42710. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  42711. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  42712. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  42713. SIMDHelper._isEnabled = true;
  42714. };
  42715. return SIMDHelper;
  42716. }());
  42717. SIMDHelper._isEnabled = false;
  42718. BABYLON.SIMDHelper = SIMDHelper;
  42719. })(BABYLON || (BABYLON = {}));
  42720. //# sourceMappingURL=babylon.math.SIMD.js.map
  42721. var BABYLON;
  42722. (function (BABYLON) {
  42723. /**
  42724. * This class describe a rectangle that were added to the map.
  42725. * You have access to its coordinates either in pixel or normalized (UV)
  42726. */
  42727. var PackedRect = (function () {
  42728. function PackedRect(root, parent, pos, size) {
  42729. this._pos = pos;
  42730. this._size = size;
  42731. this._root = root;
  42732. this._parent = parent;
  42733. this._contentSize = null;
  42734. this._bottomNode = null;
  42735. this._leftNode = null;
  42736. this._initialSize = null;
  42737. this._rightNode = null;
  42738. }
  42739. Object.defineProperty(PackedRect.prototype, "pos", {
  42740. /**
  42741. * @returns the position of this node into the map
  42742. */
  42743. get: function () {
  42744. return this._pos;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. Object.defineProperty(PackedRect.prototype, "contentSize", {
  42750. /**
  42751. * @returns the size of the rectangle this node handles
  42752. */
  42753. get: function () {
  42754. return this._contentSize;
  42755. },
  42756. enumerable: true,
  42757. configurable: true
  42758. });
  42759. Object.defineProperty(PackedRect.prototype, "UVs", {
  42760. /**
  42761. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  42762. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  42763. */
  42764. get: function () {
  42765. return this.getUVsForCustomSize(this._root._size);
  42766. },
  42767. enumerable: true,
  42768. configurable: true
  42769. });
  42770. /**
  42771. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  42772. * This method will return the UVs for this part by given the custom size of what you really use
  42773. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  42774. */
  42775. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  42776. var mainWidth = this._root._size.width;
  42777. var mainHeight = this._root._size.height;
  42778. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  42779. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  42780. var uvs = new Array();
  42781. uvs.push(topLeft);
  42782. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  42783. uvs.push(rightBottom);
  42784. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  42785. return uvs;
  42786. };
  42787. /**
  42788. * Free this rectangle from the map.
  42789. * Call this method when you no longer need the rectangle to be in the map.
  42790. */
  42791. PackedRect.prototype.freeContent = function () {
  42792. if (!this.contentSize) {
  42793. return;
  42794. }
  42795. this._contentSize = null;
  42796. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  42797. this.attemptDefrag();
  42798. };
  42799. Object.defineProperty(PackedRect.prototype, "isUsed", {
  42800. get: function () {
  42801. return this._contentSize != null || this._leftNode != null;
  42802. },
  42803. enumerable: true,
  42804. configurable: true
  42805. });
  42806. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  42807. var node = this.findNode(contentSize);
  42808. // Not enough space...
  42809. if (!node) {
  42810. return null;
  42811. }
  42812. node.splitNode(contentSize);
  42813. return node;
  42814. };
  42815. PackedRect.prototype.findNode = function (size) {
  42816. var resNode = null;
  42817. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  42818. if (this.isUsed) {
  42819. if (this._leftNode) {
  42820. resNode = this._leftNode.findNode(size);
  42821. }
  42822. if (!resNode && this._rightNode) {
  42823. resNode = this._rightNode.findNode(size);
  42824. }
  42825. if (!resNode && this._bottomNode) {
  42826. resNode = this._bottomNode.findNode(size);
  42827. }
  42828. }
  42829. else if (this._initialSize) {
  42830. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  42831. resNode = this;
  42832. }
  42833. else {
  42834. return null;
  42835. }
  42836. }
  42837. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  42838. resNode = this;
  42839. }
  42840. return resNode;
  42841. };
  42842. PackedRect.prototype.splitNode = function (contentSize) {
  42843. // 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)
  42844. if (!this._contentSize && this._initialSize) {
  42845. this._contentSize = contentSize.clone();
  42846. 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));
  42847. return this._leftNode.splitNode(contentSize);
  42848. }
  42849. else {
  42850. this._contentSize = contentSize.clone();
  42851. this._initialSize = contentSize.clone();
  42852. if (contentSize.width !== this._size.width) {
  42853. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  42854. }
  42855. if (contentSize.height !== this._size.height) {
  42856. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  42857. }
  42858. return this;
  42859. }
  42860. };
  42861. PackedRect.prototype.attemptDefrag = function () {
  42862. if (!this.isUsed && this.isRecursiveFree) {
  42863. this.clearNode();
  42864. if (this._parent) {
  42865. this._parent.attemptDefrag();
  42866. }
  42867. }
  42868. };
  42869. PackedRect.prototype.clearNode = function () {
  42870. this._initialSize = null;
  42871. this._rightNode = null;
  42872. this._bottomNode = null;
  42873. };
  42874. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  42875. get: function () {
  42876. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  42877. },
  42878. enumerable: true,
  42879. configurable: true
  42880. });
  42881. PackedRect.prototype.evalFreeSize = function (size) {
  42882. var levelSize = 0;
  42883. if (!this.isUsed) {
  42884. if (this._initialSize) {
  42885. levelSize = this._initialSize.surface;
  42886. }
  42887. else {
  42888. levelSize = this._size.surface;
  42889. }
  42890. }
  42891. if (this._rightNode) {
  42892. levelSize += this._rightNode.evalFreeSize(0);
  42893. }
  42894. if (this._bottomNode) {
  42895. levelSize += this._bottomNode.evalFreeSize(0);
  42896. }
  42897. return levelSize + size;
  42898. };
  42899. return PackedRect;
  42900. }());
  42901. BABYLON.PackedRect = PackedRect;
  42902. /**
  42903. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  42904. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  42905. * 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.
  42906. */
  42907. var RectPackingMap = (function (_super) {
  42908. __extends(RectPackingMap, _super);
  42909. /**
  42910. * Create an instance of the object with a dimension using the given size
  42911. * @param size The dimension of the rectangle that will contain all the sub ones.
  42912. */
  42913. function RectPackingMap(size) {
  42914. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  42915. _this._root = _this;
  42916. return _this;
  42917. }
  42918. /**
  42919. * Add a rectangle, finding the best location to store it into the map
  42920. * @param size the dimension of the rectangle to store
  42921. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  42922. */
  42923. RectPackingMap.prototype.addRect = function (size) {
  42924. var node = this.findAndSplitNode(size);
  42925. return node;
  42926. };
  42927. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  42928. /**
  42929. * Return the current space free normalized between [0;1]
  42930. * @returns {}
  42931. */
  42932. get: function () {
  42933. var freeSize = 0;
  42934. freeSize = this.evalFreeSize(freeSize);
  42935. return freeSize / (this._size.width * this._size.height);
  42936. },
  42937. enumerable: true,
  42938. configurable: true
  42939. });
  42940. return RectPackingMap;
  42941. }(PackedRect));
  42942. BABYLON.RectPackingMap = RectPackingMap;
  42943. })(BABYLON || (BABYLON = {}));
  42944. //# sourceMappingURL=babylon.rectPackingMap.js.map
  42945. var BABYLON;
  42946. (function (BABYLON) {
  42947. var DynamicFloatArrayElementInfo = (function () {
  42948. function DynamicFloatArrayElementInfo() {
  42949. }
  42950. return DynamicFloatArrayElementInfo;
  42951. }());
  42952. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  42953. /**
  42954. * 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.
  42955. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  42956. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  42957. * 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.
  42958. * 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.
  42959. * 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".
  42960. */
  42961. var DynamicFloatArray = (function () {
  42962. /**
  42963. * Construct an instance of the dynamic float array
  42964. * @param stride size of one element in float (i.e. not bytes!)
  42965. * @param initialElementCount the number of available entries at construction
  42966. */
  42967. function DynamicFloatArray(stride, initialElementCount) {
  42968. this.compareValueOffset = null;
  42969. this.sortingAscending = true;
  42970. this._stride = stride;
  42971. this.buffer = new Float32Array(stride * initialElementCount);
  42972. this._lastUsed = 0;
  42973. this._firstFree = 0;
  42974. this._allEntries = new Array(initialElementCount);
  42975. this._freeEntries = new Array(initialElementCount);
  42976. for (var i = 0; i < initialElementCount; i++) {
  42977. var element = new DynamicFloatArrayElementInfo();
  42978. element.offset = i * stride;
  42979. this._allEntries[i] = element;
  42980. this._freeEntries[initialElementCount - i - 1] = element;
  42981. }
  42982. }
  42983. /**
  42984. * Allocate an element in the array.
  42985. * @return the element info instance that contains the offset into the main buffer of the element's location.
  42986. * Beware, this offset may change when you call pack()
  42987. */
  42988. DynamicFloatArray.prototype.allocElement = function () {
  42989. if (this._freeEntries.length === 0) {
  42990. this._growBuffer();
  42991. }
  42992. var el = this._freeEntries.pop();
  42993. this._lastUsed = Math.max(el.offset, this._lastUsed);
  42994. if (el.offset === this._firstFree) {
  42995. if (this._freeEntries.length > 0) {
  42996. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  42997. }
  42998. else {
  42999. this._firstFree += this._stride;
  43000. }
  43001. }
  43002. return el;
  43003. };
  43004. /**
  43005. * Free the element corresponding to the given element info
  43006. * @param elInfo the element that describe the allocated element
  43007. */
  43008. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43009. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43010. this._freeEntries.push(elInfo);
  43011. };
  43012. /**
  43013. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43014. * 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().
  43015. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43016. */
  43017. DynamicFloatArray.prototype.pack = function () {
  43018. // no free slot? no need to pack
  43019. if (this._freeEntries.length === 0) {
  43020. return this.buffer;
  43021. }
  43022. // If the buffer is already packed the last used will always be lower than the first free
  43023. // 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.
  43024. if (this._lastUsed < this._firstFree) {
  43025. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43026. return elementsBuffer_1;
  43027. }
  43028. var s = this._stride;
  43029. // 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
  43030. var lastFree = new DynamicFloatArrayElementInfo();
  43031. lastFree.offset = this.totalElementCount * s;
  43032. this._freeEntries.push(lastFree);
  43033. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43034. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43035. var firstFreeSlotOffset = sortedFree[0].offset;
  43036. var freeZoneSize = 1;
  43037. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43038. var prevOffset = sortedFree[0].offset;
  43039. for (var i = 1; i < sortedFree.length; i++) {
  43040. // 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
  43041. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43042. break;
  43043. }
  43044. var curFree = sortedFree[i];
  43045. var curOffset = curFree.offset;
  43046. // Compute the distance between this offset and the previous
  43047. var distance = curOffset - prevOffset;
  43048. // If the distance is the stride size, they are adjacent, it good, move to the next
  43049. if (distance === s) {
  43050. // Free zone is one element bigger
  43051. ++freeZoneSize;
  43052. // as we're about to iterate to the next, the cur becomes the previous...
  43053. prevOffset = curOffset;
  43054. continue;
  43055. }
  43056. // Distance is bigger, which means there's x element between the previous free and this one
  43057. var usedRange = (distance / s) - 1;
  43058. // Two cases the free zone is smaller than the data to move or bigger
  43059. // Copy what can fit in the free zone
  43060. var curMoveOffset = curOffset - s;
  43061. var copyCount = Math.min(freeZoneSize, usedRange);
  43062. for (var j = 0; j < copyCount; j++) {
  43063. var freeI = firstFreeSlotOffset / s;
  43064. var curI = curMoveOffset / s;
  43065. var moveEl = sortedAll[curI];
  43066. this._moveElement(moveEl, firstFreeSlotOffset);
  43067. var replacedEl = sortedAll[freeI];
  43068. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43069. replacedEl.offset = curMoveOffset;
  43070. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43071. sortedAll[freeI] = moveEl;
  43072. sortedAll[curI] = replacedEl;
  43073. curMoveOffset -= s;
  43074. firstFreeSlotOffset += s;
  43075. }
  43076. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43077. if (freeZoneSize <= usedRange) {
  43078. firstFreeSlotOffset = curMoveOffset + s;
  43079. freeZoneSize = 1 + copyCount;
  43080. }
  43081. else {
  43082. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43083. }
  43084. // as we're about to iterate to the next, the cur becomes the previous...
  43085. prevOffset = curOffset;
  43086. }
  43087. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43088. this._lastUsed = firstFreeSlotOffset - s;
  43089. this._firstFree = firstFreeSlotOffset;
  43090. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43091. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43092. this._allEntries = sortedAll;
  43093. return elementsBuffer;
  43094. };
  43095. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43096. for (var i = 0; i < this._stride; i++) {
  43097. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43098. }
  43099. element.offset = destOffset;
  43100. };
  43101. DynamicFloatArray.prototype._growBuffer = function () {
  43102. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43103. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43104. var newBuffer = new Float32Array(newElCount * this._stride);
  43105. newBuffer.set(this.buffer);
  43106. var curCount = this.totalElementCount;
  43107. var addedCount = newElCount - this.totalElementCount;
  43108. for (var i = 0; i < addedCount; i++) {
  43109. var element = new DynamicFloatArrayElementInfo();
  43110. element.offset = (curCount + i) * this.stride;
  43111. this._allEntries.push(element);
  43112. this._freeEntries[addedCount - i - 1] = element;
  43113. }
  43114. this._firstFree = curCount * this.stride;
  43115. this.buffer = newBuffer;
  43116. };
  43117. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43118. /**
  43119. * Get the total count of entries that can fit in the current buffer
  43120. * @returns the elements count
  43121. */
  43122. get: function () {
  43123. return this._allEntries.length;
  43124. },
  43125. enumerable: true,
  43126. configurable: true
  43127. });
  43128. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43129. /**
  43130. * Get the count of free entries that can still be allocated without resizing the buffer
  43131. * @returns the free elements count
  43132. */
  43133. get: function () {
  43134. return this._freeEntries.length;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43140. /**
  43141. * Get the count of allocated elements
  43142. * @returns the allocated elements count
  43143. */
  43144. get: function () {
  43145. return this._allEntries.length - this._freeEntries.length;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43151. /**
  43152. * Return the size of one element in float
  43153. * @returns the size in float
  43154. */
  43155. get: function () {
  43156. return this._stride;
  43157. },
  43158. enumerable: true,
  43159. configurable: true
  43160. });
  43161. DynamicFloatArray.prototype.sort = function () {
  43162. var _this = this;
  43163. if (!this.compareValueOffset) {
  43164. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43165. }
  43166. var count = this.usedElementCount;
  43167. // Do we have to (re)create the sort table?
  43168. if (!this._sortTable || this._sortTable.length < count) {
  43169. // 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...
  43170. var newCount = Math.min(this.totalElementCount, count * 2);
  43171. this._sortTable = new Array(newCount);
  43172. }
  43173. if (!this._sortedTable || this._sortedTable.length !== count) {
  43174. this._sortedTable = new Array(count);
  43175. }
  43176. // Because, you know...
  43177. this.pack();
  43178. //let stride = this.stride;
  43179. //for (let i = 0; i < count; i++) {
  43180. // let si = this._sortTable[i];
  43181. // if (!si) {
  43182. // si = new SortInfo();
  43183. // this._sortTable[i] = si;
  43184. // }
  43185. // si.entry = this._allEntries[i];
  43186. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43187. // si.swapedOffset = null;
  43188. // this._sortedTable[i] = si;
  43189. //}
  43190. var curOffset = 0;
  43191. var stride = this.stride;
  43192. for (var i = 0; i < count; i++, curOffset += stride) {
  43193. var si = this._sortTable[i];
  43194. if (!si) {
  43195. si = new SortInfo();
  43196. this._sortTable[i] = si;
  43197. }
  43198. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43199. si.offset = curOffset;
  43200. si.swapedOffset = null;
  43201. this._sortedTable[i] = si;
  43202. }
  43203. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43204. if (this.sortingAscending) {
  43205. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43206. }
  43207. else {
  43208. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43209. }
  43210. var swapElements = function (src, dst) {
  43211. for (var i = 0; i < stride; i++) {
  43212. var tps = _this.buffer[dst + i];
  43213. _this.buffer[dst + i] = _this.buffer[src + i];
  43214. _this.buffer[src + i] = tps;
  43215. }
  43216. };
  43217. // 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:
  43218. // 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),
  43219. // and I still want something with a good algorithm complexity.
  43220. // 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,
  43221. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43222. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43223. // 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
  43224. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43225. // 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
  43226. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43227. for (var i = 0; i < count; i++) {
  43228. // Get the element to move
  43229. var sourceSI = this._sortedTable[i];
  43230. var destSI = this._sortTable[i];
  43231. var sourceOff = sourceSI.offset;
  43232. // If the source changed location, find the new one
  43233. if (sourceSI.swapedOffset) {
  43234. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43235. var curSI = sourceSI;
  43236. while (curSI.swapedOffset) {
  43237. curSI = this._sortTable[curSI.swapedOffset / stride];
  43238. }
  43239. // Finally get the right location
  43240. sourceOff = curSI.offset;
  43241. }
  43242. // Tag the element being replaced with its new location
  43243. destSI.swapedOffset = sourceOff;
  43244. // Swap elements (only if needed)
  43245. if (sourceOff !== destSI.offset) {
  43246. swapElements(sourceOff, destSI.offset);
  43247. }
  43248. // Update the offset in the corresponding DFAE
  43249. //sourceSI.entry.offset = destSI.entry.offset;
  43250. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43251. }
  43252. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43253. return true;
  43254. };
  43255. return DynamicFloatArray;
  43256. }());
  43257. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43258. var SortInfo = (function () {
  43259. function SortInfo() {
  43260. this.compareData = this.offset = this.swapedOffset = null;
  43261. }
  43262. return SortInfo;
  43263. }());
  43264. })(BABYLON || (BABYLON = {}));
  43265. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43266. var BABYLON;
  43267. (function (BABYLON) {
  43268. var MapTexture = (function (_super) {
  43269. __extends(MapTexture, _super);
  43270. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  43271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43272. if (useMipMap === void 0) { useMipMap = false; }
  43273. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  43274. _this.name = name;
  43275. _this._size = size;
  43276. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43277. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43278. // Create the rectPackMap that will allocate portion of the texture
  43279. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  43280. // Create the texture that will store the content
  43281. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  43282. return _this;
  43283. }
  43284. /**
  43285. * Allocate a rectangle of a given size in the texture map
  43286. * @param size the size of the rectangle to allocation
  43287. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  43288. */
  43289. MapTexture.prototype.allocateRect = function (size) {
  43290. return this._rectPackingMap.addRect(size);
  43291. };
  43292. /**
  43293. * Free a given rectangle from the texture map
  43294. * @param rectInfo the instance corresponding to the rect to free.
  43295. */
  43296. MapTexture.prototype.freeRect = function (rectInfo) {
  43297. if (rectInfo) {
  43298. rectInfo.freeContent();
  43299. }
  43300. };
  43301. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  43302. /**
  43303. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  43304. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  43305. * @returns {}
  43306. */
  43307. get: function () {
  43308. return this._rectPackingMap.freeSpace;
  43309. },
  43310. enumerable: true,
  43311. configurable: true
  43312. });
  43313. /**
  43314. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  43315. * 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.
  43316. * Don't forget to call unbindTexture when you're done rendering
  43317. * @param rect the zone to render to
  43318. * @param clear true to clear the portion's color/depth data
  43319. */
  43320. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  43321. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  43322. };
  43323. /**
  43324. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  43325. * 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.
  43326. * Don't forget to call unbindTexture when you're done rendering
  43327. * @param pos the position into the texture
  43328. * @param size the portion to fit the clip space to
  43329. * @param clear true to clear the portion's color/depth data
  43330. */
  43331. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  43332. var engine = this.getScene().getEngine();
  43333. engine.bindFramebuffer(this._texture);
  43334. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  43335. if (clear) {
  43336. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  43337. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  43338. }
  43339. };
  43340. /**
  43341. * Unbind the texture map from the rendering engine.
  43342. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  43343. * @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.
  43344. */
  43345. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  43346. // Dump ?
  43347. if (dumpForDebug) {
  43348. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  43349. }
  43350. var engine = this.getScene().getEngine();
  43351. if (this._replacedViewport) {
  43352. engine.setViewport(this._replacedViewport);
  43353. this._replacedViewport = null;
  43354. }
  43355. engine.unBindFramebuffer(this._texture);
  43356. };
  43357. Object.defineProperty(MapTexture.prototype, "canRescale", {
  43358. get: function () {
  43359. return false;
  43360. },
  43361. enumerable: true,
  43362. configurable: true
  43363. });
  43364. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  43365. // Anyway, there's not much point to use this method for this kind of texture I guess
  43366. MapTexture.prototype.clone = function () {
  43367. return null;
  43368. };
  43369. return MapTexture;
  43370. }(BABYLON.Texture));
  43371. BABYLON.MapTexture = MapTexture;
  43372. })(BABYLON || (BABYLON = {}));
  43373. //# sourceMappingURL=babylon.mapTexture.js.map
  43374. var BABYLON;
  43375. (function (BABYLON) {
  43376. var ShaderMaterial = (function (_super) {
  43377. __extends(ShaderMaterial, _super);
  43378. function ShaderMaterial(name, scene, shaderPath, options) {
  43379. var _this = _super.call(this, name, scene) || this;
  43380. _this._textures = {};
  43381. _this._textureArrays = {};
  43382. _this._floats = {};
  43383. _this._floatsArrays = {};
  43384. _this._colors3 = {};
  43385. _this._colors4 = {};
  43386. _this._vectors2 = {};
  43387. _this._vectors3 = {};
  43388. _this._vectors4 = {};
  43389. _this._matrices = {};
  43390. _this._matrices3x3 = {};
  43391. _this._matrices2x2 = {};
  43392. _this._vectors3Arrays = {};
  43393. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43394. _this._shaderPath = shaderPath;
  43395. options.needAlphaBlending = options.needAlphaBlending || false;
  43396. options.needAlphaTesting = options.needAlphaTesting || false;
  43397. options.attributes = options.attributes || ["position", "normal", "uv"];
  43398. options.uniforms = options.uniforms || ["worldViewProjection"];
  43399. options.samplers = options.samplers || [];
  43400. options.defines = options.defines || [];
  43401. _this._options = options;
  43402. return _this;
  43403. }
  43404. ShaderMaterial.prototype.getClassName = function () {
  43405. return "ShaderMaterial";
  43406. };
  43407. ShaderMaterial.prototype.needAlphaBlending = function () {
  43408. return this._options.needAlphaBlending;
  43409. };
  43410. ShaderMaterial.prototype.needAlphaTesting = function () {
  43411. return this._options.needAlphaTesting;
  43412. };
  43413. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43414. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43415. this._options.uniforms.push(uniformName);
  43416. }
  43417. };
  43418. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43419. if (this._options.samplers.indexOf(name) === -1) {
  43420. this._options.samplers.push(name);
  43421. }
  43422. this._textures[name] = texture;
  43423. return this;
  43424. };
  43425. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43426. if (this._options.samplers.indexOf(name) === -1) {
  43427. this._options.samplers.push(name);
  43428. }
  43429. this._checkUniform(name);
  43430. this._textureArrays[name] = textures;
  43431. return this;
  43432. };
  43433. ShaderMaterial.prototype.setFloat = function (name, value) {
  43434. this._checkUniform(name);
  43435. this._floats[name] = value;
  43436. return this;
  43437. };
  43438. ShaderMaterial.prototype.setFloats = function (name, value) {
  43439. this._checkUniform(name);
  43440. this._floatsArrays[name] = value;
  43441. return this;
  43442. };
  43443. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43444. this._checkUniform(name);
  43445. this._colors3[name] = value;
  43446. return this;
  43447. };
  43448. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43449. this._checkUniform(name);
  43450. this._colors4[name] = value;
  43451. return this;
  43452. };
  43453. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43454. this._checkUniform(name);
  43455. this._vectors2[name] = value;
  43456. return this;
  43457. };
  43458. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43459. this._checkUniform(name);
  43460. this._vectors3[name] = value;
  43461. return this;
  43462. };
  43463. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43464. this._checkUniform(name);
  43465. this._vectors4[name] = value;
  43466. return this;
  43467. };
  43468. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43469. this._checkUniform(name);
  43470. this._matrices[name] = value;
  43471. return this;
  43472. };
  43473. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43474. this._checkUniform(name);
  43475. this._matrices3x3[name] = value;
  43476. return this;
  43477. };
  43478. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43479. this._checkUniform(name);
  43480. this._matrices2x2[name] = value;
  43481. return this;
  43482. };
  43483. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43484. this._checkUniform(name);
  43485. this._vectors3Arrays[name] = value;
  43486. return this;
  43487. };
  43488. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43489. if (!mesh) {
  43490. return true;
  43491. }
  43492. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43493. return false;
  43494. }
  43495. return false;
  43496. };
  43497. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43498. var scene = this.getScene();
  43499. var engine = scene.getEngine();
  43500. if (!this.checkReadyOnEveryCall) {
  43501. if (this._renderId === scene.getRenderId()) {
  43502. if (this._checkCache(scene, mesh, useInstances)) {
  43503. return true;
  43504. }
  43505. }
  43506. }
  43507. // Instances
  43508. var defines = [];
  43509. var fallbacks = new BABYLON.EffectFallbacks();
  43510. if (useInstances) {
  43511. defines.push("#define INSTANCES");
  43512. }
  43513. for (var index = 0; index < this._options.defines.length; index++) {
  43514. defines.push(this._options.defines[index]);
  43515. }
  43516. // Bones
  43517. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43518. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43519. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43520. fallbacks.addCPUSkinningFallback(0, mesh);
  43521. }
  43522. // Alpha test
  43523. if (engine.getAlphaTesting()) {
  43524. defines.push("#define ALPHATEST");
  43525. }
  43526. var previousEffect = this._effect;
  43527. var join = defines.join("\n");
  43528. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  43529. if (!this._effect.isReady()) {
  43530. return false;
  43531. }
  43532. if (previousEffect !== this._effect) {
  43533. scene.resetCachedMaterial();
  43534. }
  43535. this._renderId = scene.getRenderId();
  43536. return true;
  43537. };
  43538. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43539. var scene = this.getScene();
  43540. if (this._options.uniforms.indexOf("world") !== -1) {
  43541. this._effect.setMatrix("world", world);
  43542. }
  43543. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43544. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43545. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43546. }
  43547. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43548. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43549. }
  43550. };
  43551. ShaderMaterial.prototype.bind = function (world, mesh) {
  43552. // Std values
  43553. this.bindOnlyWorldMatrix(world);
  43554. if (this.getScene().getCachedMaterial() !== this) {
  43555. if (this._options.uniforms.indexOf("view") !== -1) {
  43556. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43557. }
  43558. if (this._options.uniforms.indexOf("projection") !== -1) {
  43559. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43560. }
  43561. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43562. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43563. }
  43564. // Bones
  43565. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43566. var name;
  43567. // Texture
  43568. for (name in this._textures) {
  43569. this._effect.setTexture(name, this._textures[name]);
  43570. }
  43571. // Texture arrays
  43572. for (name in this._textureArrays) {
  43573. this._effect.setTextureArray(name, this._textureArrays[name]);
  43574. }
  43575. // Float
  43576. for (name in this._floats) {
  43577. this._effect.setFloat(name, this._floats[name]);
  43578. }
  43579. // Float s
  43580. for (name in this._floatsArrays) {
  43581. this._effect.setArray(name, this._floatsArrays[name]);
  43582. }
  43583. // Color3
  43584. for (name in this._colors3) {
  43585. this._effect.setColor3(name, this._colors3[name]);
  43586. }
  43587. // Color4
  43588. for (name in this._colors4) {
  43589. var color = this._colors4[name];
  43590. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43591. }
  43592. // Vector2
  43593. for (name in this._vectors2) {
  43594. this._effect.setVector2(name, this._vectors2[name]);
  43595. }
  43596. // Vector3
  43597. for (name in this._vectors3) {
  43598. this._effect.setVector3(name, this._vectors3[name]);
  43599. }
  43600. // Vector4
  43601. for (name in this._vectors4) {
  43602. this._effect.setVector4(name, this._vectors4[name]);
  43603. }
  43604. // Matrix
  43605. for (name in this._matrices) {
  43606. this._effect.setMatrix(name, this._matrices[name]);
  43607. }
  43608. // Matrix 3x3
  43609. for (name in this._matrices3x3) {
  43610. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43611. }
  43612. // Matrix 2x2
  43613. for (name in this._matrices2x2) {
  43614. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43615. }
  43616. // Vector3Array
  43617. for (name in this._vectors3Arrays) {
  43618. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43619. }
  43620. }
  43621. _super.prototype.bind.call(this, world, mesh);
  43622. };
  43623. ShaderMaterial.prototype.clone = function (name) {
  43624. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43625. return newShaderMaterial;
  43626. };
  43627. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43628. if (forceDisposeTextures) {
  43629. var name;
  43630. for (name in this._textures) {
  43631. this._textures[name].dispose();
  43632. }
  43633. for (name in this._textureArrays) {
  43634. var array = this._textureArrays[name];
  43635. for (var index = 0; index < array.length; index++) {
  43636. array[index].dispose();
  43637. }
  43638. }
  43639. }
  43640. this._textures = {};
  43641. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43642. };
  43643. ShaderMaterial.prototype.serialize = function () {
  43644. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43645. serializationObject.customType = "BABYLON.ShaderMaterial";
  43646. serializationObject.options = this._options;
  43647. serializationObject.shaderPath = this._shaderPath;
  43648. var name;
  43649. // Texture
  43650. serializationObject.textures = {};
  43651. for (name in this._textures) {
  43652. serializationObject.textures[name] = this._textures[name].serialize();
  43653. }
  43654. // Texture arrays
  43655. serializationObject.textureArrays = {};
  43656. for (name in this._textureArrays) {
  43657. serializationObject.textureArrays[name] = [];
  43658. var array = this._textureArrays[name];
  43659. for (var index = 0; index < array.length; index++) {
  43660. serializationObject.textureArrays[name].push(array[index].serialize());
  43661. }
  43662. }
  43663. // Float
  43664. serializationObject.floats = {};
  43665. for (name in this._floats) {
  43666. serializationObject.floats[name] = this._floats[name];
  43667. }
  43668. // Float s
  43669. serializationObject.floatArrays = {};
  43670. for (name in this._floatsArrays) {
  43671. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43672. }
  43673. // Color3
  43674. serializationObject.colors3 = {};
  43675. for (name in this._colors3) {
  43676. serializationObject.colors3[name] = this._colors3[name].asArray();
  43677. }
  43678. // Color4
  43679. serializationObject.colors4 = {};
  43680. for (name in this._colors4) {
  43681. serializationObject.colors4[name] = this._colors4[name].asArray();
  43682. }
  43683. // Vector2
  43684. serializationObject.vectors2 = {};
  43685. for (name in this._vectors2) {
  43686. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43687. }
  43688. // Vector3
  43689. serializationObject.vectors3 = {};
  43690. for (name in this._vectors3) {
  43691. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43692. }
  43693. // Vector4
  43694. serializationObject.vectors4 = {};
  43695. for (name in this._vectors4) {
  43696. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43697. }
  43698. // Matrix
  43699. serializationObject.matrices = {};
  43700. for (name in this._matrices) {
  43701. serializationObject.matrices[name] = this._matrices[name].asArray();
  43702. }
  43703. // Matrix 3x3
  43704. serializationObject.matrices3x3 = {};
  43705. for (name in this._matrices3x3) {
  43706. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43707. }
  43708. // Matrix 2x2
  43709. serializationObject.matrices2x2 = {};
  43710. for (name in this._matrices2x2) {
  43711. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43712. }
  43713. // Vector3Array
  43714. serializationObject.vectors3Arrays = {};
  43715. for (name in this._vectors3Arrays) {
  43716. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43717. }
  43718. return serializationObject;
  43719. };
  43720. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43721. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43722. var name;
  43723. // Texture
  43724. for (name in source.textures) {
  43725. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43726. }
  43727. // Texture arrays
  43728. for (name in source.textureArrays) {
  43729. var array = source.textureArrays[name];
  43730. var textureArray = new Array();
  43731. for (var index = 0; index < array.length; index++) {
  43732. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43733. }
  43734. material.setTextureArray(name, textureArray);
  43735. }
  43736. // Float
  43737. for (name in source.floats) {
  43738. material.setFloat(name, source.floats[name]);
  43739. }
  43740. // Float s
  43741. for (name in source.floatsArrays) {
  43742. material.setFloats(name, source.floatsArrays[name]);
  43743. }
  43744. // Color3
  43745. for (name in source.colors3) {
  43746. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43747. }
  43748. // Color4
  43749. for (name in source.colors4) {
  43750. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43751. }
  43752. // Vector2
  43753. for (name in source.vectors2) {
  43754. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43755. }
  43756. // Vector3
  43757. for (name in source.vectors3) {
  43758. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43759. }
  43760. // Vector4
  43761. for (name in source.vectors4) {
  43762. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43763. }
  43764. // Matrix
  43765. for (name in source.matrices) {
  43766. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43767. }
  43768. // Matrix 3x3
  43769. for (name in source.matrices3x3) {
  43770. material.setMatrix3x3(name, source.matrices3x3[name]);
  43771. }
  43772. // Matrix 2x2
  43773. for (name in source.matrices2x2) {
  43774. material.setMatrix2x2(name, source.matrices2x2[name]);
  43775. }
  43776. // Vector3Array
  43777. for (name in source.vectors3Arrays) {
  43778. material.setArray3(name, source.vectors3Arrays[name]);
  43779. }
  43780. return material;
  43781. };
  43782. return ShaderMaterial;
  43783. }(BABYLON.Material));
  43784. BABYLON.ShaderMaterial = ShaderMaterial;
  43785. })(BABYLON || (BABYLON = {}));
  43786. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43787. var BABYLON;
  43788. (function (BABYLON) {
  43789. var Internals;
  43790. (function (Internals) {
  43791. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  43792. // All values and structures referenced from:
  43793. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  43794. var DDS_MAGIC = 0x20534444;
  43795. 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;
  43796. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  43797. 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;
  43798. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  43799. function FourCCToInt32(value) {
  43800. return value.charCodeAt(0) +
  43801. (value.charCodeAt(1) << 8) +
  43802. (value.charCodeAt(2) << 16) +
  43803. (value.charCodeAt(3) << 24);
  43804. }
  43805. function Int32ToFourCC(value) {
  43806. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  43807. }
  43808. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  43809. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  43810. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  43811. var headerLengthInt = 31; // The header length in 32 bit ints
  43812. // Offsets into the header array
  43813. var off_magic = 0;
  43814. var off_size = 1;
  43815. var off_flags = 2;
  43816. var off_height = 3;
  43817. var off_width = 4;
  43818. var off_mipmapCount = 7;
  43819. var off_pfFlags = 20;
  43820. var off_pfFourCC = 21;
  43821. var off_RGBbpp = 22;
  43822. var off_RMask = 23;
  43823. var off_GMask = 24;
  43824. var off_BMask = 25;
  43825. var off_AMask = 26;
  43826. var off_caps1 = 27;
  43827. var off_caps2 = 28;
  43828. ;
  43829. var DDSTools = (function () {
  43830. function DDSTools() {
  43831. }
  43832. DDSTools.GetDDSInfo = function (arrayBuffer) {
  43833. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  43834. var mipmapCount = 1;
  43835. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  43836. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43837. }
  43838. return {
  43839. width: header[off_width],
  43840. height: header[off_height],
  43841. mipmapCount: mipmapCount,
  43842. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  43843. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  43844. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  43845. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  43846. };
  43847. };
  43848. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43849. var byteArray = new Uint8Array(dataLength);
  43850. var srcData = new Uint8Array(arrayBuffer);
  43851. var index = 0;
  43852. for (var y = height - 1; y >= 0; y--) {
  43853. for (var x = 0; x < width; x++) {
  43854. var srcPos = dataOffset + (x + y * width) * 4;
  43855. byteArray[index + 2] = srcData[srcPos];
  43856. byteArray[index + 1] = srcData[srcPos + 1];
  43857. byteArray[index] = srcData[srcPos + 2];
  43858. byteArray[index + 3] = srcData[srcPos + 3];
  43859. index += 4;
  43860. }
  43861. }
  43862. return byteArray;
  43863. };
  43864. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43865. var byteArray = new Uint8Array(dataLength);
  43866. var srcData = new Uint8Array(arrayBuffer);
  43867. var index = 0;
  43868. for (var y = height - 1; y >= 0; y--) {
  43869. for (var x = 0; x < width; x++) {
  43870. var srcPos = dataOffset + (x + y * width) * 3;
  43871. byteArray[index + 2] = srcData[srcPos];
  43872. byteArray[index + 1] = srcData[srcPos + 1];
  43873. byteArray[index] = srcData[srcPos + 2];
  43874. index += 3;
  43875. }
  43876. }
  43877. return byteArray;
  43878. };
  43879. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43880. var byteArray = new Uint8Array(dataLength);
  43881. var srcData = new Uint8Array(arrayBuffer);
  43882. var index = 0;
  43883. for (var y = height - 1; y >= 0; y--) {
  43884. for (var x = 0; x < width; x++) {
  43885. var srcPos = dataOffset + (x + y * width);
  43886. byteArray[index] = srcData[srcPos];
  43887. index++;
  43888. }
  43889. }
  43890. return byteArray;
  43891. };
  43892. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  43893. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  43894. if (header[off_magic] != DDS_MAGIC) {
  43895. BABYLON.Tools.Error("Invalid magic number in DDS header");
  43896. return;
  43897. }
  43898. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  43899. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  43900. return;
  43901. }
  43902. if (info.isFourCC) {
  43903. fourCC = header[off_pfFourCC];
  43904. switch (fourCC) {
  43905. case FOURCC_DXT1:
  43906. blockBytes = 8;
  43907. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43908. break;
  43909. case FOURCC_DXT3:
  43910. blockBytes = 16;
  43911. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43912. break;
  43913. case FOURCC_DXT5:
  43914. blockBytes = 16;
  43915. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43916. break;
  43917. default:
  43918. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  43919. return;
  43920. }
  43921. }
  43922. mipmapCount = 1;
  43923. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  43924. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43925. }
  43926. var bpp = header[off_RGBbpp];
  43927. for (var face = 0; face < faces; face++) {
  43928. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  43929. width = header[off_width];
  43930. height = header[off_height];
  43931. dataOffset = header[off_size] + 4;
  43932. for (i = 0; i < mipmapCount; ++i) {
  43933. if (info.isRGB) {
  43934. if (bpp === 24) {
  43935. dataLength = width * height * 3;
  43936. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43937. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  43938. }
  43939. else {
  43940. dataLength = width * height * 4;
  43941. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43942. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  43943. }
  43944. }
  43945. else if (info.isLuminance) {
  43946. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  43947. var unpaddedRowSize = width;
  43948. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  43949. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  43950. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43951. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  43952. }
  43953. else {
  43954. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  43955. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  43956. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  43957. }
  43958. dataOffset += dataLength;
  43959. width *= 0.5;
  43960. height *= 0.5;
  43961. width = Math.max(1.0, width);
  43962. height = Math.max(1.0, height);
  43963. }
  43964. }
  43965. };
  43966. return DDSTools;
  43967. }());
  43968. Internals.DDSTools = DDSTools;
  43969. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43970. })(BABYLON || (BABYLON = {}));
  43971. //# sourceMappingURL=babylon.tools.dds.js.map
  43972. var BABYLON;
  43973. (function (BABYLON) {
  43974. var Internals;
  43975. (function (Internals) {
  43976. /**
  43977. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  43978. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  43979. */
  43980. var KhronosTextureContainer = (function () {
  43981. /**
  43982. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  43983. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  43984. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  43985. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  43986. */
  43987. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  43988. this.arrayBuffer = arrayBuffer;
  43989. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  43990. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  43991. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  43992. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  43993. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  43994. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  43995. BABYLON.Tools.Error("texture missing KTX identifier");
  43996. return;
  43997. }
  43998. // load the reset of the header in native 32 bit int
  43999. var header = new Int32Array(this.arrayBuffer, 12, 13);
  44000. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  44001. var oppositeEndianess = header[0] === 0x01020304;
  44002. // read all the header elements in order they exist in the file, without modification (sans endainness)
  44003. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  44004. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  44005. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  44006. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  44007. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  44008. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  44009. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  44010. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  44011. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  44012. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  44013. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  44014. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  44015. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  44016. if (this.glType !== 0) {
  44017. BABYLON.Tools.Error("only compressed formats currently supported");
  44018. return;
  44019. }
  44020. else {
  44021. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  44022. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  44023. }
  44024. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  44025. BABYLON.Tools.Error("only 2D textures currently supported");
  44026. return;
  44027. }
  44028. if (this.numberOfArrayElements !== 0) {
  44029. BABYLON.Tools.Error("texture arrays not currently supported");
  44030. return;
  44031. }
  44032. if (this.numberOfFaces !== facesExpected) {
  44033. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  44034. return;
  44035. }
  44036. // we now have a completely validated file, so could use existence of loadType as success
  44037. // would need to make this more elaborate & adjust checks above to support more than one load type
  44038. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  44039. }
  44040. // not as fast hardware based, but will probably never need to use
  44041. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  44042. return ((val & 0xFF) << 24)
  44043. | ((val & 0xFF00) << 8)
  44044. | ((val >> 8) & 0xFF00)
  44045. | ((val >> 24) & 0xFF);
  44046. };
  44047. /**
  44048. * It is assumed that the texture has already been created & is currently bound
  44049. */
  44050. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  44051. switch (this.loadType) {
  44052. case KhronosTextureContainer.COMPRESSED_2D:
  44053. this._upload2DCompressedLevels(gl, loadMipmaps);
  44054. break;
  44055. case KhronosTextureContainer.TEX_2D:
  44056. case KhronosTextureContainer.COMPRESSED_3D:
  44057. case KhronosTextureContainer.TEX_3D:
  44058. }
  44059. };
  44060. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  44061. // initialize width & height for level 1
  44062. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  44063. var width = this.pixelWidth;
  44064. var height = this.pixelHeight;
  44065. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  44066. for (var level = 0; level < mipmapCount; level++) {
  44067. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  44068. for (var face = 0; face < this.numberOfFaces; face++) {
  44069. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44070. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  44071. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  44072. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  44073. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  44074. }
  44075. width = Math.max(1.0, width * 0.5);
  44076. height = Math.max(1.0, height * 0.5);
  44077. }
  44078. };
  44079. return KhronosTextureContainer;
  44080. }());
  44081. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  44082. // load types
  44083. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  44084. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  44085. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  44086. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  44087. Internals.KhronosTextureContainer = KhronosTextureContainer;
  44088. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44089. })(BABYLON || (BABYLON = {}));
  44090. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  44091. var BABYLON;
  44092. (function (BABYLON) {
  44093. var CannonJSPlugin = (function () {
  44094. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  44095. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  44096. if (iterations === void 0) { iterations = 10; }
  44097. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  44098. this.name = "CannonJSPlugin";
  44099. this._physicsMaterials = [];
  44100. this._fixedTimeStep = 1 / 60;
  44101. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44102. this._currentCollisionGroup = 2;
  44103. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  44104. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  44105. this._tmpPosition = BABYLON.Vector3.Zero();
  44106. this._tmpQuaternion = new BABYLON.Quaternion();
  44107. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  44108. this._tmpDeltaRotation = new BABYLON.Quaternion();
  44109. this._tmpUnityRotation = new BABYLON.Quaternion();
  44110. if (!this.isSupported()) {
  44111. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  44112. return;
  44113. }
  44114. this.world = new CANNON.World();
  44115. this.world.broadphase = new CANNON.NaiveBroadphase();
  44116. this.world.solver.iterations = iterations;
  44117. }
  44118. CannonJSPlugin.prototype.setGravity = function (gravity) {
  44119. this.world.gravity.copy(gravity);
  44120. };
  44121. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  44122. this._fixedTimeStep = timeStep;
  44123. };
  44124. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  44125. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  44126. };
  44127. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44128. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44129. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44130. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  44131. };
  44132. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44133. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44134. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44135. impostor.physicsBody.applyForce(impulse, worldPoint);
  44136. };
  44137. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44138. //parent-child relationship. Does this impostor has a parent impostor?
  44139. if (impostor.parent) {
  44140. if (impostor.physicsBody) {
  44141. this.removePhysicsBody(impostor);
  44142. //TODO is that needed?
  44143. impostor.forceUpdate();
  44144. }
  44145. return;
  44146. }
  44147. //should a new body be created for this impostor?
  44148. if (impostor.isBodyInitRequired()) {
  44149. var shape = this._createShape(impostor);
  44150. //unregister events, if body is being changed
  44151. var oldBody = impostor.physicsBody;
  44152. if (oldBody) {
  44153. this.removePhysicsBody(impostor);
  44154. }
  44155. //create the body and material
  44156. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  44157. var bodyCreationObject = {
  44158. mass: impostor.getParam("mass"),
  44159. material: material
  44160. };
  44161. // A simple extend, in case native options were used.
  44162. var nativeOptions = impostor.getParam("nativeOptions");
  44163. for (var key in nativeOptions) {
  44164. if (nativeOptions.hasOwnProperty(key)) {
  44165. bodyCreationObject[key] = nativeOptions[key];
  44166. }
  44167. }
  44168. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  44169. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  44170. this.world.addEventListener("preStep", impostor.beforeStep);
  44171. this.world.addEventListener("postStep", impostor.afterStep);
  44172. impostor.physicsBody.addShape(shape);
  44173. this.world.add(impostor.physicsBody);
  44174. //try to keep the body moving in the right direction by taking old properties.
  44175. //Should be tested!
  44176. if (oldBody) {
  44177. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  44178. impostor.physicsBody[param].copy(oldBody[param]);
  44179. });
  44180. }
  44181. this._processChildMeshes(impostor);
  44182. }
  44183. //now update the body's transformation
  44184. this._updatePhysicsBodyTransformation(impostor);
  44185. };
  44186. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  44187. var _this = this;
  44188. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  44189. if (meshChildren.length) {
  44190. var processMesh = function (localPosition, mesh) {
  44191. var childImpostor = mesh.getPhysicsImpostor();
  44192. if (childImpostor) {
  44193. var parent = childImpostor.parent;
  44194. if (parent !== mainImpostor) {
  44195. var localPosition = mesh.position;
  44196. if (childImpostor.physicsBody) {
  44197. _this.removePhysicsBody(childImpostor);
  44198. childImpostor.physicsBody = null;
  44199. }
  44200. childImpostor.parent = mainImpostor;
  44201. childImpostor.resetUpdateFlags();
  44202. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  44203. //Add the mass of the children.
  44204. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  44205. }
  44206. }
  44207. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  44208. };
  44209. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  44210. }
  44211. };
  44212. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44213. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  44214. this.world.removeEventListener("preStep", impostor.beforeStep);
  44215. this.world.removeEventListener("postStep", impostor.afterStep);
  44216. this.world.remove(impostor.physicsBody);
  44217. };
  44218. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44219. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44220. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44221. if (!mainBody || !connectedBody) {
  44222. return;
  44223. }
  44224. var constraint;
  44225. var jointData = impostorJoint.joint.jointData;
  44226. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44227. var constraintData = {
  44228. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  44229. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  44230. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  44231. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  44232. maxForce: jointData.nativeParams.maxForce,
  44233. collideConnected: !!jointData.collision
  44234. };
  44235. switch (impostorJoint.joint.type) {
  44236. case BABYLON.PhysicsJoint.HingeJoint:
  44237. case BABYLON.PhysicsJoint.Hinge2Joint:
  44238. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  44239. break;
  44240. case BABYLON.PhysicsJoint.DistanceJoint:
  44241. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  44242. break;
  44243. case BABYLON.PhysicsJoint.SpringJoint:
  44244. var springData = jointData;
  44245. constraint = new CANNON.Spring(mainBody, connectedBody, {
  44246. restLength: springData.length,
  44247. stiffness: springData.stiffness,
  44248. damping: springData.damping,
  44249. localAnchorA: constraintData.pivotA,
  44250. localAnchorB: constraintData.pivotB
  44251. });
  44252. break;
  44253. case BABYLON.PhysicsJoint.LockJoint:
  44254. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  44255. break;
  44256. case BABYLON.PhysicsJoint.PointToPointJoint:
  44257. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44258. default:
  44259. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  44260. break;
  44261. }
  44262. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  44263. constraint.collideConnected = !!jointData.collision;
  44264. impostorJoint.joint.physicsJoint = constraint;
  44265. //don't add spring as constraint, as it is not one.
  44266. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  44267. this.world.addConstraint(constraint);
  44268. }
  44269. else {
  44270. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  44271. constraint.applyForce();
  44272. });
  44273. }
  44274. };
  44275. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44276. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  44277. };
  44278. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  44279. var index;
  44280. var mat;
  44281. for (index = 0; index < this._physicsMaterials.length; index++) {
  44282. mat = this._physicsMaterials[index];
  44283. if (mat.friction === friction && mat.restitution === restitution) {
  44284. return mat;
  44285. }
  44286. }
  44287. var currentMat = new CANNON.Material(name);
  44288. currentMat.friction = friction;
  44289. currentMat.restitution = restitution;
  44290. this._physicsMaterials.push(currentMat);
  44291. return currentMat;
  44292. };
  44293. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  44294. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  44295. };
  44296. CannonJSPlugin.prototype._createShape = function (impostor) {
  44297. var object = impostor.object;
  44298. var returnValue;
  44299. var extendSize = impostor.getObjectExtendSize();
  44300. switch (impostor.type) {
  44301. case BABYLON.PhysicsEngine.SphereImpostor:
  44302. var radiusX = extendSize.x;
  44303. var radiusY = extendSize.y;
  44304. var radiusZ = extendSize.z;
  44305. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  44306. break;
  44307. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  44308. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44309. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  44310. break;
  44311. case BABYLON.PhysicsImpostor.BoxImpostor:
  44312. var box = extendSize.scale(0.5);
  44313. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  44314. break;
  44315. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44316. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  44317. returnValue = new CANNON.Plane();
  44318. break;
  44319. case BABYLON.PhysicsImpostor.MeshImpostor:
  44320. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  44321. var rawFaces = object.getIndices ? object.getIndices() : [];
  44322. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  44323. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  44324. break;
  44325. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  44326. returnValue = this._createHeightmap(object);
  44327. break;
  44328. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44329. returnValue = new CANNON.Particle();
  44330. break;
  44331. }
  44332. return returnValue;
  44333. };
  44334. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  44335. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44336. var matrix = [];
  44337. //For now pointDepth will not be used and will be automatically calculated.
  44338. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  44339. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  44340. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  44341. var elementSize = dim * 2 / arraySize;
  44342. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  44343. for (var i = 0; i < pos.length; i = i + 3) {
  44344. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  44345. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  44346. var y = pos[i + 1] + minY;
  44347. if (!matrix[x]) {
  44348. matrix[x] = [];
  44349. }
  44350. if (!matrix[x][z]) {
  44351. matrix[x][z] = y;
  44352. }
  44353. matrix[x][z] = Math.max(y, matrix[x][z]);
  44354. }
  44355. for (var x = 0; x <= arraySize; ++x) {
  44356. if (!matrix[x]) {
  44357. var loc = 1;
  44358. while (!matrix[(x + loc) % arraySize]) {
  44359. loc++;
  44360. }
  44361. matrix[x] = matrix[(x + loc) % arraySize].slice();
  44362. }
  44363. for (var z = 0; z <= arraySize; ++z) {
  44364. if (!matrix[x][z]) {
  44365. var loc = 1;
  44366. var newValue;
  44367. while (newValue === undefined) {
  44368. newValue = matrix[x][(z + loc++) % arraySize];
  44369. }
  44370. matrix[x][z] = newValue;
  44371. }
  44372. }
  44373. }
  44374. var shape = new CANNON.Heightfield(matrix, {
  44375. elementSize: elementSize
  44376. });
  44377. //For future reference, needed for body transformation
  44378. shape.minY = minY;
  44379. return shape;
  44380. };
  44381. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  44382. var object = impostor.object;
  44383. //make sure it is updated...
  44384. object.computeWorldMatrix && object.computeWorldMatrix(true);
  44385. // The delta between the mesh position and the mesh bounding box center
  44386. var center = impostor.getObjectCenter();
  44387. var extendSize = impostor.getObjectExtendSize();
  44388. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  44389. this._tmpPosition.copyFrom(center);
  44390. var quaternion = object.rotationQuaternion;
  44391. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  44392. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  44393. //-90 DEG in X, precalculated
  44394. quaternion = quaternion.multiply(this._minus90X);
  44395. //Invert! (Precalculated, 90 deg in X)
  44396. //No need to clone. this will never change.
  44397. impostor.setDeltaRotation(this._plus90X);
  44398. }
  44399. //If it is a heightfield, if should be centered.
  44400. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  44401. var mesh = object;
  44402. //calculate the correct body position:
  44403. var rotationQuaternion = mesh.rotationQuaternion;
  44404. mesh.rotationQuaternion = this._tmpUnityRotation;
  44405. mesh.computeWorldMatrix(true);
  44406. //get original center with no rotation
  44407. var c = center.clone();
  44408. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  44409. //rotation is back
  44410. mesh.rotationQuaternion = rotationQuaternion;
  44411. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  44412. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  44413. mesh.setPivotMatrix(p);
  44414. mesh.computeWorldMatrix(true);
  44415. //calculate the translation
  44416. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  44417. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  44418. //add it inverted to the delta
  44419. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  44420. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  44421. mesh.setPivotMatrix(oldPivot);
  44422. mesh.computeWorldMatrix(true);
  44423. }
  44424. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  44425. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  44426. this._tmpPosition.copyFrom(object.position);
  44427. }
  44428. impostor.setDeltaPosition(this._tmpDeltaPosition);
  44429. //Now update the impostor object
  44430. impostor.physicsBody.position.copy(this._tmpPosition);
  44431. impostor.physicsBody.quaternion.copy(quaternion);
  44432. };
  44433. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44434. impostor.object.position.copyFrom(impostor.physicsBody.position);
  44435. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  44436. };
  44437. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44438. impostor.physicsBody.position.copy(newPosition);
  44439. impostor.physicsBody.quaternion.copy(newRotation);
  44440. };
  44441. CannonJSPlugin.prototype.isSupported = function () {
  44442. return window.CANNON !== undefined;
  44443. };
  44444. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44445. impostor.physicsBody.velocity.copy(velocity);
  44446. };
  44447. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44448. impostor.physicsBody.angularVelocity.copy(velocity);
  44449. };
  44450. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44451. var v = impostor.physicsBody.velocity;
  44452. if (!v)
  44453. return null;
  44454. return new BABYLON.Vector3(v.x, v.y, v.z);
  44455. };
  44456. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44457. var v = impostor.physicsBody.angularVelocity;
  44458. if (!v)
  44459. return null;
  44460. return new BABYLON.Vector3(v.x, v.y, v.z);
  44461. };
  44462. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44463. impostor.physicsBody.mass = mass;
  44464. impostor.physicsBody.updateMassProperties();
  44465. };
  44466. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  44467. impostor.physicsBody.sleep();
  44468. };
  44469. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  44470. impostor.physicsBody.wakeUp();
  44471. };
  44472. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44473. joint.physicsJoint.distance = maxDistance;
  44474. };
  44475. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  44476. if (!motorIndex) {
  44477. joint.physicsJoint.enableMotor();
  44478. }
  44479. };
  44480. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  44481. if (!motorIndex) {
  44482. joint.physicsJoint.disableMotor();
  44483. }
  44484. };
  44485. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44486. if (!motorIndex) {
  44487. joint.physicsJoint.enableMotor();
  44488. joint.physicsJoint.setMotorSpeed(speed);
  44489. if (maxForce) {
  44490. this.setLimit(joint, maxForce);
  44491. }
  44492. }
  44493. };
  44494. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  44495. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  44496. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  44497. };
  44498. CannonJSPlugin.prototype.dispose = function () {
  44499. //nothing to do, actually.
  44500. };
  44501. return CannonJSPlugin;
  44502. }());
  44503. BABYLON.CannonJSPlugin = CannonJSPlugin;
  44504. })(BABYLON || (BABYLON = {}));
  44505. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  44506. var BABYLON;
  44507. (function (BABYLON) {
  44508. var OimoJSPlugin = (function () {
  44509. function OimoJSPlugin(iterations) {
  44510. this.name = "OimoJSPlugin";
  44511. this._tmpImpostorsArray = [];
  44512. this._tmpPositionVector = BABYLON.Vector3.Zero();
  44513. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  44514. this.world.worldscale(1);
  44515. this.world.clear();
  44516. //making sure no stats are calculated
  44517. this.world.isNoStat = true;
  44518. }
  44519. OimoJSPlugin.prototype.setGravity = function (gravity) {
  44520. this.world.gravity.copy(gravity);
  44521. };
  44522. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  44523. this.world.timeStep = timeStep;
  44524. };
  44525. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  44526. var _this = this;
  44527. impostors.forEach(function (impostor) {
  44528. impostor.beforeStep();
  44529. });
  44530. this.world.step();
  44531. impostors.forEach(function (impostor) {
  44532. impostor.afterStep();
  44533. //update the ordered impostors array
  44534. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44535. });
  44536. //check for collisions
  44537. var contact = this.world.contacts;
  44538. while (contact !== null) {
  44539. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  44540. contact = contact.next;
  44541. continue;
  44542. }
  44543. //is this body colliding with any other? get the impostor
  44544. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  44545. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  44546. if (!mainImpostor || !collidingImpostor) {
  44547. contact = contact.next;
  44548. continue;
  44549. }
  44550. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  44551. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  44552. contact = contact.next;
  44553. }
  44554. };
  44555. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44556. var mass = impostor.physicsBody.massInfo.mass;
  44557. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  44558. };
  44559. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44560. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  44561. this.applyImpulse(impostor, force, contactPoint);
  44562. };
  44563. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44564. var _this = this;
  44565. //parent-child relationship. Does this impostor has a parent impostor?
  44566. if (impostor.parent) {
  44567. if (impostor.physicsBody) {
  44568. this.removePhysicsBody(impostor);
  44569. //TODO is that needed?
  44570. impostor.forceUpdate();
  44571. }
  44572. return;
  44573. }
  44574. if (impostor.isBodyInitRequired()) {
  44575. var bodyConfig = {
  44576. name: impostor.uniqueId,
  44577. //Oimo must have mass, also for static objects.
  44578. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  44579. size: [],
  44580. type: [],
  44581. pos: [],
  44582. rot: [],
  44583. move: impostor.getParam("mass") !== 0,
  44584. //Supporting older versions of Oimo
  44585. world: this.world
  44586. };
  44587. var impostors = [impostor];
  44588. var addToArray = function (parent) {
  44589. if (!parent.getChildMeshes)
  44590. return;
  44591. parent.getChildMeshes().forEach(function (m) {
  44592. if (m.physicsImpostor) {
  44593. impostors.push(m.physicsImpostor);
  44594. m.physicsImpostor._init();
  44595. }
  44596. });
  44597. };
  44598. addToArray(impostor.object);
  44599. var checkWithEpsilon_1 = function (value) {
  44600. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  44601. };
  44602. impostors.forEach(function (i) {
  44603. //get the correct bounding box
  44604. var oldQuaternion = i.object.rotationQuaternion;
  44605. var rot = new OIMO.Euler().setFromQuaternion({
  44606. x: impostor.object.rotationQuaternion.x,
  44607. y: impostor.object.rotationQuaternion.y,
  44608. z: impostor.object.rotationQuaternion.z,
  44609. s: impostor.object.rotationQuaternion.w
  44610. });
  44611. var extendSize = i.getObjectExtendSize();
  44612. if (i === impostor) {
  44613. var center = impostor.getObjectCenter();
  44614. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  44615. //Can also use Array.prototype.push.apply
  44616. bodyConfig.pos.push(center.x);
  44617. bodyConfig.pos.push(center.y);
  44618. bodyConfig.pos.push(center.z);
  44619. //tmp solution
  44620. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  44621. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  44622. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  44623. }
  44624. else {
  44625. bodyConfig.pos.push(i.object.position.x);
  44626. bodyConfig.pos.push(i.object.position.y);
  44627. bodyConfig.pos.push(i.object.position.z);
  44628. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  44629. bodyConfig.rot.push(0);
  44630. bodyConfig.rot.push(0);
  44631. bodyConfig.rot.push(0);
  44632. }
  44633. // register mesh
  44634. switch (i.type) {
  44635. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44636. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  44637. case BABYLON.PhysicsImpostor.SphereImpostor:
  44638. var radiusX = extendSize.x;
  44639. var radiusY = extendSize.y;
  44640. var radiusZ = extendSize.z;
  44641. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  44642. bodyConfig.type.push('sphere');
  44643. //due to the way oimo works with compounds, add 3 times
  44644. bodyConfig.size.push(size);
  44645. bodyConfig.size.push(size);
  44646. bodyConfig.size.push(size);
  44647. break;
  44648. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44649. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  44650. var sizeY = checkWithEpsilon_1(extendSize.y);
  44651. bodyConfig.type.push('cylinder');
  44652. bodyConfig.size.push(sizeX);
  44653. bodyConfig.size.push(sizeY);
  44654. //due to the way oimo works with compounds, add one more value.
  44655. bodyConfig.size.push(sizeY);
  44656. break;
  44657. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44658. case BABYLON.PhysicsImpostor.BoxImpostor:
  44659. default:
  44660. var sizeX = checkWithEpsilon_1(extendSize.x);
  44661. var sizeY = checkWithEpsilon_1(extendSize.y);
  44662. var sizeZ = checkWithEpsilon_1(extendSize.z);
  44663. bodyConfig.type.push('box');
  44664. bodyConfig.size.push(sizeX);
  44665. bodyConfig.size.push(sizeY);
  44666. bodyConfig.size.push(sizeZ);
  44667. break;
  44668. }
  44669. //actually not needed, but hey...
  44670. i.object.rotationQuaternion = oldQuaternion;
  44671. });
  44672. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  44673. }
  44674. else {
  44675. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  44676. }
  44677. impostor.setDeltaPosition(this._tmpPositionVector);
  44678. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  44679. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  44680. };
  44681. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44682. //impostor.physicsBody.dispose();
  44683. //Same as : (older oimo versions)
  44684. this.world.removeRigidBody(impostor.physicsBody);
  44685. };
  44686. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44687. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44688. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44689. if (!mainBody || !connectedBody) {
  44690. return;
  44691. }
  44692. var jointData = impostorJoint.joint.jointData;
  44693. var options = jointData.nativeParams || {};
  44694. var type;
  44695. var nativeJointData = {
  44696. body1: mainBody,
  44697. body2: connectedBody,
  44698. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  44699. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  44700. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  44701. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  44702. min: options.min,
  44703. max: options.max,
  44704. collision: options.collision || jointData.collision,
  44705. spring: options.spring,
  44706. //supporting older version of Oimo
  44707. world: this.world
  44708. };
  44709. switch (impostorJoint.joint.type) {
  44710. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44711. type = "jointBall";
  44712. break;
  44713. case BABYLON.PhysicsJoint.SpringJoint:
  44714. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  44715. var springData = jointData;
  44716. nativeJointData.min = springData.length || nativeJointData.min;
  44717. //Max should also be set, just make sure it is at least min
  44718. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  44719. case BABYLON.PhysicsJoint.DistanceJoint:
  44720. type = "jointDistance";
  44721. nativeJointData.max = jointData.maxDistance;
  44722. break;
  44723. case BABYLON.PhysicsJoint.PrismaticJoint:
  44724. type = "jointPrisme";
  44725. break;
  44726. case BABYLON.PhysicsJoint.SliderJoint:
  44727. type = "jointSlide";
  44728. break;
  44729. case BABYLON.PhysicsJoint.WheelJoint:
  44730. type = "jointWheel";
  44731. break;
  44732. case BABYLON.PhysicsJoint.HingeJoint:
  44733. default:
  44734. type = "jointHinge";
  44735. break;
  44736. }
  44737. nativeJointData.type = type;
  44738. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  44739. };
  44740. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44741. //Bug in Oimo prevents us from disposing a joint in the playground
  44742. //joint.joint.physicsJoint.dispose();
  44743. //So we will bruteforce it!
  44744. try {
  44745. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  44746. }
  44747. catch (e) {
  44748. BABYLON.Tools.Warn(e);
  44749. }
  44750. };
  44751. OimoJSPlugin.prototype.isSupported = function () {
  44752. return OIMO !== undefined;
  44753. };
  44754. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44755. if (!impostor.physicsBody.sleeping) {
  44756. //TODO check that
  44757. if (impostor.physicsBody.shapes.next) {
  44758. var parentShape = this._getLastShape(impostor.physicsBody);
  44759. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  44760. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  44761. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  44762. }
  44763. else {
  44764. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  44765. }
  44766. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  44767. impostor.object.rotationQuaternion.normalize();
  44768. }
  44769. };
  44770. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44771. var body = impostor.physicsBody;
  44772. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  44773. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  44774. body.syncShapes();
  44775. body.awake();
  44776. };
  44777. OimoJSPlugin.prototype._getLastShape = function (body) {
  44778. var lastShape = body.shapes;
  44779. while (lastShape.next) {
  44780. lastShape = lastShape.next;
  44781. }
  44782. return lastShape;
  44783. };
  44784. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44785. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  44786. };
  44787. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44788. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  44789. };
  44790. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44791. var v = impostor.physicsBody.linearVelocity;
  44792. if (!v)
  44793. return null;
  44794. return new BABYLON.Vector3(v.x, v.y, v.z);
  44795. };
  44796. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44797. var v = impostor.physicsBody.angularVelocity;
  44798. if (!v)
  44799. return null;
  44800. return new BABYLON.Vector3(v.x, v.y, v.z);
  44801. };
  44802. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44803. var staticBody = mass === 0;
  44804. //this will actually set the body's density and not its mass.
  44805. //But this is how oimo treats the mass variable.
  44806. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  44807. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  44808. };
  44809. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  44810. impostor.physicsBody.sleep();
  44811. };
  44812. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  44813. impostor.physicsBody.awake();
  44814. };
  44815. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44816. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  44817. if (minDistance !== void 0) {
  44818. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  44819. }
  44820. };
  44821. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44822. //TODO separate rotational and transational motors.
  44823. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44824. if (motor) {
  44825. motor.setMotor(speed, maxForce);
  44826. }
  44827. };
  44828. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  44829. //TODO separate rotational and transational motors.
  44830. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44831. if (motor) {
  44832. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  44833. }
  44834. };
  44835. OimoJSPlugin.prototype.dispose = function () {
  44836. this.world.clear();
  44837. };
  44838. return OimoJSPlugin;
  44839. }());
  44840. BABYLON.OimoJSPlugin = OimoJSPlugin;
  44841. })(BABYLON || (BABYLON = {}));
  44842. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  44843. var BABYLON;
  44844. (function (BABYLON) {
  44845. var DisplayPassPostProcess = (function (_super) {
  44846. __extends(DisplayPassPostProcess, _super);
  44847. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44848. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  44849. }
  44850. return DisplayPassPostProcess;
  44851. }(BABYLON.PostProcess));
  44852. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  44853. })(BABYLON || (BABYLON = {}));
  44854. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  44855. var BABYLON;
  44856. (function (BABYLON) {
  44857. var SimplificationSettings = (function () {
  44858. function SimplificationSettings(quality, distance, optimizeMesh) {
  44859. this.quality = quality;
  44860. this.distance = distance;
  44861. this.optimizeMesh = optimizeMesh;
  44862. }
  44863. return SimplificationSettings;
  44864. }());
  44865. BABYLON.SimplificationSettings = SimplificationSettings;
  44866. var SimplificationQueue = (function () {
  44867. function SimplificationQueue() {
  44868. this.running = false;
  44869. this._simplificationArray = [];
  44870. }
  44871. SimplificationQueue.prototype.addTask = function (task) {
  44872. this._simplificationArray.push(task);
  44873. };
  44874. SimplificationQueue.prototype.executeNext = function () {
  44875. var task = this._simplificationArray.pop();
  44876. if (task) {
  44877. this.running = true;
  44878. this.runSimplification(task);
  44879. }
  44880. else {
  44881. this.running = false;
  44882. }
  44883. };
  44884. SimplificationQueue.prototype.runSimplification = function (task) {
  44885. var _this = this;
  44886. if (task.parallelProcessing) {
  44887. //parallel simplifier
  44888. task.settings.forEach(function (setting) {
  44889. var simplifier = _this.getSimplifier(task);
  44890. simplifier.simplify(setting, function (newMesh) {
  44891. task.mesh.addLODLevel(setting.distance, newMesh);
  44892. newMesh.isVisible = true;
  44893. //check if it is the last
  44894. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  44895. //all done, run the success callback.
  44896. task.successCallback();
  44897. }
  44898. _this.executeNext();
  44899. });
  44900. });
  44901. }
  44902. else {
  44903. //single simplifier.
  44904. var simplifier = this.getSimplifier(task);
  44905. var runDecimation = function (setting, callback) {
  44906. simplifier.simplify(setting, function (newMesh) {
  44907. task.mesh.addLODLevel(setting.distance, newMesh);
  44908. newMesh.isVisible = true;
  44909. //run the next quality level
  44910. callback();
  44911. });
  44912. };
  44913. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  44914. runDecimation(task.settings[loop.index], function () {
  44915. loop.executeNext();
  44916. });
  44917. }, function () {
  44918. //execution ended, run the success callback.
  44919. if (task.successCallback) {
  44920. task.successCallback();
  44921. }
  44922. _this.executeNext();
  44923. });
  44924. }
  44925. };
  44926. SimplificationQueue.prototype.getSimplifier = function (task) {
  44927. switch (task.simplificationType) {
  44928. case SimplificationType.QUADRATIC:
  44929. default:
  44930. return new QuadraticErrorSimplification(task.mesh);
  44931. }
  44932. };
  44933. return SimplificationQueue;
  44934. }());
  44935. BABYLON.SimplificationQueue = SimplificationQueue;
  44936. /**
  44937. * The implemented types of simplification.
  44938. * At the moment only Quadratic Error Decimation is implemented.
  44939. */
  44940. var SimplificationType;
  44941. (function (SimplificationType) {
  44942. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  44943. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  44944. var DecimationTriangle = (function () {
  44945. function DecimationTriangle(vertices) {
  44946. this.vertices = vertices;
  44947. this.error = new Array(4);
  44948. this.deleted = false;
  44949. this.isDirty = false;
  44950. this.deletePending = false;
  44951. this.borderFactor = 0;
  44952. }
  44953. return DecimationTriangle;
  44954. }());
  44955. BABYLON.DecimationTriangle = DecimationTriangle;
  44956. var DecimationVertex = (function () {
  44957. function DecimationVertex(position, id) {
  44958. this.position = position;
  44959. this.id = id;
  44960. this.isBorder = true;
  44961. this.q = new QuadraticMatrix();
  44962. this.triangleCount = 0;
  44963. this.triangleStart = 0;
  44964. this.originalOffsets = [];
  44965. }
  44966. DecimationVertex.prototype.updatePosition = function (newPosition) {
  44967. this.position.copyFrom(newPosition);
  44968. };
  44969. return DecimationVertex;
  44970. }());
  44971. BABYLON.DecimationVertex = DecimationVertex;
  44972. var QuadraticMatrix = (function () {
  44973. function QuadraticMatrix(data) {
  44974. this.data = new Array(10);
  44975. for (var i = 0; i < 10; ++i) {
  44976. if (data && data[i]) {
  44977. this.data[i] = data[i];
  44978. }
  44979. else {
  44980. this.data[i] = 0;
  44981. }
  44982. }
  44983. }
  44984. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  44985. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  44986. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  44987. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  44988. return det;
  44989. };
  44990. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  44991. for (var i = 0; i < 10; ++i) {
  44992. this.data[i] += matrix.data[i];
  44993. }
  44994. };
  44995. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  44996. for (var i = 0; i < 10; ++i) {
  44997. this.data[i] += data[i];
  44998. }
  44999. };
  45000. QuadraticMatrix.prototype.add = function (matrix) {
  45001. var m = new QuadraticMatrix();
  45002. for (var i = 0; i < 10; ++i) {
  45003. m.data[i] = this.data[i] + matrix.data[i];
  45004. }
  45005. return m;
  45006. };
  45007. QuadraticMatrix.FromData = function (a, b, c, d) {
  45008. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  45009. };
  45010. //returning an array to avoid garbage collection
  45011. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  45012. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  45013. };
  45014. return QuadraticMatrix;
  45015. }());
  45016. BABYLON.QuadraticMatrix = QuadraticMatrix;
  45017. var Reference = (function () {
  45018. function Reference(vertexId, triangleId) {
  45019. this.vertexId = vertexId;
  45020. this.triangleId = triangleId;
  45021. }
  45022. return Reference;
  45023. }());
  45024. BABYLON.Reference = Reference;
  45025. /**
  45026. * An implementation of the Quadratic Error simplification algorithm.
  45027. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  45028. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  45029. * @author RaananW
  45030. */
  45031. var QuadraticErrorSimplification = (function () {
  45032. function QuadraticErrorSimplification(_mesh) {
  45033. this._mesh = _mesh;
  45034. this.initialized = false;
  45035. this.syncIterations = 5000;
  45036. this.aggressiveness = 7;
  45037. this.decimationIterations = 100;
  45038. this.boundingBoxEpsilon = BABYLON.Epsilon;
  45039. }
  45040. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  45041. var _this = this;
  45042. this.initDecimatedMesh();
  45043. //iterating through the submeshes array, one after the other.
  45044. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  45045. _this.initWithMesh(loop.index, function () {
  45046. _this.runDecimation(settings, loop.index, function () {
  45047. loop.executeNext();
  45048. });
  45049. }, settings.optimizeMesh);
  45050. }, function () {
  45051. setTimeout(function () {
  45052. successCallback(_this._reconstructedMesh);
  45053. }, 0);
  45054. });
  45055. };
  45056. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  45057. var _this = this;
  45058. var gCount = 0;
  45059. triangle.vertices.forEach(function (vertex) {
  45060. var count = 0;
  45061. var vPos = vertex.position;
  45062. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  45063. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  45064. ++count;
  45065. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  45066. ++count;
  45067. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  45068. ++count;
  45069. if (count > 1) {
  45070. ++gCount;
  45071. }
  45072. ;
  45073. });
  45074. if (gCount > 1) {
  45075. console.log(triangle, gCount);
  45076. }
  45077. return gCount > 1;
  45078. };
  45079. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  45080. var _this = this;
  45081. var targetCount = ~~(this.triangles.length * settings.quality);
  45082. var deletedTriangles = 0;
  45083. var triangleCount = this.triangles.length;
  45084. var iterationFunction = function (iteration, callback) {
  45085. setTimeout(function () {
  45086. if (iteration % 5 === 0) {
  45087. _this.updateMesh(iteration === 0);
  45088. }
  45089. for (var i = 0; i < _this.triangles.length; ++i) {
  45090. _this.triangles[i].isDirty = false;
  45091. }
  45092. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  45093. var trianglesIterator = function (i) {
  45094. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  45095. var t = _this.triangles[tIdx];
  45096. if (!t)
  45097. return;
  45098. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  45099. return;
  45100. }
  45101. for (var j = 0; j < 3; ++j) {
  45102. if (t.error[j] < threshold) {
  45103. var deleted0 = [];
  45104. var deleted1 = [];
  45105. var v0 = t.vertices[j];
  45106. var v1 = t.vertices[(j + 1) % 3];
  45107. if (v0.isBorder || v1.isBorder)
  45108. continue;
  45109. var p = BABYLON.Vector3.Zero();
  45110. var n = BABYLON.Vector3.Zero();
  45111. var uv = BABYLON.Vector2.Zero();
  45112. var color = new BABYLON.Color4(0, 0, 0, 1);
  45113. _this.calculateError(v0, v1, p, n, uv, color);
  45114. var delTr = [];
  45115. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  45116. continue;
  45117. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  45118. continue;
  45119. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  45120. continue;
  45121. var uniqueArray = [];
  45122. delTr.forEach(function (deletedT) {
  45123. if (uniqueArray.indexOf(deletedT) === -1) {
  45124. deletedT.deletePending = true;
  45125. uniqueArray.push(deletedT);
  45126. }
  45127. });
  45128. if (uniqueArray.length % 2 !== 0) {
  45129. continue;
  45130. }
  45131. v0.q = v1.q.add(v0.q);
  45132. v0.updatePosition(p);
  45133. var tStart = _this.references.length;
  45134. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  45135. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  45136. var tCount = _this.references.length - tStart;
  45137. if (tCount <= v0.triangleCount) {
  45138. if (tCount) {
  45139. for (var c = 0; c < tCount; c++) {
  45140. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  45141. }
  45142. }
  45143. }
  45144. else {
  45145. v0.triangleStart = tStart;
  45146. }
  45147. v0.triangleCount = tCount;
  45148. break;
  45149. }
  45150. }
  45151. };
  45152. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  45153. }, 0);
  45154. };
  45155. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  45156. if (triangleCount - deletedTriangles <= targetCount)
  45157. loop.breakLoop();
  45158. else {
  45159. iterationFunction(loop.index, function () {
  45160. loop.executeNext();
  45161. });
  45162. }
  45163. }, function () {
  45164. setTimeout(function () {
  45165. //reconstruct this part of the mesh
  45166. _this.reconstructMesh(submeshIndex);
  45167. successCallback();
  45168. }, 0);
  45169. });
  45170. };
  45171. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  45172. var _this = this;
  45173. this.vertices = [];
  45174. this.triangles = [];
  45175. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45176. var indices = this._mesh.getIndices();
  45177. var submesh = this._mesh.subMeshes[submeshIndex];
  45178. var findInVertices = function (positionToSearch) {
  45179. if (optimizeMesh) {
  45180. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  45181. if (_this.vertices[ii].position.equals(positionToSearch)) {
  45182. return _this.vertices[ii];
  45183. }
  45184. }
  45185. }
  45186. return null;
  45187. };
  45188. var vertexReferences = [];
  45189. var vertexInit = function (i) {
  45190. var offset = i + submesh.verticesStart;
  45191. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  45192. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  45193. vertex.originalOffsets.push(offset);
  45194. if (vertex.id === _this.vertices.length) {
  45195. _this.vertices.push(vertex);
  45196. }
  45197. vertexReferences.push(vertex.id);
  45198. };
  45199. //var totalVertices = mesh.getTotalVertices();
  45200. var totalVertices = submesh.verticesCount;
  45201. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  45202. var indicesInit = function (i) {
  45203. var offset = (submesh.indexStart / 3) + i;
  45204. var pos = (offset * 3);
  45205. var i0 = indices[pos + 0];
  45206. var i1 = indices[pos + 1];
  45207. var i2 = indices[pos + 2];
  45208. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  45209. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  45210. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  45211. var triangle = new DecimationTriangle([v0, v1, v2]);
  45212. triangle.originalOffset = pos;
  45213. _this.triangles.push(triangle);
  45214. };
  45215. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  45216. _this.init(callback);
  45217. });
  45218. });
  45219. };
  45220. QuadraticErrorSimplification.prototype.init = function (callback) {
  45221. var _this = this;
  45222. var triangleInit1 = function (i) {
  45223. var t = _this.triangles[i];
  45224. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  45225. for (var j = 0; j < 3; j++) {
  45226. 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))));
  45227. }
  45228. };
  45229. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  45230. var triangleInit2 = function (i) {
  45231. var t = _this.triangles[i];
  45232. for (var j = 0; j < 3; ++j) {
  45233. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  45234. }
  45235. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45236. };
  45237. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  45238. _this.initialized = true;
  45239. callback();
  45240. });
  45241. });
  45242. };
  45243. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  45244. var newTriangles = [];
  45245. var i;
  45246. for (i = 0; i < this.vertices.length; ++i) {
  45247. this.vertices[i].triangleCount = 0;
  45248. }
  45249. var t;
  45250. var j;
  45251. for (i = 0; i < this.triangles.length; ++i) {
  45252. if (!this.triangles[i].deleted) {
  45253. t = this.triangles[i];
  45254. for (j = 0; j < 3; ++j) {
  45255. t.vertices[j].triangleCount = 1;
  45256. }
  45257. newTriangles.push(t);
  45258. }
  45259. }
  45260. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  45261. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  45262. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  45263. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  45264. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45265. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45266. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45267. var vertexCount = 0;
  45268. for (i = 0; i < this.vertices.length; ++i) {
  45269. var vertex = this.vertices[i];
  45270. vertex.id = vertexCount;
  45271. if (vertex.triangleCount) {
  45272. vertex.originalOffsets.forEach(function (originalOffset) {
  45273. newPositionData.push(vertex.position.x);
  45274. newPositionData.push(vertex.position.y);
  45275. newPositionData.push(vertex.position.z);
  45276. newNormalData.push(normalData[originalOffset * 3]);
  45277. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  45278. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  45279. if (uvs && uvs.length) {
  45280. newUVsData.push(uvs[(originalOffset * 2)]);
  45281. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  45282. }
  45283. else if (colorsData && colorsData.length) {
  45284. newColorsData.push(colorsData[(originalOffset * 4)]);
  45285. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  45286. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  45287. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  45288. }
  45289. ++vertexCount;
  45290. });
  45291. }
  45292. }
  45293. var startingIndex = this._reconstructedMesh.getTotalIndices();
  45294. var startingVertex = this._reconstructedMesh.getTotalVertices();
  45295. var submeshesArray = this._reconstructedMesh.subMeshes;
  45296. this._reconstructedMesh.subMeshes = [];
  45297. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  45298. var originalIndices = this._mesh.getIndices();
  45299. for (i = 0; i < newTriangles.length; ++i) {
  45300. t = newTriangles[i]; //now get the new referencing point for each vertex
  45301. [0, 1, 2].forEach(function (idx) {
  45302. var id = originalIndices[t.originalOffset + idx];
  45303. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  45304. if (offset < 0)
  45305. offset = 0;
  45306. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  45307. });
  45308. }
  45309. //overwriting the old vertex buffers and indices.
  45310. this._reconstructedMesh.setIndices(newIndicesArray);
  45311. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  45312. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  45313. if (newUVsData.length > 0)
  45314. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  45315. if (newColorsData.length > 0)
  45316. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  45317. //create submesh
  45318. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  45319. if (submeshIndex > 0) {
  45320. this._reconstructedMesh.subMeshes = [];
  45321. submeshesArray.forEach(function (submesh) {
  45322. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  45323. });
  45324. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  45325. }
  45326. };
  45327. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  45328. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  45329. this._reconstructedMesh.material = this._mesh.material;
  45330. this._reconstructedMesh.parent = this._mesh.parent;
  45331. this._reconstructedMesh.isVisible = false;
  45332. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  45333. };
  45334. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  45335. for (var i = 0; i < vertex1.triangleCount; ++i) {
  45336. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  45337. if (t.deleted)
  45338. continue;
  45339. var s = this.references[vertex1.triangleStart + i].vertexId;
  45340. var v1 = t.vertices[(s + 1) % 3];
  45341. var v2 = t.vertices[(s + 2) % 3];
  45342. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  45343. deletedArray[i] = true;
  45344. delTr.push(t);
  45345. continue;
  45346. }
  45347. var d1 = v1.position.subtract(point);
  45348. d1 = d1.normalize();
  45349. var d2 = v2.position.subtract(point);
  45350. d2 = d2.normalize();
  45351. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  45352. return true;
  45353. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  45354. deletedArray[i] = false;
  45355. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  45356. return true;
  45357. }
  45358. return false;
  45359. };
  45360. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  45361. var newDeleted = deletedTriangles;
  45362. for (var i = 0; i < vertex.triangleCount; ++i) {
  45363. var ref = this.references[vertex.triangleStart + i];
  45364. var t = this.triangles[ref.triangleId];
  45365. if (t.deleted)
  45366. continue;
  45367. if (deletedArray[i] && t.deletePending) {
  45368. t.deleted = true;
  45369. newDeleted++;
  45370. continue;
  45371. }
  45372. t.vertices[ref.vertexId] = origVertex;
  45373. t.isDirty = true;
  45374. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  45375. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  45376. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  45377. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45378. this.references.push(ref);
  45379. }
  45380. return newDeleted;
  45381. };
  45382. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  45383. for (var i = 0; i < this.vertices.length; ++i) {
  45384. var vCount = [];
  45385. var vId = [];
  45386. var v = this.vertices[i];
  45387. var j;
  45388. for (j = 0; j < v.triangleCount; ++j) {
  45389. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  45390. for (var ii = 0; ii < 3; ii++) {
  45391. var ofs = 0;
  45392. var vv = triangle.vertices[ii];
  45393. while (ofs < vCount.length) {
  45394. if (vId[ofs] === vv.id)
  45395. break;
  45396. ++ofs;
  45397. }
  45398. if (ofs === vCount.length) {
  45399. vCount.push(1);
  45400. vId.push(vv.id);
  45401. }
  45402. else {
  45403. vCount[ofs]++;
  45404. }
  45405. }
  45406. }
  45407. for (j = 0; j < vCount.length; ++j) {
  45408. if (vCount[j] === 1) {
  45409. this.vertices[vId[j]].isBorder = true;
  45410. }
  45411. else {
  45412. this.vertices[vId[j]].isBorder = false;
  45413. }
  45414. }
  45415. }
  45416. };
  45417. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  45418. if (identifyBorders === void 0) { identifyBorders = false; }
  45419. var i;
  45420. if (!identifyBorders) {
  45421. var newTrianglesVector = [];
  45422. for (i = 0; i < this.triangles.length; ++i) {
  45423. if (!this.triangles[i].deleted) {
  45424. newTrianglesVector.push(this.triangles[i]);
  45425. }
  45426. }
  45427. this.triangles = newTrianglesVector;
  45428. }
  45429. for (i = 0; i < this.vertices.length; ++i) {
  45430. this.vertices[i].triangleCount = 0;
  45431. this.vertices[i].triangleStart = 0;
  45432. }
  45433. var t;
  45434. var j;
  45435. var v;
  45436. for (i = 0; i < this.triangles.length; ++i) {
  45437. t = this.triangles[i];
  45438. for (j = 0; j < 3; ++j) {
  45439. v = t.vertices[j];
  45440. v.triangleCount++;
  45441. }
  45442. }
  45443. var tStart = 0;
  45444. for (i = 0; i < this.vertices.length; ++i) {
  45445. this.vertices[i].triangleStart = tStart;
  45446. tStart += this.vertices[i].triangleCount;
  45447. this.vertices[i].triangleCount = 0;
  45448. }
  45449. var newReferences = new Array(this.triangles.length * 3);
  45450. for (i = 0; i < this.triangles.length; ++i) {
  45451. t = this.triangles[i];
  45452. for (j = 0; j < 3; ++j) {
  45453. v = t.vertices[j];
  45454. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  45455. v.triangleCount++;
  45456. }
  45457. }
  45458. this.references = newReferences;
  45459. if (identifyBorders) {
  45460. this.identifyBorder();
  45461. }
  45462. };
  45463. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  45464. var x = point.x;
  45465. var y = point.y;
  45466. var z = point.z;
  45467. 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
  45468. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  45469. };
  45470. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  45471. var q = vertex1.q.add(vertex2.q);
  45472. var border = vertex1.isBorder && vertex2.isBorder;
  45473. var error = 0;
  45474. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  45475. if (qDet !== 0 && !border) {
  45476. if (!pointResult) {
  45477. pointResult = BABYLON.Vector3.Zero();
  45478. }
  45479. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  45480. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  45481. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  45482. error = this.vertexError(q, pointResult);
  45483. }
  45484. else {
  45485. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  45486. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  45487. var error1 = this.vertexError(q, vertex1.position);
  45488. var error2 = this.vertexError(q, vertex2.position);
  45489. var error3 = this.vertexError(q, p3);
  45490. error = Math.min(error1, error2, error3);
  45491. if (error === error1) {
  45492. if (pointResult) {
  45493. pointResult.copyFrom(vertex1.position);
  45494. }
  45495. }
  45496. else if (error === error2) {
  45497. if (pointResult) {
  45498. pointResult.copyFrom(vertex2.position);
  45499. }
  45500. }
  45501. else {
  45502. if (pointResult) {
  45503. pointResult.copyFrom(p3);
  45504. }
  45505. }
  45506. }
  45507. return error;
  45508. };
  45509. return QuadraticErrorSimplification;
  45510. }());
  45511. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  45512. })(BABYLON || (BABYLON = {}));
  45513. //# sourceMappingURL=babylon.meshSimplification.js.map
  45514. var BABYLON;
  45515. (function (BABYLON) {
  45516. var serializedGeometries = [];
  45517. var serializeGeometry = function (geometry, serializationGeometries) {
  45518. if (serializedGeometries[geometry.id]) {
  45519. return;
  45520. }
  45521. if (geometry.doNotSerialize) {
  45522. return;
  45523. }
  45524. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  45525. serializationGeometries.boxes.push(geometry.serialize());
  45526. }
  45527. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  45528. serializationGeometries.spheres.push(geometry.serialize());
  45529. }
  45530. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  45531. serializationGeometries.cylinders.push(geometry.serialize());
  45532. }
  45533. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  45534. serializationGeometries.toruses.push(geometry.serialize());
  45535. }
  45536. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  45537. serializationGeometries.grounds.push(geometry.serialize());
  45538. }
  45539. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  45540. serializationGeometries.planes.push(geometry.serialize());
  45541. }
  45542. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  45543. serializationGeometries.torusKnots.push(geometry.serialize());
  45544. }
  45545. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  45546. throw new Error("Unknown primitive type");
  45547. }
  45548. else {
  45549. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  45550. }
  45551. serializedGeometries[geometry.id] = true;
  45552. };
  45553. var serializeMesh = function (mesh, serializationScene) {
  45554. var serializationObject = {};
  45555. serializationObject.name = mesh.name;
  45556. serializationObject.id = mesh.id;
  45557. if (BABYLON.Tags.HasTags(mesh)) {
  45558. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  45559. }
  45560. serializationObject.position = mesh.position.asArray();
  45561. if (mesh.rotationQuaternion) {
  45562. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  45563. }
  45564. else if (mesh.rotation) {
  45565. serializationObject.rotation = mesh.rotation.asArray();
  45566. }
  45567. serializationObject.scaling = mesh.scaling.asArray();
  45568. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  45569. serializationObject.isEnabled = mesh.isEnabled();
  45570. serializationObject.isVisible = mesh.isVisible;
  45571. serializationObject.infiniteDistance = mesh.infiniteDistance;
  45572. serializationObject.pickable = mesh.isPickable;
  45573. serializationObject.receiveShadows = mesh.receiveShadows;
  45574. serializationObject.billboardMode = mesh.billboardMode;
  45575. serializationObject.visibility = mesh.visibility;
  45576. serializationObject.checkCollisions = mesh.checkCollisions;
  45577. serializationObject.isBlocker = mesh.isBlocker;
  45578. // Parent
  45579. if (mesh.parent) {
  45580. serializationObject.parentId = mesh.parent.id;
  45581. }
  45582. // Geometry
  45583. var geometry = mesh._geometry;
  45584. if (geometry) {
  45585. var geometryId = geometry.id;
  45586. serializationObject.geometryId = geometryId;
  45587. if (!mesh.getScene().getGeometryByID(geometryId)) {
  45588. // 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
  45589. serializeGeometry(geometry, serializationScene.geometries);
  45590. }
  45591. // SubMeshes
  45592. serializationObject.subMeshes = [];
  45593. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45594. var subMesh = mesh.subMeshes[subIndex];
  45595. serializationObject.subMeshes.push({
  45596. materialIndex: subMesh.materialIndex,
  45597. verticesStart: subMesh.verticesStart,
  45598. verticesCount: subMesh.verticesCount,
  45599. indexStart: subMesh.indexStart,
  45600. indexCount: subMesh.indexCount
  45601. });
  45602. }
  45603. }
  45604. // Material
  45605. if (mesh.material) {
  45606. serializationObject.materialId = mesh.material.id;
  45607. }
  45608. else {
  45609. mesh.material = null;
  45610. }
  45611. // Skeleton
  45612. if (mesh.skeleton) {
  45613. serializationObject.skeletonId = mesh.skeleton.id;
  45614. }
  45615. // Physics
  45616. //TODO implement correct serialization for physics impostors.
  45617. if (mesh.getPhysicsImpostor()) {
  45618. serializationObject.physicsMass = mesh.getPhysicsMass();
  45619. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  45620. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  45621. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  45622. }
  45623. // Metadata
  45624. if (mesh.metadata) {
  45625. serializationObject.metadata = mesh.metadata;
  45626. }
  45627. // Instances
  45628. serializationObject.instances = [];
  45629. for (var index = 0; index < mesh.instances.length; index++) {
  45630. var instance = mesh.instances[index];
  45631. var serializationInstance = {
  45632. name: instance.name,
  45633. position: instance.position.asArray(),
  45634. scaling: instance.scaling.asArray()
  45635. };
  45636. if (instance.rotationQuaternion) {
  45637. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  45638. }
  45639. else if (instance.rotation) {
  45640. serializationInstance.rotation = instance.rotation.asArray();
  45641. }
  45642. serializationObject.instances.push(serializationInstance);
  45643. // Animations
  45644. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  45645. serializationInstance.ranges = instance.serializeAnimationRanges();
  45646. }
  45647. // Animations
  45648. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  45649. serializationObject.ranges = mesh.serializeAnimationRanges();
  45650. // Layer mask
  45651. serializationObject.layerMask = mesh.layerMask;
  45652. // Alpha
  45653. serializationObject.alphaIndex = mesh.alphaIndex;
  45654. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  45655. // Overlay
  45656. serializationObject.overlayAlpha = mesh.overlayAlpha;
  45657. serializationObject.overlayColor = mesh.overlayColor.asArray();
  45658. serializationObject.renderOverlay = mesh.renderOverlay;
  45659. // Fog
  45660. serializationObject.applyFog = mesh.applyFog;
  45661. // Action Manager
  45662. if (mesh.actionManager) {
  45663. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  45664. }
  45665. return serializationObject;
  45666. };
  45667. var finalizeSingleMesh = function (mesh, serializationObject) {
  45668. //only works if the mesh is already loaded
  45669. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45670. //serialize material
  45671. if (mesh.material) {
  45672. if (mesh.material instanceof BABYLON.StandardMaterial) {
  45673. serializationObject.materials = serializationObject.materials || [];
  45674. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45675. serializationObject.materials.push(mesh.material.serialize());
  45676. }
  45677. }
  45678. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  45679. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  45680. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45681. serializationObject.multiMaterials.push(mesh.material.serialize());
  45682. }
  45683. }
  45684. }
  45685. //serialize geometry
  45686. var geometry = mesh._geometry;
  45687. if (geometry) {
  45688. if (!serializationObject.geometries) {
  45689. serializationObject.geometries = {};
  45690. serializationObject.geometries.boxes = [];
  45691. serializationObject.geometries.spheres = [];
  45692. serializationObject.geometries.cylinders = [];
  45693. serializationObject.geometries.toruses = [];
  45694. serializationObject.geometries.grounds = [];
  45695. serializationObject.geometries.planes = [];
  45696. serializationObject.geometries.torusKnots = [];
  45697. serializationObject.geometries.vertexData = [];
  45698. }
  45699. serializeGeometry(geometry, serializationObject.geometries);
  45700. }
  45701. // Skeletons
  45702. if (mesh.skeleton) {
  45703. serializationObject.skeletons = serializationObject.skeletons || [];
  45704. serializationObject.skeletons.push(mesh.skeleton.serialize());
  45705. }
  45706. //serialize the actual mesh
  45707. serializationObject.meshes = serializationObject.meshes || [];
  45708. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45709. }
  45710. };
  45711. var SceneSerializer = (function () {
  45712. function SceneSerializer() {
  45713. }
  45714. SceneSerializer.ClearCache = function () {
  45715. serializedGeometries = [];
  45716. };
  45717. SceneSerializer.Serialize = function (scene) {
  45718. var serializationObject = {};
  45719. // Scene
  45720. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  45721. serializationObject.autoClear = scene.autoClear;
  45722. serializationObject.clearColor = scene.clearColor.asArray();
  45723. serializationObject.ambientColor = scene.ambientColor.asArray();
  45724. serializationObject.gravity = scene.gravity.asArray();
  45725. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  45726. serializationObject.workerCollisions = scene.workerCollisions;
  45727. // Fog
  45728. if (scene.fogMode && scene.fogMode !== 0) {
  45729. serializationObject.fogMode = scene.fogMode;
  45730. serializationObject.fogColor = scene.fogColor.asArray();
  45731. serializationObject.fogStart = scene.fogStart;
  45732. serializationObject.fogEnd = scene.fogEnd;
  45733. serializationObject.fogDensity = scene.fogDensity;
  45734. }
  45735. //Physics
  45736. if (scene.isPhysicsEnabled()) {
  45737. serializationObject.physicsEnabled = true;
  45738. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  45739. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  45740. }
  45741. // Metadata
  45742. if (scene.metadata) {
  45743. serializationObject.metadata = scene.metadata;
  45744. }
  45745. // Lights
  45746. serializationObject.lights = [];
  45747. var index;
  45748. var light;
  45749. for (index = 0; index < scene.lights.length; index++) {
  45750. light = scene.lights[index];
  45751. if (!light.doNotSerialize) {
  45752. serializationObject.lights.push(light.serialize());
  45753. }
  45754. }
  45755. // Cameras
  45756. serializationObject.cameras = [];
  45757. for (index = 0; index < scene.cameras.length; index++) {
  45758. var camera = scene.cameras[index];
  45759. if (!camera.doNotSerialize) {
  45760. serializationObject.cameras.push(camera.serialize());
  45761. }
  45762. }
  45763. if (scene.activeCamera) {
  45764. serializationObject.activeCameraID = scene.activeCamera.id;
  45765. }
  45766. // Animations
  45767. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  45768. // Materials
  45769. serializationObject.materials = [];
  45770. serializationObject.multiMaterials = [];
  45771. var material;
  45772. for (index = 0; index < scene.materials.length; index++) {
  45773. material = scene.materials[index];
  45774. if (!material.doNotSerialize) {
  45775. serializationObject.materials.push(material.serialize());
  45776. }
  45777. }
  45778. // MultiMaterials
  45779. serializationObject.multiMaterials = [];
  45780. for (index = 0; index < scene.multiMaterials.length; index++) {
  45781. var multiMaterial = scene.multiMaterials[index];
  45782. serializationObject.multiMaterials.push(multiMaterial.serialize());
  45783. }
  45784. // Skeletons
  45785. serializationObject.skeletons = [];
  45786. for (index = 0; index < scene.skeletons.length; index++) {
  45787. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  45788. }
  45789. // Geometries
  45790. serializationObject.geometries = {};
  45791. serializationObject.geometries.boxes = [];
  45792. serializationObject.geometries.spheres = [];
  45793. serializationObject.geometries.cylinders = [];
  45794. serializationObject.geometries.toruses = [];
  45795. serializationObject.geometries.grounds = [];
  45796. serializationObject.geometries.planes = [];
  45797. serializationObject.geometries.torusKnots = [];
  45798. serializationObject.geometries.vertexData = [];
  45799. serializedGeometries = [];
  45800. var geometries = scene.getGeometries();
  45801. for (index = 0; index < geometries.length; index++) {
  45802. var geometry = geometries[index];
  45803. if (geometry.isReady()) {
  45804. serializeGeometry(geometry, serializationObject.geometries);
  45805. }
  45806. }
  45807. // Meshes
  45808. serializationObject.meshes = [];
  45809. for (index = 0; index < scene.meshes.length; index++) {
  45810. var abstractMesh = scene.meshes[index];
  45811. if (abstractMesh instanceof BABYLON.Mesh) {
  45812. var mesh = abstractMesh;
  45813. if (!mesh.doNotSerialize) {
  45814. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45815. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45816. }
  45817. }
  45818. }
  45819. }
  45820. // Particles Systems
  45821. serializationObject.particleSystems = [];
  45822. for (index = 0; index < scene.particleSystems.length; index++) {
  45823. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  45824. }
  45825. // Lens flares
  45826. serializationObject.lensFlareSystems = [];
  45827. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  45828. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  45829. }
  45830. // Shadows
  45831. serializationObject.shadowGenerators = [];
  45832. for (index = 0; index < scene.lights.length; index++) {
  45833. light = scene.lights[index];
  45834. var shadowGenerator = light.getShadowGenerator();
  45835. // Only support serialization for official generator so far.
  45836. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  45837. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  45838. }
  45839. }
  45840. // Action Manager
  45841. if (scene.actionManager) {
  45842. serializationObject.actions = scene.actionManager.serialize("scene");
  45843. }
  45844. // Audio
  45845. serializationObject.sounds = [];
  45846. for (index = 0; index < scene.soundTracks.length; index++) {
  45847. var soundtrack = scene.soundTracks[index];
  45848. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  45849. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  45850. }
  45851. }
  45852. return serializationObject;
  45853. };
  45854. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  45855. if (withParents === void 0) { withParents = false; }
  45856. if (withChildren === void 0) { withChildren = false; }
  45857. var serializationObject = {};
  45858. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  45859. if (withParents || withChildren) {
  45860. //deliberate for loop! not for each, appended should be processed as well.
  45861. for (var i = 0; i < toSerialize.length; ++i) {
  45862. if (withChildren) {
  45863. toSerialize[i].getDescendants().forEach(function (node) {
  45864. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  45865. toSerialize.push(node);
  45866. }
  45867. });
  45868. }
  45869. //make sure the array doesn't contain the object already
  45870. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  45871. toSerialize.push(toSerialize[i].parent);
  45872. }
  45873. }
  45874. }
  45875. toSerialize.forEach(function (mesh) {
  45876. finalizeSingleMesh(mesh, serializationObject);
  45877. });
  45878. return serializationObject;
  45879. };
  45880. return SceneSerializer;
  45881. }());
  45882. BABYLON.SceneSerializer = SceneSerializer;
  45883. })(BABYLON || (BABYLON = {}));
  45884. //# sourceMappingURL=babylon.sceneSerializer.js.map
  45885. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  45886. // Huge respect for a such great lib.
  45887. // Earcut license:
  45888. // Copyright (c) 2016, Mapbox
  45889. //
  45890. // Permission to use, copy, modify, and/or distribute this software for any purpose
  45891. // with or without fee is hereby granted, provided that the above copyright notice
  45892. // and this permission notice appear in all copies.
  45893. //
  45894. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  45895. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  45896. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  45897. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  45898. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  45899. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  45900. // THIS SOFTWARE.
  45901. var Earcut;
  45902. (function (Earcut) {
  45903. /**
  45904. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  45905. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  45906. * @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).
  45907. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  45908. */
  45909. function earcut(data, holeIndices, dim) {
  45910. dim = dim || 2;
  45911. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  45912. if (!outerNode)
  45913. return triangles;
  45914. var minX, minY, maxX, maxY, x, y, size;
  45915. if (hasHoles)
  45916. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  45917. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  45918. if (data.length > 80 * dim) {
  45919. minX = maxX = data[0];
  45920. minY = maxY = data[1];
  45921. for (var i = dim; i < outerLen; i += dim) {
  45922. x = data[i];
  45923. y = data[i + 1];
  45924. if (x < minX)
  45925. minX = x;
  45926. if (y < minY)
  45927. minY = y;
  45928. if (x > maxX)
  45929. maxX = x;
  45930. if (y > maxY)
  45931. maxY = y;
  45932. }
  45933. // minX, minY and size are later used to transform coords into integers for z-order calculation
  45934. size = Math.max(maxX - minX, maxY - minY);
  45935. }
  45936. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  45937. return triangles;
  45938. }
  45939. Earcut.earcut = earcut;
  45940. // create a circular doubly linked list from polygon points in the specified winding order
  45941. function linkedList(data, start, end, dim, clockwise) {
  45942. var i, last;
  45943. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  45944. for (i = start; i < end; i += dim)
  45945. last = insertNode(i, data[i], data[i + 1], last);
  45946. }
  45947. else {
  45948. for (i = end - dim; i >= start; i -= dim)
  45949. last = insertNode(i, data[i], data[i + 1], last);
  45950. }
  45951. if (last && equals(last, last.next)) {
  45952. removeNode(last);
  45953. last = last.next;
  45954. }
  45955. return last;
  45956. }
  45957. // eliminate colinear or duplicate points
  45958. function filterPoints(start, end) {
  45959. if (!start)
  45960. return start;
  45961. if (!end)
  45962. end = start;
  45963. var p = start, again;
  45964. do {
  45965. again = false;
  45966. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  45967. removeNode(p);
  45968. p = end = p.prev;
  45969. if (p === p.next)
  45970. return null;
  45971. again = true;
  45972. }
  45973. else {
  45974. p = p.next;
  45975. }
  45976. } while (again || p !== end);
  45977. return end;
  45978. }
  45979. // main ear slicing loop which triangulates a polygon (given as a linked list)
  45980. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  45981. if (!ear)
  45982. return;
  45983. // interlink polygon nodes in z-order
  45984. if (!pass && size)
  45985. indexCurve(ear, minX, minY, size);
  45986. var stop = ear, prev, next;
  45987. // iterate through ears, slicing them one by one
  45988. while (ear.prev !== ear.next) {
  45989. prev = ear.prev;
  45990. next = ear.next;
  45991. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  45992. // cut off the triangle
  45993. triangles.push(prev.i / dim);
  45994. triangles.push(ear.i / dim);
  45995. triangles.push(next.i / dim);
  45996. removeNode(ear);
  45997. // skipping the next vertice leads to less sliver triangles
  45998. ear = next.next;
  45999. stop = next.next;
  46000. continue;
  46001. }
  46002. ear = next;
  46003. // if we looped through the whole remaining polygon and can't find any more ears
  46004. if (ear === stop) {
  46005. // try filtering points and slicing again
  46006. if (!pass) {
  46007. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  46008. }
  46009. else if (pass === 1) {
  46010. ear = cureLocalIntersections(ear, triangles, dim);
  46011. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  46012. }
  46013. else if (pass === 2) {
  46014. splitEarcut(ear, triangles, dim, minX, minY, size);
  46015. }
  46016. break;
  46017. }
  46018. }
  46019. }
  46020. // check whether a polygon node forms a valid ear with adjacent nodes
  46021. function isEar(ear) {
  46022. var a = ear.prev, b = ear, c = ear.next;
  46023. if (area(a, b, c) >= 0)
  46024. return false; // reflex, can't be an ear
  46025. // now make sure we don't have other points inside the potential ear
  46026. var p = ear.next.next;
  46027. while (p !== ear.prev) {
  46028. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46029. area(p.prev, p, p.next) >= 0)
  46030. return false;
  46031. p = p.next;
  46032. }
  46033. return true;
  46034. }
  46035. function isEarHashed(ear, minX, minY, size) {
  46036. var a = ear.prev, b = ear, c = ear.next;
  46037. if (area(a, b, c) >= 0)
  46038. return false; // reflex, can't be an ear
  46039. // triangle bbox; min & max are calculated like this for speed
  46040. 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);
  46041. // z-order range for the current triangle bbox;
  46042. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  46043. // first look for points inside the triangle in increasing z-order
  46044. var p = ear.nextZ;
  46045. while (p && p.z <= maxZ) {
  46046. if (p !== ear.prev &&
  46047. p !== ear.next &&
  46048. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46049. area(p.prev, p, p.next) >= 0)
  46050. return false;
  46051. p = p.nextZ;
  46052. }
  46053. // then look for points in decreasing z-order
  46054. p = ear.prevZ;
  46055. while (p && p.z >= minZ) {
  46056. if (p !== ear.prev &&
  46057. p !== ear.next &&
  46058. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46059. area(p.prev, p, p.next) >= 0)
  46060. return false;
  46061. p = p.prevZ;
  46062. }
  46063. return true;
  46064. }
  46065. // go through all polygon nodes and cure small local self-intersections
  46066. function cureLocalIntersections(start, triangles, dim) {
  46067. var p = start;
  46068. do {
  46069. var a = p.prev, b = p.next.next;
  46070. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  46071. triangles.push(a.i / dim);
  46072. triangles.push(p.i / dim);
  46073. triangles.push(b.i / dim);
  46074. // remove two nodes involved
  46075. removeNode(p);
  46076. removeNode(p.next);
  46077. p = start = b;
  46078. }
  46079. p = p.next;
  46080. } while (p !== start);
  46081. return p;
  46082. }
  46083. // try splitting polygon into two and triangulate them independently
  46084. function splitEarcut(start, triangles, dim, minX, minY, size) {
  46085. // look for a valid diagonal that divides the polygon into two
  46086. var a = start;
  46087. do {
  46088. var b = a.next.next;
  46089. while (b !== a.prev) {
  46090. if (a.i !== b.i && isValidDiagonal(a, b)) {
  46091. // split the polygon in two by the diagonal
  46092. var c = splitPolygon(a, b);
  46093. // filter colinear points around the cuts
  46094. a = filterPoints(a, a.next);
  46095. c = filterPoints(c, c.next);
  46096. // run earcut on each half
  46097. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  46098. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  46099. return;
  46100. }
  46101. b = b.next;
  46102. }
  46103. a = a.next;
  46104. } while (a !== start);
  46105. }
  46106. // link every hole into the outer loop, producing a single-ring polygon without holes
  46107. function eliminateHoles(data, holeIndices, outerNode, dim) {
  46108. var queue = [], i, len, start, end, list;
  46109. for (i = 0, len = holeIndices.length; i < len; i++) {
  46110. start = holeIndices[i] * dim;
  46111. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46112. list = linkedList(data, start, end, dim, false);
  46113. if (list === list.next)
  46114. list.steiner = true;
  46115. queue.push(getLeftmost(list));
  46116. }
  46117. queue.sort(compareX);
  46118. // process holes from left to right
  46119. for (i = 0; i < queue.length; i++) {
  46120. eliminateHole(queue[i], outerNode);
  46121. outerNode = filterPoints(outerNode, outerNode.next);
  46122. }
  46123. return outerNode;
  46124. }
  46125. function compareX(a, b) {
  46126. return a.x - b.x;
  46127. }
  46128. // find a bridge between vertices that connects hole with an outer ring and and link it
  46129. function eliminateHole(hole, outerNode) {
  46130. outerNode = findHoleBridge(hole, outerNode);
  46131. if (outerNode) {
  46132. var b = splitPolygon(outerNode, hole);
  46133. filterPoints(b, b.next);
  46134. }
  46135. }
  46136. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  46137. function findHoleBridge(hole, outerNode) {
  46138. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  46139. // find a segment intersected by a ray from the hole's leftmost point to the left;
  46140. // segment's endpoint with lesser x will be potential connection point
  46141. do {
  46142. if (hy <= p.y && hy >= p.next.y) {
  46143. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  46144. if (x <= hx && x > qx) {
  46145. qx = x;
  46146. if (x === hx) {
  46147. if (hy === p.y)
  46148. return p;
  46149. if (hy === p.next.y)
  46150. return p.next;
  46151. }
  46152. m = p.x < p.next.x ? p : p.next;
  46153. }
  46154. }
  46155. p = p.next;
  46156. } while (p !== outerNode);
  46157. if (!m)
  46158. return null;
  46159. if (hx === qx)
  46160. return m.prev; // hole touches outer segment; pick lower endpoint
  46161. // look for points inside the triangle of hole point, segment intersection and endpoint;
  46162. // if there are no points found, we have a valid connection;
  46163. // otherwise choose the point of the minimum angle with the ray as connection point
  46164. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  46165. p = m.next;
  46166. while (p !== stop) {
  46167. if (hx >= p.x &&
  46168. p.x >= mx &&
  46169. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  46170. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  46171. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  46172. m = p;
  46173. tanMin = tan;
  46174. }
  46175. }
  46176. p = p.next;
  46177. }
  46178. return m;
  46179. }
  46180. // interlink polygon nodes in z-order
  46181. function indexCurve(start, minX, minY, size) {
  46182. var p = start;
  46183. do {
  46184. if (p.z === null)
  46185. p.z = zOrder(p.x, p.y, minX, minY, size);
  46186. p.prevZ = p.prev;
  46187. p.nextZ = p.next;
  46188. p = p.next;
  46189. } while (p !== start);
  46190. p.prevZ.nextZ = null;
  46191. p.prevZ = null;
  46192. sortLinked(p);
  46193. }
  46194. // Simon Tatham's linked list merge sort algorithm
  46195. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  46196. function sortLinked(list) {
  46197. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  46198. do {
  46199. p = list;
  46200. list = null;
  46201. tail = null;
  46202. numMerges = 0;
  46203. while (p) {
  46204. numMerges++;
  46205. q = p;
  46206. pSize = 0;
  46207. for (i = 0; i < inSize; i++) {
  46208. pSize++;
  46209. q = q.nextZ;
  46210. if (!q)
  46211. break;
  46212. }
  46213. qSize = inSize;
  46214. while (pSize > 0 || (qSize > 0 && q)) {
  46215. if (pSize === 0) {
  46216. e = q;
  46217. q = q.nextZ;
  46218. qSize--;
  46219. }
  46220. else if (qSize === 0 || !q) {
  46221. e = p;
  46222. p = p.nextZ;
  46223. pSize--;
  46224. }
  46225. else if (p.z <= q.z) {
  46226. e = p;
  46227. p = p.nextZ;
  46228. pSize--;
  46229. }
  46230. else {
  46231. e = q;
  46232. q = q.nextZ;
  46233. qSize--;
  46234. }
  46235. if (tail)
  46236. tail.nextZ = e;
  46237. else
  46238. list = e;
  46239. e.prevZ = tail;
  46240. tail = e;
  46241. }
  46242. p = q;
  46243. }
  46244. tail.nextZ = null;
  46245. inSize *= 2;
  46246. } while (numMerges > 1);
  46247. return list;
  46248. }
  46249. // z-order of a point given coords and size of the data bounding box
  46250. function zOrder(x, y, minX, minY, size) {
  46251. // coords are transformed into non-negative 15-bit integer range
  46252. x = 32767 * (x - minX) / size;
  46253. y = 32767 * (y - minY) / size;
  46254. x = (x | (x << 8)) & 0x00FF00FF;
  46255. x = (x | (x << 4)) & 0x0F0F0F0F;
  46256. x = (x | (x << 2)) & 0x33333333;
  46257. x = (x | (x << 1)) & 0x55555555;
  46258. y = (y | (y << 8)) & 0x00FF00FF;
  46259. y = (y | (y << 4)) & 0x0F0F0F0F;
  46260. y = (y | (y << 2)) & 0x33333333;
  46261. y = (y | (y << 1)) & 0x55555555;
  46262. return x | (y << 1);
  46263. }
  46264. // find the leftmost node of a polygon ring
  46265. function getLeftmost(start) {
  46266. var p = start, leftmost = start;
  46267. do {
  46268. if (p.x < leftmost.x)
  46269. leftmost = p;
  46270. p = p.next;
  46271. } while (p !== start);
  46272. return leftmost;
  46273. }
  46274. // check if a point lies within a convex triangle
  46275. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  46276. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  46277. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  46278. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  46279. }
  46280. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  46281. function isValidDiagonal(a, b) {
  46282. return a.next.i !== b.i &&
  46283. a.prev.i !== b.i &&
  46284. !intersectsPolygon(a, b) &&
  46285. locallyInside(a, b) &&
  46286. locallyInside(b, a) &&
  46287. middleInside(a, b);
  46288. }
  46289. // signed area of a triangle
  46290. function area(p, q, r) {
  46291. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  46292. }
  46293. // check if two points are equal
  46294. function equals(p1, p2) {
  46295. return p1.x === p2.x && p1.y === p2.y;
  46296. }
  46297. // check if two segments intersect
  46298. function intersects(p1, q1, p2, q2) {
  46299. if ((equals(p1, q1) && equals(p2, q2)) ||
  46300. (equals(p1, q2) && equals(p2, q1)))
  46301. return true;
  46302. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  46303. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  46304. }
  46305. // check if a polygon diagonal intersects any polygon segments
  46306. function intersectsPolygon(a, b) {
  46307. var p = a;
  46308. do {
  46309. if (p.i !== a.i &&
  46310. p.next.i !== a.i &&
  46311. p.i !== b.i &&
  46312. p.next.i !== b.i &&
  46313. intersects(p, p.next, a, b))
  46314. return true;
  46315. p = p.next;
  46316. } while (p !== a);
  46317. return false;
  46318. }
  46319. // check if a polygon diagonal is locally inside the polygon
  46320. function locallyInside(a, b) {
  46321. return area(a.prev, a, a.next) < 0
  46322. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  46323. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  46324. }
  46325. // check if the middle point of a polygon diagonal is inside the polygon
  46326. function middleInside(a, b) {
  46327. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  46328. do {
  46329. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  46330. inside = !inside;
  46331. p = p.next;
  46332. } while (p !== a);
  46333. return inside;
  46334. }
  46335. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  46336. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  46337. function splitPolygon(a, b) {
  46338. 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;
  46339. a.next = b;
  46340. b.prev = a;
  46341. a2.next = an;
  46342. an.prev = a2;
  46343. b2.next = a2;
  46344. a2.prev = b2;
  46345. bp.next = b2;
  46346. b2.prev = bp;
  46347. return b2;
  46348. }
  46349. // create a node and optionally link it with previous one (in a circular doubly linked list)
  46350. function insertNode(i, x, y, last) {
  46351. var p = new Node(i, x, y);
  46352. if (!last) {
  46353. p.prev = p;
  46354. p.next = p;
  46355. }
  46356. else {
  46357. p.next = last.next;
  46358. p.prev = last;
  46359. last.next.prev = p;
  46360. last.next = p;
  46361. }
  46362. return p;
  46363. }
  46364. function removeNode(p) {
  46365. p.next.prev = p.prev;
  46366. p.prev.next = p.next;
  46367. if (p.prevZ)
  46368. p.prevZ.nextZ = p.nextZ;
  46369. if (p.nextZ)
  46370. p.nextZ.prevZ = p.prevZ;
  46371. }
  46372. function Node(i, x, y) {
  46373. // vertice index in coordinates array
  46374. this.i = i;
  46375. // vertex coordinates
  46376. this.x = x;
  46377. this.y = y;
  46378. // previous and next vertice nodes in a polygon ring
  46379. this.prev = null;
  46380. this.next = null;
  46381. // z-order curve value
  46382. this.z = null;
  46383. // previous and next nodes in z-order
  46384. this.prevZ = null;
  46385. this.nextZ = null;
  46386. // indicates whether this is a steiner point
  46387. this.steiner = false;
  46388. }
  46389. /**
  46390. * return a percentage difference between the polygon area and its triangulation area;
  46391. * used to verify correctness of triangulation
  46392. */
  46393. function deviation(data, holeIndices, dim, triangles) {
  46394. var hasHoles = holeIndices && holeIndices.length;
  46395. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  46396. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  46397. if (hasHoles) {
  46398. for (var i = 0, len = holeIndices.length; i < len; i++) {
  46399. var start = holeIndices[i] * dim;
  46400. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46401. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  46402. }
  46403. }
  46404. var trianglesArea = 0;
  46405. for (i = 0; i < triangles.length; i += 3) {
  46406. var a = triangles[i] * dim;
  46407. var b = triangles[i + 1] * dim;
  46408. var c = triangles[i + 2] * dim;
  46409. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  46410. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  46411. }
  46412. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  46413. }
  46414. Earcut.deviation = deviation;
  46415. ;
  46416. function signedArea(data, start, end, dim) {
  46417. var sum = 0;
  46418. for (var i = start, j = end - dim; i < end; i += dim) {
  46419. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  46420. j = i;
  46421. }
  46422. return sum;
  46423. }
  46424. /**
  46425. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  46426. */
  46427. function flatten(data) {
  46428. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  46429. for (var i = 0; i < data.length; i++) {
  46430. for (var j = 0; j < data[i].length; j++) {
  46431. for (var d = 0; d < dim; d++)
  46432. result.vertices.push(data[i][j][d]);
  46433. }
  46434. if (i > 0) {
  46435. holeIndex += data[i - 1].length;
  46436. result.holes.push(holeIndex);
  46437. }
  46438. }
  46439. return result;
  46440. }
  46441. Earcut.flatten = flatten;
  46442. ;
  46443. })(Earcut || (Earcut = {}));
  46444. //# sourceMappingURL=babylon.earcut.js.map
  46445. var BABYLON;
  46446. (function (BABYLON) {
  46447. // Unique ID when we import meshes from Babylon to CSG
  46448. var currentCSGMeshId = 0;
  46449. // # class Vertex
  46450. // Represents a vertex of a polygon. Use your own vertex class instead of this
  46451. // one to provide additional features like texture coordinates and vertex
  46452. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  46453. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  46454. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  46455. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  46456. // is not used anywhere else.
  46457. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  46458. var Vertex = (function () {
  46459. function Vertex(pos, normal, uv) {
  46460. this.pos = pos;
  46461. this.normal = normal;
  46462. this.uv = uv;
  46463. }
  46464. Vertex.prototype.clone = function () {
  46465. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  46466. };
  46467. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  46468. // orientation of a polygon is flipped.
  46469. Vertex.prototype.flip = function () {
  46470. this.normal = this.normal.scale(-1);
  46471. };
  46472. // Create a new vertex between this vertex and `other` by linearly
  46473. // interpolating all properties using a parameter of `t`. Subclasses should
  46474. // override this to interpolate additional properties.
  46475. Vertex.prototype.interpolate = function (other, t) {
  46476. 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));
  46477. };
  46478. return Vertex;
  46479. }());
  46480. // # class Plane
  46481. // Represents a plane in 3D space.
  46482. var Plane = (function () {
  46483. function Plane(normal, w) {
  46484. this.normal = normal;
  46485. this.w = w;
  46486. }
  46487. Plane.FromPoints = function (a, b, c) {
  46488. var v0 = c.subtract(a);
  46489. var v1 = b.subtract(a);
  46490. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  46491. return null;
  46492. }
  46493. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  46494. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  46495. };
  46496. Plane.prototype.clone = function () {
  46497. return new Plane(this.normal.clone(), this.w);
  46498. };
  46499. Plane.prototype.flip = function () {
  46500. this.normal.scaleInPlace(-1);
  46501. this.w = -this.w;
  46502. };
  46503. // Split `polygon` by this plane if needed, then put the polygon or polygon
  46504. // fragments in the appropriate lists. Coplanar polygons go into either
  46505. // `coplanarFront` or `coplanarBack` depending on their orientation with
  46506. // respect to this plane. Polygons in front or in back of this plane go into
  46507. // either `front` or `back`.
  46508. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  46509. var COPLANAR = 0;
  46510. var FRONT = 1;
  46511. var BACK = 2;
  46512. var SPANNING = 3;
  46513. // Classify each point as well as the entire polygon into one of the above
  46514. // four classes.
  46515. var polygonType = 0;
  46516. var types = [];
  46517. var i;
  46518. var t;
  46519. for (i = 0; i < polygon.vertices.length; i++) {
  46520. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  46521. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  46522. polygonType |= type;
  46523. types.push(type);
  46524. }
  46525. // Put the polygon in the correct list, splitting it when necessary.
  46526. switch (polygonType) {
  46527. case COPLANAR:
  46528. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  46529. break;
  46530. case FRONT:
  46531. front.push(polygon);
  46532. break;
  46533. case BACK:
  46534. back.push(polygon);
  46535. break;
  46536. case SPANNING:
  46537. var f = [], b = [];
  46538. for (i = 0; i < polygon.vertices.length; i++) {
  46539. var j = (i + 1) % polygon.vertices.length;
  46540. var ti = types[i], tj = types[j];
  46541. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  46542. if (ti !== BACK)
  46543. f.push(vi);
  46544. if (ti !== FRONT)
  46545. b.push(ti !== BACK ? vi.clone() : vi);
  46546. if ((ti | tj) === SPANNING) {
  46547. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  46548. var v = vi.interpolate(vj, t);
  46549. f.push(v);
  46550. b.push(v.clone());
  46551. }
  46552. }
  46553. var poly;
  46554. if (f.length >= 3) {
  46555. poly = new Polygon(f, polygon.shared);
  46556. if (poly.plane)
  46557. front.push(poly);
  46558. }
  46559. if (b.length >= 3) {
  46560. poly = new Polygon(b, polygon.shared);
  46561. if (poly.plane)
  46562. back.push(poly);
  46563. }
  46564. break;
  46565. }
  46566. };
  46567. return Plane;
  46568. }());
  46569. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  46570. // point is on the plane.
  46571. Plane.EPSILON = 1e-5;
  46572. // # class Polygon
  46573. // Represents a convex polygon. The vertices used to initialize a polygon must
  46574. // be coplanar and form a convex loop.
  46575. //
  46576. // Each convex polygon has a `shared` property, which is shared between all
  46577. // polygons that are clones of each other or were split from the same polygon.
  46578. // This can be used to define per-polygon properties (such as surface color).
  46579. var Polygon = (function () {
  46580. function Polygon(vertices, shared) {
  46581. this.vertices = vertices;
  46582. this.shared = shared;
  46583. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  46584. }
  46585. Polygon.prototype.clone = function () {
  46586. var vertices = this.vertices.map(function (v) { return v.clone(); });
  46587. return new Polygon(vertices, this.shared);
  46588. };
  46589. Polygon.prototype.flip = function () {
  46590. this.vertices.reverse().map(function (v) { v.flip(); });
  46591. this.plane.flip();
  46592. };
  46593. return Polygon;
  46594. }());
  46595. // # class Node
  46596. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  46597. // by picking a polygon to split along. That polygon (and all other coplanar
  46598. // polygons) are added directly to that node and the other polygons are added to
  46599. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  46600. // no distinction between internal and leaf nodes.
  46601. var Node = (function () {
  46602. function Node(polygons) {
  46603. this.plane = null;
  46604. this.front = null;
  46605. this.back = null;
  46606. this.polygons = [];
  46607. if (polygons) {
  46608. this.build(polygons);
  46609. }
  46610. }
  46611. Node.prototype.clone = function () {
  46612. var node = new Node();
  46613. node.plane = this.plane && this.plane.clone();
  46614. node.front = this.front && this.front.clone();
  46615. node.back = this.back && this.back.clone();
  46616. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  46617. return node;
  46618. };
  46619. // Convert solid space to empty space and empty space to solid space.
  46620. Node.prototype.invert = function () {
  46621. for (var i = 0; i < this.polygons.length; i++) {
  46622. this.polygons[i].flip();
  46623. }
  46624. if (this.plane) {
  46625. this.plane.flip();
  46626. }
  46627. if (this.front) {
  46628. this.front.invert();
  46629. }
  46630. if (this.back) {
  46631. this.back.invert();
  46632. }
  46633. var temp = this.front;
  46634. this.front = this.back;
  46635. this.back = temp;
  46636. };
  46637. // Recursively remove all polygons in `polygons` that are inside this BSP
  46638. // tree.
  46639. Node.prototype.clipPolygons = function (polygons) {
  46640. if (!this.plane)
  46641. return polygons.slice();
  46642. var front = [], back = [];
  46643. for (var i = 0; i < polygons.length; i++) {
  46644. this.plane.splitPolygon(polygons[i], front, back, front, back);
  46645. }
  46646. if (this.front) {
  46647. front = this.front.clipPolygons(front);
  46648. }
  46649. if (this.back) {
  46650. back = this.back.clipPolygons(back);
  46651. }
  46652. else {
  46653. back = [];
  46654. }
  46655. return front.concat(back);
  46656. };
  46657. // Remove all polygons in this BSP tree that are inside the other BSP tree
  46658. // `bsp`.
  46659. Node.prototype.clipTo = function (bsp) {
  46660. this.polygons = bsp.clipPolygons(this.polygons);
  46661. if (this.front)
  46662. this.front.clipTo(bsp);
  46663. if (this.back)
  46664. this.back.clipTo(bsp);
  46665. };
  46666. // Return a list of all polygons in this BSP tree.
  46667. Node.prototype.allPolygons = function () {
  46668. var polygons = this.polygons.slice();
  46669. if (this.front)
  46670. polygons = polygons.concat(this.front.allPolygons());
  46671. if (this.back)
  46672. polygons = polygons.concat(this.back.allPolygons());
  46673. return polygons;
  46674. };
  46675. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  46676. // new polygons are filtered down to the bottom of the tree and become new
  46677. // nodes there. Each set of polygons is partitioned using the first polygon
  46678. // (no heuristic is used to pick a good split).
  46679. Node.prototype.build = function (polygons) {
  46680. if (!polygons.length)
  46681. return;
  46682. if (!this.plane)
  46683. this.plane = polygons[0].plane.clone();
  46684. var front = [], back = [];
  46685. for (var i = 0; i < polygons.length; i++) {
  46686. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  46687. }
  46688. if (front.length) {
  46689. if (!this.front)
  46690. this.front = new Node();
  46691. this.front.build(front);
  46692. }
  46693. if (back.length) {
  46694. if (!this.back)
  46695. this.back = new Node();
  46696. this.back.build(back);
  46697. }
  46698. };
  46699. return Node;
  46700. }());
  46701. var CSG = (function () {
  46702. function CSG() {
  46703. this.polygons = new Array();
  46704. }
  46705. // Convert BABYLON.Mesh to BABYLON.CSG
  46706. CSG.FromMesh = function (mesh) {
  46707. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  46708. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  46709. if (mesh instanceof BABYLON.Mesh) {
  46710. mesh.computeWorldMatrix(true);
  46711. matrix = mesh.getWorldMatrix();
  46712. meshPosition = mesh.position.clone();
  46713. meshRotation = mesh.rotation.clone();
  46714. if (mesh.rotationQuaternion) {
  46715. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  46716. }
  46717. meshScaling = mesh.scaling.clone();
  46718. }
  46719. else {
  46720. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  46721. }
  46722. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46723. var subMeshes = mesh.subMeshes;
  46724. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  46725. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  46726. vertices = [];
  46727. for (var j = 0; j < 3; j++) {
  46728. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  46729. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  46730. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  46731. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  46732. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  46733. vertex = new Vertex(position, normal, uv);
  46734. vertices.push(vertex);
  46735. }
  46736. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  46737. // To handle the case of degenerated triangle
  46738. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  46739. if (polygon.plane)
  46740. polygons.push(polygon);
  46741. }
  46742. }
  46743. var csg = CSG.FromPolygons(polygons);
  46744. csg.matrix = matrix;
  46745. csg.position = meshPosition;
  46746. csg.rotation = meshRotation;
  46747. csg.scaling = meshScaling;
  46748. csg.rotationQuaternion = meshRotationQuaternion;
  46749. currentCSGMeshId++;
  46750. return csg;
  46751. };
  46752. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  46753. CSG.FromPolygons = function (polygons) {
  46754. var csg = new CSG();
  46755. csg.polygons = polygons;
  46756. return csg;
  46757. };
  46758. CSG.prototype.clone = function () {
  46759. var csg = new CSG();
  46760. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  46761. csg.copyTransformAttributes(this);
  46762. return csg;
  46763. };
  46764. CSG.prototype.toPolygons = function () {
  46765. return this.polygons;
  46766. };
  46767. CSG.prototype.union = function (csg) {
  46768. var a = new Node(this.clone().polygons);
  46769. var b = new Node(csg.clone().polygons);
  46770. a.clipTo(b);
  46771. b.clipTo(a);
  46772. b.invert();
  46773. b.clipTo(a);
  46774. b.invert();
  46775. a.build(b.allPolygons());
  46776. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46777. };
  46778. CSG.prototype.unionInPlace = function (csg) {
  46779. var a = new Node(this.polygons);
  46780. var b = new Node(csg.polygons);
  46781. a.clipTo(b);
  46782. b.clipTo(a);
  46783. b.invert();
  46784. b.clipTo(a);
  46785. b.invert();
  46786. a.build(b.allPolygons());
  46787. this.polygons = a.allPolygons();
  46788. };
  46789. CSG.prototype.subtract = function (csg) {
  46790. var a = new Node(this.clone().polygons);
  46791. var b = new Node(csg.clone().polygons);
  46792. a.invert();
  46793. a.clipTo(b);
  46794. b.clipTo(a);
  46795. b.invert();
  46796. b.clipTo(a);
  46797. b.invert();
  46798. a.build(b.allPolygons());
  46799. a.invert();
  46800. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46801. };
  46802. CSG.prototype.subtractInPlace = function (csg) {
  46803. var a = new Node(this.polygons);
  46804. var b = new Node(csg.polygons);
  46805. a.invert();
  46806. a.clipTo(b);
  46807. b.clipTo(a);
  46808. b.invert();
  46809. b.clipTo(a);
  46810. b.invert();
  46811. a.build(b.allPolygons());
  46812. a.invert();
  46813. this.polygons = a.allPolygons();
  46814. };
  46815. CSG.prototype.intersect = function (csg) {
  46816. var a = new Node(this.clone().polygons);
  46817. var b = new Node(csg.clone().polygons);
  46818. a.invert();
  46819. b.clipTo(a);
  46820. b.invert();
  46821. a.clipTo(b);
  46822. b.clipTo(a);
  46823. a.build(b.allPolygons());
  46824. a.invert();
  46825. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46826. };
  46827. CSG.prototype.intersectInPlace = function (csg) {
  46828. var a = new Node(this.polygons);
  46829. var b = new Node(csg.polygons);
  46830. a.invert();
  46831. b.clipTo(a);
  46832. b.invert();
  46833. a.clipTo(b);
  46834. b.clipTo(a);
  46835. a.build(b.allPolygons());
  46836. a.invert();
  46837. this.polygons = a.allPolygons();
  46838. };
  46839. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  46840. // not modified.
  46841. CSG.prototype.inverse = function () {
  46842. var csg = this.clone();
  46843. csg.inverseInPlace();
  46844. return csg;
  46845. };
  46846. CSG.prototype.inverseInPlace = function () {
  46847. this.polygons.map(function (p) { p.flip(); });
  46848. };
  46849. // This is used to keep meshes transformations so they can be restored
  46850. // when we build back a Babylon Mesh
  46851. // NB : All CSG operations are performed in world coordinates
  46852. CSG.prototype.copyTransformAttributes = function (csg) {
  46853. this.matrix = csg.matrix;
  46854. this.position = csg.position;
  46855. this.rotation = csg.rotation;
  46856. this.scaling = csg.scaling;
  46857. this.rotationQuaternion = csg.rotationQuaternion;
  46858. return this;
  46859. };
  46860. // Build Raw mesh from CSG
  46861. // Coordinates here are in world space
  46862. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  46863. var matrix = this.matrix.clone();
  46864. matrix.invert();
  46865. 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;
  46866. if (keepSubMeshes) {
  46867. // Sort Polygons, since subMeshes are indices range
  46868. polygons.sort(function (a, b) {
  46869. if (a.shared.meshId === b.shared.meshId) {
  46870. return a.shared.subMeshId - b.shared.subMeshId;
  46871. }
  46872. else {
  46873. return a.shared.meshId - b.shared.meshId;
  46874. }
  46875. });
  46876. }
  46877. for (var i = 0, il = polygons.length; i < il; i++) {
  46878. polygon = polygons[i];
  46879. // Building SubMeshes
  46880. if (!subMesh_dict[polygon.shared.meshId]) {
  46881. subMesh_dict[polygon.shared.meshId] = {};
  46882. }
  46883. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  46884. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  46885. indexStart: +Infinity,
  46886. indexEnd: -Infinity,
  46887. materialIndex: polygon.shared.materialIndex
  46888. };
  46889. }
  46890. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  46891. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  46892. polygonIndices[0] = 0;
  46893. polygonIndices[1] = j - 1;
  46894. polygonIndices[2] = j;
  46895. for (var k = 0; k < 3; k++) {
  46896. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  46897. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  46898. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  46899. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  46900. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  46901. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  46902. // Check if 2 points can be merged
  46903. if (!(typeof vertex_idx !== 'undefined' &&
  46904. normals[vertex_idx * 3] === localNormal.x &&
  46905. normals[vertex_idx * 3 + 1] === localNormal.y &&
  46906. normals[vertex_idx * 3 + 2] === localNormal.z &&
  46907. uvs[vertex_idx * 2] === uv.x &&
  46908. uvs[vertex_idx * 2 + 1] === uv.y)) {
  46909. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  46910. uvs.push(uv.x, uv.y);
  46911. normals.push(normal.x, normal.y, normal.z);
  46912. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  46913. }
  46914. indices.push(vertex_idx);
  46915. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  46916. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  46917. currentIndex++;
  46918. }
  46919. }
  46920. }
  46921. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  46922. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  46923. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  46924. mesh.setIndices(indices);
  46925. if (keepSubMeshes) {
  46926. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  46927. var materialIndexOffset = 0, materialMaxIndex;
  46928. mesh.subMeshes = new Array();
  46929. for (var m in subMesh_dict) {
  46930. materialMaxIndex = -1;
  46931. for (var sm in subMesh_dict[m]) {
  46932. subMesh_obj = subMesh_dict[m][sm];
  46933. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  46934. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  46935. }
  46936. materialIndexOffset += ++materialMaxIndex;
  46937. }
  46938. }
  46939. return mesh;
  46940. };
  46941. // Build Mesh from CSG taking material and transforms into account
  46942. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  46943. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  46944. mesh.material = material;
  46945. mesh.position.copyFrom(this.position);
  46946. mesh.rotation.copyFrom(this.rotation);
  46947. if (this.rotationQuaternion) {
  46948. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  46949. }
  46950. mesh.scaling.copyFrom(this.scaling);
  46951. mesh.computeWorldMatrix(true);
  46952. return mesh;
  46953. };
  46954. return CSG;
  46955. }());
  46956. BABYLON.CSG = CSG;
  46957. })(BABYLON || (BABYLON = {}));
  46958. //# sourceMappingURL=babylon.csg.js.map
  46959. var BABYLON;
  46960. (function (BABYLON) {
  46961. var VRDistortionCorrectionPostProcess = (function (_super) {
  46962. __extends(VRDistortionCorrectionPostProcess, _super);
  46963. //ANY
  46964. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  46965. var _this = _super.call(this, name, "vrDistortionCorrection", [
  46966. 'LensCenter',
  46967. 'Scale',
  46968. 'ScaleIn',
  46969. 'HmdWarpParam'
  46970. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  46971. _this._isRightEye = isRightEye;
  46972. _this._distortionFactors = vrMetrics.distortionK;
  46973. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  46974. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  46975. _this.onSizeChangedObservable.add(function () {
  46976. _this.aspectRatio = _this.width * .5 / _this.height;
  46977. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  46978. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  46979. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  46980. });
  46981. _this.onApplyObservable.add(function (effect) {
  46982. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  46983. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  46984. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  46985. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  46986. });
  46987. return _this;
  46988. }
  46989. return VRDistortionCorrectionPostProcess;
  46990. }(BABYLON.PostProcess));
  46991. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  46992. })(BABYLON || (BABYLON = {}));
  46993. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  46994. // Mainly based on these 2 articles :
  46995. // 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
  46996. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  46997. var BABYLON;
  46998. (function (BABYLON) {
  46999. var JoystickAxis;
  47000. (function (JoystickAxis) {
  47001. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  47002. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  47003. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  47004. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  47005. var VirtualJoystick = (function () {
  47006. function VirtualJoystick(leftJoystick) {
  47007. var _this = this;
  47008. if (leftJoystick) {
  47009. this._leftJoystick = true;
  47010. }
  47011. else {
  47012. this._leftJoystick = false;
  47013. }
  47014. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  47015. VirtualJoystick._globalJoystickIndex++;
  47016. // By default left & right arrow keys are moving the X
  47017. // and up & down keys are moving the Y
  47018. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47019. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47020. this.reverseLeftRight = false;
  47021. this.reverseUpDown = false;
  47022. // collections of pointers
  47023. this._touches = new BABYLON.StringDictionary();
  47024. this.deltaPosition = BABYLON.Vector3.Zero();
  47025. this._joystickSensibility = 25;
  47026. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47027. this._rotationSpeed = 25;
  47028. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  47029. this._rotateOnAxisRelativeToMesh = false;
  47030. this._onResize = function (evt) {
  47031. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47032. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47033. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  47034. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  47035. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  47036. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  47037. };
  47038. // injecting a canvas element on top of the canvas 3D game
  47039. if (!VirtualJoystick.vjCanvas) {
  47040. window.addEventListener("resize", this._onResize, false);
  47041. VirtualJoystick.vjCanvas = document.createElement("canvas");
  47042. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47043. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47044. VirtualJoystick.vjCanvas.width = window.innerWidth;
  47045. VirtualJoystick.vjCanvas.height = window.innerHeight;
  47046. VirtualJoystick.vjCanvas.style.width = "100%";
  47047. VirtualJoystick.vjCanvas.style.height = "100%";
  47048. VirtualJoystick.vjCanvas.style.position = "absolute";
  47049. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  47050. VirtualJoystick.vjCanvas.style.top = "0px";
  47051. VirtualJoystick.vjCanvas.style.left = "0px";
  47052. VirtualJoystick.vjCanvas.style.zIndex = "5";
  47053. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  47054. // Support for jQuery PEP polyfill
  47055. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  47056. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  47057. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  47058. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47059. document.body.appendChild(VirtualJoystick.vjCanvas);
  47060. }
  47061. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  47062. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  47063. this.pressed = false;
  47064. // default joystick color
  47065. this._joystickColor = "cyan";
  47066. this._joystickPointerID = -1;
  47067. // current joystick position
  47068. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  47069. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  47070. // origin joystick position
  47071. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  47072. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  47073. this._onPointerDownHandlerRef = function (evt) {
  47074. _this._onPointerDown(evt);
  47075. };
  47076. this._onPointerMoveHandlerRef = function (evt) {
  47077. _this._onPointerMove(evt);
  47078. };
  47079. this._onPointerOutHandlerRef = function (evt) {
  47080. _this._onPointerUp(evt);
  47081. };
  47082. this._onPointerUpHandlerRef = function (evt) {
  47083. _this._onPointerUp(evt);
  47084. };
  47085. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  47086. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  47087. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  47088. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  47089. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  47090. evt.preventDefault(); // Disables system menu
  47091. }, false);
  47092. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47093. }
  47094. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  47095. this._joystickSensibility = newJoystickSensibility;
  47096. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47097. };
  47098. VirtualJoystick.prototype._onPointerDown = function (e) {
  47099. var positionOnScreenCondition;
  47100. e.preventDefault();
  47101. if (this._leftJoystick === true) {
  47102. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  47103. }
  47104. else {
  47105. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  47106. }
  47107. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  47108. // First contact will be dedicated to the virtual joystick
  47109. this._joystickPointerID = e.pointerId;
  47110. this._joystickPointerStartPos.x = e.clientX;
  47111. this._joystickPointerStartPos.y = e.clientY;
  47112. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  47113. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  47114. this._deltaJoystickVector.x = 0;
  47115. this._deltaJoystickVector.y = 0;
  47116. this.pressed = true;
  47117. this._touches.add(e.pointerId.toString(), e);
  47118. }
  47119. else {
  47120. // You can only trigger the action buttons with a joystick declared
  47121. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  47122. this._action();
  47123. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  47124. }
  47125. }
  47126. };
  47127. VirtualJoystick.prototype._onPointerMove = function (e) {
  47128. // If the current pointer is the one associated to the joystick (first touch contact)
  47129. if (this._joystickPointerID == e.pointerId) {
  47130. this._joystickPointerPos.x = e.clientX;
  47131. this._joystickPointerPos.y = e.clientY;
  47132. this._deltaJoystickVector = this._joystickPointerPos.clone();
  47133. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  47134. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  47135. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  47136. switch (this._axisTargetedByLeftAndRight) {
  47137. case JoystickAxis.X:
  47138. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  47139. break;
  47140. case JoystickAxis.Y:
  47141. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  47142. break;
  47143. case JoystickAxis.Z:
  47144. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  47145. break;
  47146. }
  47147. var directionUpDown = this.reverseUpDown ? 1 : -1;
  47148. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  47149. switch (this._axisTargetedByUpAndDown) {
  47150. case JoystickAxis.X:
  47151. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  47152. break;
  47153. case JoystickAxis.Y:
  47154. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  47155. break;
  47156. case JoystickAxis.Z:
  47157. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  47158. break;
  47159. }
  47160. }
  47161. else {
  47162. var data = this._touches.get(e.pointerId.toString());
  47163. if (data) {
  47164. data.x = e.clientX;
  47165. data.y = e.clientY;
  47166. }
  47167. }
  47168. };
  47169. VirtualJoystick.prototype._onPointerUp = function (e) {
  47170. if (this._joystickPointerID == e.pointerId) {
  47171. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  47172. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  47173. this._joystickPointerID = -1;
  47174. this.pressed = false;
  47175. }
  47176. else {
  47177. var touch = this._touches.get(e.pointerId.toString());
  47178. if (touch) {
  47179. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47180. }
  47181. }
  47182. this._deltaJoystickVector.x = 0;
  47183. this._deltaJoystickVector.y = 0;
  47184. this._touches.remove(e.pointerId.toString());
  47185. };
  47186. /**
  47187. * Change the color of the virtual joystick
  47188. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  47189. */
  47190. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  47191. this._joystickColor = newColor;
  47192. };
  47193. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  47194. this._action = action;
  47195. };
  47196. // Define which axis you'd like to control for left & right
  47197. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  47198. switch (axis) {
  47199. case JoystickAxis.X:
  47200. case JoystickAxis.Y:
  47201. case JoystickAxis.Z:
  47202. this._axisTargetedByLeftAndRight = axis;
  47203. break;
  47204. default:
  47205. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47206. break;
  47207. }
  47208. };
  47209. // Define which axis you'd like to control for up & down
  47210. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  47211. switch (axis) {
  47212. case JoystickAxis.X:
  47213. case JoystickAxis.Y:
  47214. case JoystickAxis.Z:
  47215. this._axisTargetedByUpAndDown = axis;
  47216. break;
  47217. default:
  47218. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47219. break;
  47220. }
  47221. };
  47222. VirtualJoystick.prototype._clearCanvas = function () {
  47223. if (this._leftJoystick) {
  47224. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  47225. }
  47226. else {
  47227. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  47228. }
  47229. };
  47230. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  47231. var _this = this;
  47232. if (this.pressed) {
  47233. this._touches.forEach(function (key, touch) {
  47234. if (touch.pointerId === _this._joystickPointerID) {
  47235. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  47236. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  47237. VirtualJoystick.vjCanvasContext.beginPath();
  47238. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47239. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47240. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  47241. VirtualJoystick.vjCanvasContext.stroke();
  47242. VirtualJoystick.vjCanvasContext.closePath();
  47243. VirtualJoystick.vjCanvasContext.beginPath();
  47244. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47245. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47246. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  47247. VirtualJoystick.vjCanvasContext.stroke();
  47248. VirtualJoystick.vjCanvasContext.closePath();
  47249. VirtualJoystick.vjCanvasContext.beginPath();
  47250. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47251. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  47252. VirtualJoystick.vjCanvasContext.stroke();
  47253. VirtualJoystick.vjCanvasContext.closePath();
  47254. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  47255. }
  47256. else {
  47257. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47258. VirtualJoystick.vjCanvasContext.beginPath();
  47259. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  47260. VirtualJoystick.vjCanvasContext.beginPath();
  47261. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  47262. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47263. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  47264. VirtualJoystick.vjCanvasContext.stroke();
  47265. VirtualJoystick.vjCanvasContext.closePath();
  47266. touch.prevX = touch.x;
  47267. touch.prevY = touch.y;
  47268. }
  47269. ;
  47270. });
  47271. }
  47272. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47273. };
  47274. VirtualJoystick.prototype.releaseCanvas = function () {
  47275. if (VirtualJoystick.vjCanvas) {
  47276. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  47277. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  47278. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  47279. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  47280. window.removeEventListener("resize", this._onResize);
  47281. document.body.removeChild(VirtualJoystick.vjCanvas);
  47282. VirtualJoystick.vjCanvas = null;
  47283. }
  47284. };
  47285. return VirtualJoystick;
  47286. }());
  47287. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  47288. VirtualJoystick._globalJoystickIndex = 0;
  47289. BABYLON.VirtualJoystick = VirtualJoystick;
  47290. })(BABYLON || (BABYLON = {}));
  47291. //# sourceMappingURL=babylon.virtualJoystick.js.map
  47292. var BABYLON;
  47293. (function (BABYLON) {
  47294. // We're mainly based on the logic defined into the FreeCamera code
  47295. var VirtualJoysticksCamera = (function (_super) {
  47296. __extends(VirtualJoysticksCamera, _super);
  47297. function VirtualJoysticksCamera(name, position, scene) {
  47298. var _this = _super.call(this, name, position, scene) || this;
  47299. _this.inputs.addVirtualJoystick();
  47300. return _this;
  47301. }
  47302. VirtualJoysticksCamera.prototype.getClassName = function () {
  47303. return "VirtualJoysticksCamera";
  47304. };
  47305. return VirtualJoysticksCamera;
  47306. }(BABYLON.FreeCamera));
  47307. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  47308. })(BABYLON || (BABYLON = {}));
  47309. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  47310. var BABYLON;
  47311. (function (BABYLON) {
  47312. var FreeCameraVirtualJoystickInput = (function () {
  47313. function FreeCameraVirtualJoystickInput() {
  47314. }
  47315. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  47316. return this._leftjoystick;
  47317. };
  47318. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  47319. return this._rightjoystick;
  47320. };
  47321. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  47322. if (this._leftjoystick) {
  47323. var camera = this.camera;
  47324. var speed = camera._computeLocalCameraSpeed() * 50;
  47325. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  47326. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  47327. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  47328. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  47329. if (!this._leftjoystick.pressed) {
  47330. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  47331. }
  47332. if (!this._rightjoystick.pressed) {
  47333. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  47334. }
  47335. }
  47336. };
  47337. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  47338. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  47339. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  47340. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  47341. this._leftjoystick.setJoystickSensibility(0.15);
  47342. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  47343. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  47344. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  47345. this._rightjoystick.reverseUpDown = true;
  47346. this._rightjoystick.setJoystickSensibility(0.05);
  47347. this._rightjoystick.setJoystickColor("yellow");
  47348. };
  47349. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  47350. this._leftjoystick.releaseCanvas();
  47351. this._rightjoystick.releaseCanvas();
  47352. };
  47353. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  47354. return "FreeCameraVirtualJoystickInput";
  47355. };
  47356. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  47357. return "virtualJoystick";
  47358. };
  47359. return FreeCameraVirtualJoystickInput;
  47360. }());
  47361. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  47362. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  47363. })(BABYLON || (BABYLON = {}));
  47364. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  47365. var BABYLON;
  47366. (function (BABYLON) {
  47367. var AnaglyphPostProcess = (function (_super) {
  47368. __extends(AnaglyphPostProcess, _super);
  47369. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  47370. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  47371. _this._passedProcess = rigCameras[0]._rigPostProcess;
  47372. _this.onApplyObservable.add(function (effect) {
  47373. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  47374. });
  47375. return _this;
  47376. }
  47377. return AnaglyphPostProcess;
  47378. }(BABYLON.PostProcess));
  47379. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  47380. })(BABYLON || (BABYLON = {}));
  47381. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  47382. var BABYLON;
  47383. (function (BABYLON) {
  47384. var OutlineRenderer = (function () {
  47385. function OutlineRenderer(scene) {
  47386. this._scene = scene;
  47387. }
  47388. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  47389. var _this = this;
  47390. if (useOverlay === void 0) { useOverlay = false; }
  47391. var scene = this._scene;
  47392. var engine = this._scene.getEngine();
  47393. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47394. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  47395. return;
  47396. }
  47397. var mesh = subMesh.getRenderingMesh();
  47398. var material = subMesh.getMaterial();
  47399. engine.enableEffect(this._effect);
  47400. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  47401. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  47402. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47403. // Bones
  47404. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47405. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47406. }
  47407. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47408. // Alpha test
  47409. if (material && material.needAlphaTesting()) {
  47410. var alphaTexture = material.getAlphaTestTexture();
  47411. this._effect.setTexture("diffuseSampler", alphaTexture);
  47412. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47413. }
  47414. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  47415. };
  47416. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  47417. var defines = [];
  47418. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  47419. var mesh = subMesh.getMesh();
  47420. var material = subMesh.getMaterial();
  47421. // Alpha test
  47422. if (material && material.needAlphaTesting()) {
  47423. defines.push("#define ALPHATEST");
  47424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47425. attribs.push(BABYLON.VertexBuffer.UVKind);
  47426. defines.push("#define UV1");
  47427. }
  47428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47429. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47430. defines.push("#define UV2");
  47431. }
  47432. }
  47433. // Bones
  47434. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47437. if (mesh.numBoneInfluencers > 4) {
  47438. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47439. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47440. }
  47441. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47442. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47443. }
  47444. else {
  47445. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47446. }
  47447. // Instances
  47448. if (useInstances) {
  47449. defines.push("#define INSTANCES");
  47450. attribs.push("world0");
  47451. attribs.push("world1");
  47452. attribs.push("world2");
  47453. attribs.push("world3");
  47454. }
  47455. // Get correct effect
  47456. var join = defines.join("\n");
  47457. if (this._cachedDefines !== join) {
  47458. this._cachedDefines = join;
  47459. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  47460. }
  47461. return this._effect.isReady();
  47462. };
  47463. return OutlineRenderer;
  47464. }());
  47465. BABYLON.OutlineRenderer = OutlineRenderer;
  47466. })(BABYLON || (BABYLON = {}));
  47467. //# sourceMappingURL=babylon.outlineRenderer.js.map
  47468. var BABYLON;
  47469. (function (BABYLON) {
  47470. var MeshAssetTask = (function () {
  47471. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  47472. this.name = name;
  47473. this.meshesNames = meshesNames;
  47474. this.rootUrl = rootUrl;
  47475. this.sceneFilename = sceneFilename;
  47476. this.isCompleted = false;
  47477. }
  47478. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47479. var _this = this;
  47480. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  47481. _this.loadedMeshes = meshes;
  47482. _this.loadedParticleSystems = particleSystems;
  47483. _this.loadedSkeletons = skeletons;
  47484. _this.isCompleted = true;
  47485. if (_this.onSuccess) {
  47486. _this.onSuccess(_this);
  47487. }
  47488. onSuccess();
  47489. }, null, function () {
  47490. if (_this.onError) {
  47491. _this.onError(_this);
  47492. }
  47493. onError();
  47494. });
  47495. };
  47496. return MeshAssetTask;
  47497. }());
  47498. BABYLON.MeshAssetTask = MeshAssetTask;
  47499. var TextFileAssetTask = (function () {
  47500. function TextFileAssetTask(name, url) {
  47501. this.name = name;
  47502. this.url = url;
  47503. this.isCompleted = false;
  47504. }
  47505. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47506. var _this = this;
  47507. BABYLON.Tools.LoadFile(this.url, function (data) {
  47508. _this.text = data;
  47509. _this.isCompleted = true;
  47510. if (_this.onSuccess) {
  47511. _this.onSuccess(_this);
  47512. }
  47513. onSuccess();
  47514. }, null, scene.database, false, function () {
  47515. if (_this.onError) {
  47516. _this.onError(_this);
  47517. }
  47518. onError();
  47519. });
  47520. };
  47521. return TextFileAssetTask;
  47522. }());
  47523. BABYLON.TextFileAssetTask = TextFileAssetTask;
  47524. var BinaryFileAssetTask = (function () {
  47525. function BinaryFileAssetTask(name, url) {
  47526. this.name = name;
  47527. this.url = url;
  47528. this.isCompleted = false;
  47529. }
  47530. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47531. var _this = this;
  47532. BABYLON.Tools.LoadFile(this.url, function (data) {
  47533. _this.data = data;
  47534. _this.isCompleted = true;
  47535. if (_this.onSuccess) {
  47536. _this.onSuccess(_this);
  47537. }
  47538. onSuccess();
  47539. }, null, scene.database, true, function () {
  47540. if (_this.onError) {
  47541. _this.onError(_this);
  47542. }
  47543. onError();
  47544. });
  47545. };
  47546. return BinaryFileAssetTask;
  47547. }());
  47548. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  47549. var ImageAssetTask = (function () {
  47550. function ImageAssetTask(name, url) {
  47551. this.name = name;
  47552. this.url = url;
  47553. this.isCompleted = false;
  47554. }
  47555. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47556. var _this = this;
  47557. var img = new Image();
  47558. BABYLON.Tools.SetCorsBehavior(this.url, img);
  47559. img.onload = function () {
  47560. _this.image = img;
  47561. _this.isCompleted = true;
  47562. if (_this.onSuccess) {
  47563. _this.onSuccess(_this);
  47564. }
  47565. onSuccess();
  47566. };
  47567. img.onerror = function () {
  47568. if (_this.onError) {
  47569. _this.onError(_this);
  47570. }
  47571. onError();
  47572. };
  47573. img.src = this.url;
  47574. };
  47575. return ImageAssetTask;
  47576. }());
  47577. BABYLON.ImageAssetTask = ImageAssetTask;
  47578. var TextureAssetTask = (function () {
  47579. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  47580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47581. this.name = name;
  47582. this.url = url;
  47583. this.noMipmap = noMipmap;
  47584. this.invertY = invertY;
  47585. this.samplingMode = samplingMode;
  47586. this.isCompleted = false;
  47587. }
  47588. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47589. var _this = this;
  47590. var onload = function () {
  47591. _this.isCompleted = true;
  47592. if (_this.onSuccess) {
  47593. _this.onSuccess(_this);
  47594. }
  47595. onSuccess();
  47596. };
  47597. var onerror = function () {
  47598. if (_this.onError) {
  47599. _this.onError(_this);
  47600. }
  47601. onError();
  47602. };
  47603. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  47604. };
  47605. return TextureAssetTask;
  47606. }());
  47607. BABYLON.TextureAssetTask = TextureAssetTask;
  47608. var CubeTextureAssetTask = (function () {
  47609. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  47610. this.name = name;
  47611. this.url = url;
  47612. this.extensions = extensions;
  47613. this.noMipmap = noMipmap;
  47614. this.files = files;
  47615. this.isCompleted = false;
  47616. }
  47617. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47618. var _this = this;
  47619. var onload = function () {
  47620. _this.isCompleted = true;
  47621. if (_this.onSuccess) {
  47622. _this.onSuccess(_this);
  47623. }
  47624. onSuccess();
  47625. };
  47626. var onerror = function () {
  47627. if (_this.onError) {
  47628. _this.onError(_this);
  47629. }
  47630. onError();
  47631. };
  47632. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  47633. };
  47634. return CubeTextureAssetTask;
  47635. }());
  47636. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  47637. var HDRCubeTextureAssetTask = (function () {
  47638. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  47639. if (noMipmap === void 0) { noMipmap = false; }
  47640. if (generateHarmonics === void 0) { generateHarmonics = true; }
  47641. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  47642. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  47643. this.name = name;
  47644. this.url = url;
  47645. this.size = size;
  47646. this.noMipmap = noMipmap;
  47647. this.generateHarmonics = generateHarmonics;
  47648. this.useInGammaSpace = useInGammaSpace;
  47649. this.usePMREMGenerator = usePMREMGenerator;
  47650. this.isCompleted = false;
  47651. }
  47652. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47653. var _this = this;
  47654. var onload = function () {
  47655. _this.isCompleted = true;
  47656. if (_this.onSuccess) {
  47657. _this.onSuccess(_this);
  47658. }
  47659. onSuccess();
  47660. };
  47661. var onerror = function () {
  47662. if (_this.onError) {
  47663. _this.onError(_this);
  47664. }
  47665. onError();
  47666. };
  47667. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  47668. };
  47669. return HDRCubeTextureAssetTask;
  47670. }());
  47671. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  47672. var AssetsManager = (function () {
  47673. function AssetsManager(scene) {
  47674. this.tasks = new Array();
  47675. this.waitingTasksCount = 0;
  47676. this.useDefaultLoadingScreen = true;
  47677. this._scene = scene;
  47678. }
  47679. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  47680. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  47681. this.tasks.push(task);
  47682. return task;
  47683. };
  47684. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  47685. var task = new TextFileAssetTask(taskName, url);
  47686. this.tasks.push(task);
  47687. return task;
  47688. };
  47689. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  47690. var task = new BinaryFileAssetTask(taskName, url);
  47691. this.tasks.push(task);
  47692. return task;
  47693. };
  47694. AssetsManager.prototype.addImageTask = function (taskName, url) {
  47695. var task = new ImageAssetTask(taskName, url);
  47696. this.tasks.push(task);
  47697. return task;
  47698. };
  47699. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  47700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47701. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  47702. this.tasks.push(task);
  47703. return task;
  47704. };
  47705. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  47706. this.waitingTasksCount--;
  47707. if (this.waitingTasksCount === 0) {
  47708. if (this.onFinish) {
  47709. this.onFinish(this.tasks);
  47710. }
  47711. this._scene.getEngine().hideLoadingUI();
  47712. }
  47713. };
  47714. AssetsManager.prototype._runTask = function (task) {
  47715. var _this = this;
  47716. task.run(this._scene, function () {
  47717. if (_this.onTaskSuccess) {
  47718. _this.onTaskSuccess(task);
  47719. }
  47720. _this._decreaseWaitingTasksCount();
  47721. }, function () {
  47722. if (_this.onTaskError) {
  47723. _this.onTaskError(task);
  47724. }
  47725. _this._decreaseWaitingTasksCount();
  47726. });
  47727. };
  47728. AssetsManager.prototype.reset = function () {
  47729. this.tasks = new Array();
  47730. return this;
  47731. };
  47732. AssetsManager.prototype.load = function () {
  47733. this.waitingTasksCount = this.tasks.length;
  47734. if (this.waitingTasksCount === 0) {
  47735. if (this.onFinish) {
  47736. this.onFinish(this.tasks);
  47737. }
  47738. return this;
  47739. }
  47740. if (this.useDefaultLoadingScreen) {
  47741. this._scene.getEngine().displayLoadingUI();
  47742. }
  47743. for (var index = 0; index < this.tasks.length; index++) {
  47744. var task = this.tasks[index];
  47745. this._runTask(task);
  47746. }
  47747. return this;
  47748. };
  47749. return AssetsManager;
  47750. }());
  47751. BABYLON.AssetsManager = AssetsManager;
  47752. })(BABYLON || (BABYLON = {}));
  47753. //# sourceMappingURL=babylon.assetsManager.js.map
  47754. var BABYLON;
  47755. (function (BABYLON) {
  47756. var VRCameraMetrics = (function () {
  47757. function VRCameraMetrics() {
  47758. this.compensateDistortion = true;
  47759. }
  47760. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  47761. get: function () {
  47762. return this.hResolution / (2 * this.vResolution);
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  47768. get: function () {
  47769. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  47770. },
  47771. enumerable: true,
  47772. configurable: true
  47773. });
  47774. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  47775. get: function () {
  47776. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47777. var h = (4 * meters) / this.hScreenSize;
  47778. return BABYLON.Matrix.Translation(h, 0, 0);
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  47784. get: function () {
  47785. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47786. var h = (4 * meters) / this.hScreenSize;
  47787. return BABYLON.Matrix.Translation(-h, 0, 0);
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  47793. get: function () {
  47794. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  47800. get: function () {
  47801. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  47802. },
  47803. enumerable: true,
  47804. configurable: true
  47805. });
  47806. VRCameraMetrics.GetDefault = function () {
  47807. var result = new VRCameraMetrics();
  47808. result.hResolution = 1280;
  47809. result.vResolution = 800;
  47810. result.hScreenSize = 0.149759993;
  47811. result.vScreenSize = 0.0935999975;
  47812. result.vScreenCenter = 0.0467999987;
  47813. result.eyeToScreenDistance = 0.0410000011;
  47814. result.lensSeparationDistance = 0.0635000020;
  47815. result.interpupillaryDistance = 0.0640000030;
  47816. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  47817. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  47818. result.postProcessScaleFactor = 1.714605507808412;
  47819. result.lensCenterOffset = 0.151976421;
  47820. return result;
  47821. };
  47822. return VRCameraMetrics;
  47823. }());
  47824. BABYLON.VRCameraMetrics = VRCameraMetrics;
  47825. })(BABYLON || (BABYLON = {}));
  47826. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  47827. var BABYLON;
  47828. (function (BABYLON) {
  47829. var WebVRFreeCamera = (function (_super) {
  47830. __extends(WebVRFreeCamera, _super);
  47831. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  47832. if (compensateDistortion === void 0) { compensateDistortion = false; }
  47833. if (webVROptions === void 0) { webVROptions = {}; }
  47834. var _this = _super.call(this, name, position, scene) || this;
  47835. _this.webVROptions = webVROptions;
  47836. _this._vrDevice = null;
  47837. _this._cacheState = null;
  47838. _this._vrEnabled = false;
  47839. _this._attached = false;
  47840. //using the position provided as the current position offset
  47841. _this._positionOffset = position;
  47842. //enable VR
  47843. _this.getEngine().initWebVR();
  47844. if (!_this.getEngine().vrDisplaysPromise) {
  47845. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  47846. }
  47847. else {
  47848. //TODO get the metrics updated using the device's eye parameters!
  47849. //TODO also check that the device has the right capabilities!
  47850. _this._frameData = new VRFrameData();
  47851. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  47852. if (devices.length > 0) {
  47853. _this._vrEnabled = true;
  47854. if (_this.webVROptions.displayName) {
  47855. var found = devices.some(function (device) {
  47856. if (device.displayName === _this.webVROptions.displayName) {
  47857. _this._vrDevice = device;
  47858. return true;
  47859. }
  47860. else {
  47861. return false;
  47862. }
  47863. });
  47864. if (!found) {
  47865. _this._vrDevice = devices[0];
  47866. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  47867. }
  47868. }
  47869. else {
  47870. //choose the first one
  47871. _this._vrDevice = devices[0];
  47872. }
  47873. //reset the rig parameters.
  47874. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  47875. if (_this._attached) {
  47876. _this.getEngine().enableVR(_this._vrDevice);
  47877. }
  47878. }
  47879. else {
  47880. BABYLON.Tools.Error("No WebVR devices found!");
  47881. }
  47882. });
  47883. }
  47884. _this.rotationQuaternion = new BABYLON.Quaternion();
  47885. _this._quaternionCache = new BABYLON.Quaternion();
  47886. return _this;
  47887. }
  47888. WebVRFreeCamera.prototype._checkInputs = function () {
  47889. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  47890. var currentPost = this._frameData.pose;
  47891. //make sure we have data
  47892. if (currentPost && currentPost.orientation) {
  47893. this._cacheState = currentPost;
  47894. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  47895. if (this.webVROptions.trackPosition && this._cacheState.position) {
  47896. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  47897. //scale the position accordingly
  47898. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  47899. //add the position offset
  47900. this.position.addInPlace(this._positionOffset);
  47901. }
  47902. }
  47903. }
  47904. _super.prototype._checkInputs.call(this);
  47905. };
  47906. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47907. _super.prototype.attachControl.call(this, element, noPreventDefault);
  47908. this._attached = true;
  47909. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47910. if (this._vrEnabled) {
  47911. this.getEngine().enableVR(this._vrDevice);
  47912. }
  47913. };
  47914. WebVRFreeCamera.prototype.detachControl = function (element) {
  47915. _super.prototype.detachControl.call(this, element);
  47916. this._vrEnabled = false;
  47917. this._attached = false;
  47918. this.getEngine().disableVR();
  47919. };
  47920. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  47921. //Backwards comp.
  47922. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  47923. //this.getEngine().switchFullscreen(requestPointerlock);
  47924. };
  47925. WebVRFreeCamera.prototype.getClassName = function () {
  47926. return "WebVRFreeCamera";
  47927. };
  47928. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  47929. //uses the vrDisplay's "resetPose()".
  47930. //pitch and roll won't be affected.
  47931. this._vrDevice.resetPose();
  47932. };
  47933. /**
  47934. *
  47935. * Set the position offset of the VR camera
  47936. * The offset will be added to the WebVR pose, after scaling it (if set).
  47937. *
  47938. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  47939. *
  47940. * @memberOf WebVRFreeCamera
  47941. */
  47942. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  47943. if (newPosition) {
  47944. this._positionOffset = newPosition;
  47945. }
  47946. else {
  47947. this._positionOffset.copyFrom(this.position);
  47948. }
  47949. };
  47950. return WebVRFreeCamera;
  47951. }(BABYLON.FreeCamera));
  47952. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  47953. var WebVRGamepadCamera = (function (_super) {
  47954. __extends(WebVRGamepadCamera, _super);
  47955. function WebVRGamepadCamera(name, position, scene, compensateDistortion, webVROptions) {
  47956. if (compensateDistortion === void 0) { compensateDistortion = false; }
  47957. if (webVROptions === void 0) { webVROptions = {}; }
  47958. var _this = _super.call(this, name, position, scene, compensateDistortion, webVROptions) || this;
  47959. _this.inputs.addGamepad();
  47960. return _this;
  47961. }
  47962. WebVRGamepadCamera.prototype.getClassName = function () {
  47963. return "WebVRGamepadCamera";
  47964. };
  47965. return WebVRGamepadCamera;
  47966. }(WebVRFreeCamera));
  47967. BABYLON.WebVRGamepadCamera = WebVRGamepadCamera;
  47968. })(BABYLON || (BABYLON = {}));
  47969. //# sourceMappingURL=babylon.webVRCamera.js.map
  47970. var BABYLON;
  47971. (function (BABYLON) {
  47972. // Standard optimizations
  47973. var SceneOptimization = (function () {
  47974. function SceneOptimization(priority) {
  47975. if (priority === void 0) { priority = 0; }
  47976. this.priority = priority;
  47977. this.apply = function (scene) {
  47978. return true; // Return true if everything that can be done was applied
  47979. };
  47980. }
  47981. return SceneOptimization;
  47982. }());
  47983. BABYLON.SceneOptimization = SceneOptimization;
  47984. var TextureOptimization = (function (_super) {
  47985. __extends(TextureOptimization, _super);
  47986. function TextureOptimization(priority, maximumSize) {
  47987. if (priority === void 0) { priority = 0; }
  47988. if (maximumSize === void 0) { maximumSize = 1024; }
  47989. var _this = _super.call(this, priority) || this;
  47990. _this.priority = priority;
  47991. _this.maximumSize = maximumSize;
  47992. _this.apply = function (scene) {
  47993. var allDone = true;
  47994. for (var index = 0; index < scene.textures.length; index++) {
  47995. var texture = scene.textures[index];
  47996. if (!texture.canRescale) {
  47997. continue;
  47998. }
  47999. var currentSize = texture.getSize();
  48000. var maxDimension = Math.max(currentSize.width, currentSize.height);
  48001. if (maxDimension > _this.maximumSize) {
  48002. texture.scale(0.5);
  48003. allDone = false;
  48004. }
  48005. }
  48006. return allDone;
  48007. };
  48008. return _this;
  48009. }
  48010. return TextureOptimization;
  48011. }(SceneOptimization));
  48012. BABYLON.TextureOptimization = TextureOptimization;
  48013. var HardwareScalingOptimization = (function (_super) {
  48014. __extends(HardwareScalingOptimization, _super);
  48015. function HardwareScalingOptimization(priority, maximumScale) {
  48016. if (priority === void 0) { priority = 0; }
  48017. if (maximumScale === void 0) { maximumScale = 2; }
  48018. var _this = _super.call(this, priority) || this;
  48019. _this.priority = priority;
  48020. _this.maximumScale = maximumScale;
  48021. _this._currentScale = 1;
  48022. _this.apply = function (scene) {
  48023. _this._currentScale++;
  48024. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  48025. return _this._currentScale >= _this.maximumScale;
  48026. };
  48027. return _this;
  48028. }
  48029. return HardwareScalingOptimization;
  48030. }(SceneOptimization));
  48031. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  48032. var ShadowsOptimization = (function (_super) {
  48033. __extends(ShadowsOptimization, _super);
  48034. function ShadowsOptimization() {
  48035. var _this = _super.apply(this, arguments) || this;
  48036. _this.apply = function (scene) {
  48037. scene.shadowsEnabled = false;
  48038. return true;
  48039. };
  48040. return _this;
  48041. }
  48042. return ShadowsOptimization;
  48043. }(SceneOptimization));
  48044. BABYLON.ShadowsOptimization = ShadowsOptimization;
  48045. var PostProcessesOptimization = (function (_super) {
  48046. __extends(PostProcessesOptimization, _super);
  48047. function PostProcessesOptimization() {
  48048. var _this = _super.apply(this, arguments) || this;
  48049. _this.apply = function (scene) {
  48050. scene.postProcessesEnabled = false;
  48051. return true;
  48052. };
  48053. return _this;
  48054. }
  48055. return PostProcessesOptimization;
  48056. }(SceneOptimization));
  48057. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  48058. var LensFlaresOptimization = (function (_super) {
  48059. __extends(LensFlaresOptimization, _super);
  48060. function LensFlaresOptimization() {
  48061. var _this = _super.apply(this, arguments) || this;
  48062. _this.apply = function (scene) {
  48063. scene.lensFlaresEnabled = false;
  48064. return true;
  48065. };
  48066. return _this;
  48067. }
  48068. return LensFlaresOptimization;
  48069. }(SceneOptimization));
  48070. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  48071. var ParticlesOptimization = (function (_super) {
  48072. __extends(ParticlesOptimization, _super);
  48073. function ParticlesOptimization() {
  48074. var _this = _super.apply(this, arguments) || this;
  48075. _this.apply = function (scene) {
  48076. scene.particlesEnabled = false;
  48077. return true;
  48078. };
  48079. return _this;
  48080. }
  48081. return ParticlesOptimization;
  48082. }(SceneOptimization));
  48083. BABYLON.ParticlesOptimization = ParticlesOptimization;
  48084. var RenderTargetsOptimization = (function (_super) {
  48085. __extends(RenderTargetsOptimization, _super);
  48086. function RenderTargetsOptimization() {
  48087. var _this = _super.apply(this, arguments) || this;
  48088. _this.apply = function (scene) {
  48089. scene.renderTargetsEnabled = false;
  48090. return true;
  48091. };
  48092. return _this;
  48093. }
  48094. return RenderTargetsOptimization;
  48095. }(SceneOptimization));
  48096. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  48097. var MergeMeshesOptimization = (function (_super) {
  48098. __extends(MergeMeshesOptimization, _super);
  48099. function MergeMeshesOptimization() {
  48100. var _this = _super.apply(this, arguments) || this;
  48101. _this._canBeMerged = function (abstractMesh) {
  48102. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  48103. return false;
  48104. }
  48105. var mesh = abstractMesh;
  48106. if (!mesh.isVisible || !mesh.isEnabled()) {
  48107. return false;
  48108. }
  48109. if (mesh.instances.length > 0) {
  48110. return false;
  48111. }
  48112. if (mesh.skeleton || mesh.hasLODLevels) {
  48113. return false;
  48114. }
  48115. if (mesh.parent) {
  48116. return false;
  48117. }
  48118. return true;
  48119. };
  48120. _this.apply = function (scene, updateSelectionTree) {
  48121. var globalPool = scene.meshes.slice(0);
  48122. var globalLength = globalPool.length;
  48123. for (var index = 0; index < globalLength; index++) {
  48124. var currentPool = new Array();
  48125. var current = globalPool[index];
  48126. // Checks
  48127. if (!_this._canBeMerged(current)) {
  48128. continue;
  48129. }
  48130. currentPool.push(current);
  48131. // Find compatible meshes
  48132. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  48133. var otherMesh = globalPool[subIndex];
  48134. if (!_this._canBeMerged(otherMesh)) {
  48135. continue;
  48136. }
  48137. if (otherMesh.material !== current.material) {
  48138. continue;
  48139. }
  48140. if (otherMesh.checkCollisions !== current.checkCollisions) {
  48141. continue;
  48142. }
  48143. currentPool.push(otherMesh);
  48144. globalLength--;
  48145. globalPool.splice(subIndex, 1);
  48146. subIndex--;
  48147. }
  48148. if (currentPool.length < 2) {
  48149. continue;
  48150. }
  48151. // Merge meshes
  48152. BABYLON.Mesh.MergeMeshes(currentPool);
  48153. }
  48154. if (updateSelectionTree != undefined) {
  48155. if (updateSelectionTree) {
  48156. scene.createOrUpdateSelectionOctree();
  48157. }
  48158. }
  48159. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  48160. scene.createOrUpdateSelectionOctree();
  48161. }
  48162. return true;
  48163. };
  48164. return _this;
  48165. }
  48166. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  48167. get: function () {
  48168. return MergeMeshesOptimization._UpdateSelectionTree;
  48169. },
  48170. set: function (value) {
  48171. MergeMeshesOptimization._UpdateSelectionTree = value;
  48172. },
  48173. enumerable: true,
  48174. configurable: true
  48175. });
  48176. return MergeMeshesOptimization;
  48177. }(SceneOptimization));
  48178. MergeMeshesOptimization._UpdateSelectionTree = false;
  48179. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  48180. // Options
  48181. var SceneOptimizerOptions = (function () {
  48182. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  48183. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  48184. if (trackerDuration === void 0) { trackerDuration = 2000; }
  48185. this.targetFrameRate = targetFrameRate;
  48186. this.trackerDuration = trackerDuration;
  48187. this.optimizations = new Array();
  48188. }
  48189. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  48190. var result = new SceneOptimizerOptions(targetFrameRate);
  48191. var priority = 0;
  48192. result.optimizations.push(new MergeMeshesOptimization(priority));
  48193. result.optimizations.push(new ShadowsOptimization(priority));
  48194. result.optimizations.push(new LensFlaresOptimization(priority));
  48195. // Next priority
  48196. priority++;
  48197. result.optimizations.push(new PostProcessesOptimization(priority));
  48198. result.optimizations.push(new ParticlesOptimization(priority));
  48199. // Next priority
  48200. priority++;
  48201. result.optimizations.push(new TextureOptimization(priority, 1024));
  48202. return result;
  48203. };
  48204. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  48205. var result = new SceneOptimizerOptions(targetFrameRate);
  48206. var priority = 0;
  48207. result.optimizations.push(new MergeMeshesOptimization(priority));
  48208. result.optimizations.push(new ShadowsOptimization(priority));
  48209. result.optimizations.push(new LensFlaresOptimization(priority));
  48210. // Next priority
  48211. priority++;
  48212. result.optimizations.push(new PostProcessesOptimization(priority));
  48213. result.optimizations.push(new ParticlesOptimization(priority));
  48214. // Next priority
  48215. priority++;
  48216. result.optimizations.push(new TextureOptimization(priority, 512));
  48217. // Next priority
  48218. priority++;
  48219. result.optimizations.push(new RenderTargetsOptimization(priority));
  48220. // Next priority
  48221. priority++;
  48222. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  48223. return result;
  48224. };
  48225. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  48226. var result = new SceneOptimizerOptions(targetFrameRate);
  48227. var priority = 0;
  48228. result.optimizations.push(new MergeMeshesOptimization(priority));
  48229. result.optimizations.push(new ShadowsOptimization(priority));
  48230. result.optimizations.push(new LensFlaresOptimization(priority));
  48231. // Next priority
  48232. priority++;
  48233. result.optimizations.push(new PostProcessesOptimization(priority));
  48234. result.optimizations.push(new ParticlesOptimization(priority));
  48235. // Next priority
  48236. priority++;
  48237. result.optimizations.push(new TextureOptimization(priority, 256));
  48238. // Next priority
  48239. priority++;
  48240. result.optimizations.push(new RenderTargetsOptimization(priority));
  48241. // Next priority
  48242. priority++;
  48243. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  48244. return result;
  48245. };
  48246. return SceneOptimizerOptions;
  48247. }());
  48248. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  48249. // Scene optimizer tool
  48250. var SceneOptimizer = (function () {
  48251. function SceneOptimizer() {
  48252. }
  48253. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  48254. // TODO: add an epsilon
  48255. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  48256. if (onSuccess) {
  48257. onSuccess();
  48258. }
  48259. return;
  48260. }
  48261. // Apply current level of optimizations
  48262. var allDone = true;
  48263. var noOptimizationApplied = true;
  48264. for (var index = 0; index < options.optimizations.length; index++) {
  48265. var optimization = options.optimizations[index];
  48266. if (optimization.priority === currentPriorityLevel) {
  48267. noOptimizationApplied = false;
  48268. allDone = allDone && optimization.apply(scene);
  48269. }
  48270. }
  48271. // If no optimization was applied, this is a failure :(
  48272. if (noOptimizationApplied) {
  48273. if (onFailure) {
  48274. onFailure();
  48275. }
  48276. return;
  48277. }
  48278. // If all optimizations were done, move to next level
  48279. if (allDone) {
  48280. currentPriorityLevel++;
  48281. }
  48282. // Let's the system running for a specific amount of time before checking FPS
  48283. scene.executeWhenReady(function () {
  48284. setTimeout(function () {
  48285. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  48286. }, options.trackerDuration);
  48287. });
  48288. };
  48289. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  48290. if (!options) {
  48291. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  48292. }
  48293. // Let's the system running for a specific amount of time before checking FPS
  48294. scene.executeWhenReady(function () {
  48295. setTimeout(function () {
  48296. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  48297. }, options.trackerDuration);
  48298. });
  48299. };
  48300. return SceneOptimizer;
  48301. }());
  48302. BABYLON.SceneOptimizer = SceneOptimizer;
  48303. })(BABYLON || (BABYLON = {}));
  48304. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  48305. var BABYLON;
  48306. (function (BABYLON) {
  48307. var Internals;
  48308. (function (Internals) {
  48309. var MeshLODLevel = (function () {
  48310. function MeshLODLevel(distance, mesh) {
  48311. this.distance = distance;
  48312. this.mesh = mesh;
  48313. }
  48314. return MeshLODLevel;
  48315. }());
  48316. Internals.MeshLODLevel = MeshLODLevel;
  48317. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48318. })(BABYLON || (BABYLON = {}));
  48319. //# sourceMappingURL=babylon.meshLODLevel.js.map
  48320. var BABYLON;
  48321. (function (BABYLON) {
  48322. var RawTexture = (function (_super) {
  48323. __extends(RawTexture, _super);
  48324. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48325. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48326. if (invertY === void 0) { invertY = false; }
  48327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48328. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48329. _this.format = format;
  48330. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48331. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48332. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48333. return _this;
  48334. }
  48335. RawTexture.prototype.update = function (data) {
  48336. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48337. };
  48338. // Statics
  48339. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48340. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48341. if (invertY === void 0) { invertY = false; }
  48342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48343. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48344. };
  48345. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48346. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48347. if (invertY === void 0) { invertY = false; }
  48348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48349. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48350. };
  48351. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48352. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48353. if (invertY === void 0) { invertY = false; }
  48354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48355. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48356. };
  48357. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48358. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48359. if (invertY === void 0) { invertY = false; }
  48360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48361. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  48362. };
  48363. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48364. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48365. if (invertY === void 0) { invertY = false; }
  48366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48367. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  48368. };
  48369. return RawTexture;
  48370. }(BABYLON.Texture));
  48371. BABYLON.RawTexture = RawTexture;
  48372. })(BABYLON || (BABYLON = {}));
  48373. //# sourceMappingURL=babylon.rawTexture.js.map
  48374. /// <reference path="..\Math\babylon.math.ts" />
  48375. var BABYLON;
  48376. (function (BABYLON) {
  48377. var IndexedVector2 = (function (_super) {
  48378. __extends(IndexedVector2, _super);
  48379. function IndexedVector2(original, index) {
  48380. var _this = _super.call(this, original.x, original.y) || this;
  48381. _this.index = index;
  48382. return _this;
  48383. }
  48384. return IndexedVector2;
  48385. }(BABYLON.Vector2));
  48386. var PolygonPoints = (function () {
  48387. function PolygonPoints() {
  48388. this.elements = new Array();
  48389. }
  48390. PolygonPoints.prototype.add = function (originalPoints) {
  48391. var _this = this;
  48392. var result = new Array();
  48393. originalPoints.forEach(function (point) {
  48394. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  48395. var newPoint = new IndexedVector2(point, _this.elements.length);
  48396. result.push(newPoint);
  48397. _this.elements.push(newPoint);
  48398. }
  48399. });
  48400. return result;
  48401. };
  48402. PolygonPoints.prototype.computeBounds = function () {
  48403. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48404. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48405. this.elements.forEach(function (point) {
  48406. // x
  48407. if (point.x < lmin.x) {
  48408. lmin.x = point.x;
  48409. }
  48410. else if (point.x > lmax.x) {
  48411. lmax.x = point.x;
  48412. }
  48413. // y
  48414. if (point.y < lmin.y) {
  48415. lmin.y = point.y;
  48416. }
  48417. else if (point.y > lmax.y) {
  48418. lmax.y = point.y;
  48419. }
  48420. });
  48421. return {
  48422. min: lmin,
  48423. max: lmax,
  48424. width: lmax.x - lmin.x,
  48425. height: lmax.y - lmin.y
  48426. };
  48427. };
  48428. return PolygonPoints;
  48429. }());
  48430. var Polygon = (function () {
  48431. function Polygon() {
  48432. }
  48433. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  48434. return [
  48435. new BABYLON.Vector2(xmin, ymin),
  48436. new BABYLON.Vector2(xmax, ymin),
  48437. new BABYLON.Vector2(xmax, ymax),
  48438. new BABYLON.Vector2(xmin, ymax)
  48439. ];
  48440. };
  48441. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  48442. if (cx === void 0) { cx = 0; }
  48443. if (cy === void 0) { cy = 0; }
  48444. if (numberOfSides === void 0) { numberOfSides = 32; }
  48445. var result = new Array();
  48446. var angle = 0;
  48447. var increment = (Math.PI * 2) / numberOfSides;
  48448. for (var i = 0; i < numberOfSides; i++) {
  48449. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  48450. angle -= increment;
  48451. }
  48452. return result;
  48453. };
  48454. Polygon.Parse = function (input) {
  48455. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  48456. var i, result = [];
  48457. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  48458. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  48459. }
  48460. return result;
  48461. };
  48462. Polygon.StartingAt = function (x, y) {
  48463. return BABYLON.Path2.StartingAt(x, y);
  48464. };
  48465. return Polygon;
  48466. }());
  48467. BABYLON.Polygon = Polygon;
  48468. var PolygonMeshBuilder = (function () {
  48469. function PolygonMeshBuilder(name, contours, scene) {
  48470. this._points = new PolygonPoints();
  48471. this._outlinepoints = new PolygonPoints();
  48472. this._holes = [];
  48473. this._epoints = new Array();
  48474. this._eholes = new Array();
  48475. this._name = name;
  48476. this._scene = scene;
  48477. var points;
  48478. if (contours instanceof BABYLON.Path2) {
  48479. points = contours.getPoints();
  48480. }
  48481. else {
  48482. points = contours;
  48483. }
  48484. this._addToepoint(points);
  48485. this._points.add(points);
  48486. this._outlinepoints.add(points);
  48487. }
  48488. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  48489. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  48490. var p = points_1[_i];
  48491. this._epoints.push(p.x, p.y);
  48492. }
  48493. };
  48494. PolygonMeshBuilder.prototype.addHole = function (hole) {
  48495. this._points.add(hole);
  48496. var holepoints = new PolygonPoints();
  48497. holepoints.add(hole);
  48498. this._holes.push(holepoints);
  48499. this._eholes.push(this._epoints.length / 2);
  48500. this._addToepoint(hole);
  48501. return this;
  48502. };
  48503. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  48504. var _this = this;
  48505. if (updatable === void 0) { updatable = false; }
  48506. var result = new BABYLON.Mesh(this._name, this._scene);
  48507. var normals = [];
  48508. var positions = [];
  48509. var uvs = [];
  48510. var bounds = this._points.computeBounds();
  48511. this._points.elements.forEach(function (p) {
  48512. normals.push(0, 1.0, 0);
  48513. positions.push(p.x, 0, p.y);
  48514. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  48515. });
  48516. var indices = [];
  48517. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  48518. for (var i = 0; i < res.length; i++) {
  48519. indices.push(res[i]);
  48520. }
  48521. if (depth > 0) {
  48522. var positionscount = (positions.length / 3); //get the current pointcount
  48523. this._points.elements.forEach(function (p) {
  48524. normals.push(0, -1.0, 0);
  48525. positions.push(p.x, -depth, p.y);
  48526. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  48527. });
  48528. var totalCount = indices.length;
  48529. for (var i = 0; i < totalCount; i += 3) {
  48530. var i0 = indices[i + 0];
  48531. var i1 = indices[i + 1];
  48532. var i2 = indices[i + 2];
  48533. indices.push(i2 + positionscount);
  48534. indices.push(i1 + positionscount);
  48535. indices.push(i0 + positionscount);
  48536. }
  48537. //Add the sides
  48538. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  48539. this._holes.forEach(function (hole) {
  48540. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  48541. });
  48542. }
  48543. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  48544. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  48545. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  48546. result.setIndices(indices);
  48547. return result;
  48548. };
  48549. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  48550. var StartIndex = positions.length / 3;
  48551. var ulength = 0;
  48552. for (var i = 0; i < points.elements.length; i++) {
  48553. var p = points.elements[i];
  48554. var p1;
  48555. if ((i + 1) > points.elements.length - 1) {
  48556. p1 = points.elements[0];
  48557. }
  48558. else {
  48559. p1 = points.elements[i + 1];
  48560. }
  48561. positions.push(p.x, 0, p.y);
  48562. positions.push(p.x, -depth, p.y);
  48563. positions.push(p1.x, 0, p1.y);
  48564. positions.push(p1.x, -depth, p1.y);
  48565. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  48566. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  48567. var v3 = v2.subtract(v1);
  48568. var v4 = new BABYLON.Vector3(0, 1, 0);
  48569. var vn = BABYLON.Vector3.Cross(v3, v4);
  48570. vn = vn.normalize();
  48571. uvs.push(ulength / bounds.width, 0);
  48572. uvs.push(ulength / bounds.width, 1);
  48573. ulength += v3.length();
  48574. uvs.push((ulength / bounds.width), 0);
  48575. uvs.push((ulength / bounds.width), 1);
  48576. if (!flip) {
  48577. normals.push(-vn.x, -vn.y, -vn.z);
  48578. normals.push(-vn.x, -vn.y, -vn.z);
  48579. normals.push(-vn.x, -vn.y, -vn.z);
  48580. normals.push(-vn.x, -vn.y, -vn.z);
  48581. indices.push(StartIndex);
  48582. indices.push(StartIndex + 1);
  48583. indices.push(StartIndex + 2);
  48584. indices.push(StartIndex + 1);
  48585. indices.push(StartIndex + 3);
  48586. indices.push(StartIndex + 2);
  48587. }
  48588. else {
  48589. normals.push(vn.x, vn.y, vn.z);
  48590. normals.push(vn.x, vn.y, vn.z);
  48591. normals.push(vn.x, vn.y, vn.z);
  48592. normals.push(vn.x, vn.y, vn.z);
  48593. indices.push(StartIndex);
  48594. indices.push(StartIndex + 2);
  48595. indices.push(StartIndex + 1);
  48596. indices.push(StartIndex + 1);
  48597. indices.push(StartIndex + 2);
  48598. indices.push(StartIndex + 3);
  48599. }
  48600. StartIndex += 4;
  48601. }
  48602. ;
  48603. };
  48604. return PolygonMeshBuilder;
  48605. }());
  48606. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  48607. })(BABYLON || (BABYLON = {}));
  48608. //# sourceMappingURL=babylon.polygonMesh.js.map
  48609. var BABYLON;
  48610. (function (BABYLON) {
  48611. var Octree = (function () {
  48612. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  48613. if (maxDepth === void 0) { maxDepth = 2; }
  48614. this.maxDepth = maxDepth;
  48615. this.dynamicContent = new Array();
  48616. this._maxBlockCapacity = maxBlockCapacity || 64;
  48617. this._selectionContent = new BABYLON.SmartArray(1024);
  48618. this._creationFunc = creationFunc;
  48619. }
  48620. // Methods
  48621. Octree.prototype.update = function (worldMin, worldMax, entries) {
  48622. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  48623. };
  48624. Octree.prototype.addMesh = function (entry) {
  48625. for (var index = 0; index < this.blocks.length; index++) {
  48626. var block = this.blocks[index];
  48627. block.addEntry(entry);
  48628. }
  48629. };
  48630. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  48631. this._selectionContent.reset();
  48632. for (var index = 0; index < this.blocks.length; index++) {
  48633. var block = this.blocks[index];
  48634. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  48635. }
  48636. if (allowDuplicate) {
  48637. this._selectionContent.concat(this.dynamicContent);
  48638. }
  48639. else {
  48640. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48641. }
  48642. return this._selectionContent;
  48643. };
  48644. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  48645. this._selectionContent.reset();
  48646. for (var index = 0; index < this.blocks.length; index++) {
  48647. var block = this.blocks[index];
  48648. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  48649. }
  48650. if (allowDuplicate) {
  48651. this._selectionContent.concat(this.dynamicContent);
  48652. }
  48653. else {
  48654. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48655. }
  48656. return this._selectionContent;
  48657. };
  48658. Octree.prototype.intersectsRay = function (ray) {
  48659. this._selectionContent.reset();
  48660. for (var index = 0; index < this.blocks.length; index++) {
  48661. var block = this.blocks[index];
  48662. block.intersectsRay(ray, this._selectionContent);
  48663. }
  48664. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48665. return this._selectionContent;
  48666. };
  48667. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  48668. target.blocks = new Array();
  48669. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  48670. // Segmenting space
  48671. for (var x = 0; x < 2; x++) {
  48672. for (var y = 0; y < 2; y++) {
  48673. for (var z = 0; z < 2; z++) {
  48674. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  48675. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  48676. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  48677. block.addEntries(entries);
  48678. target.blocks.push(block);
  48679. }
  48680. }
  48681. }
  48682. };
  48683. return Octree;
  48684. }());
  48685. Octree.CreationFuncForMeshes = function (entry, block) {
  48686. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48687. block.entries.push(entry);
  48688. }
  48689. };
  48690. Octree.CreationFuncForSubMeshes = function (entry, block) {
  48691. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48692. block.entries.push(entry);
  48693. }
  48694. };
  48695. BABYLON.Octree = Octree;
  48696. })(BABYLON || (BABYLON = {}));
  48697. //# sourceMappingURL=babylon.octree.js.map
  48698. var BABYLON;
  48699. (function (BABYLON) {
  48700. var OctreeBlock = (function () {
  48701. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  48702. this.entries = new Array();
  48703. this._boundingVectors = new Array();
  48704. this._capacity = capacity;
  48705. this._depth = depth;
  48706. this._maxDepth = maxDepth;
  48707. this._creationFunc = creationFunc;
  48708. this._minPoint = minPoint;
  48709. this._maxPoint = maxPoint;
  48710. this._boundingVectors.push(minPoint.clone());
  48711. this._boundingVectors.push(maxPoint.clone());
  48712. this._boundingVectors.push(minPoint.clone());
  48713. this._boundingVectors[2].x = maxPoint.x;
  48714. this._boundingVectors.push(minPoint.clone());
  48715. this._boundingVectors[3].y = maxPoint.y;
  48716. this._boundingVectors.push(minPoint.clone());
  48717. this._boundingVectors[4].z = maxPoint.z;
  48718. this._boundingVectors.push(maxPoint.clone());
  48719. this._boundingVectors[5].z = minPoint.z;
  48720. this._boundingVectors.push(maxPoint.clone());
  48721. this._boundingVectors[6].x = minPoint.x;
  48722. this._boundingVectors.push(maxPoint.clone());
  48723. this._boundingVectors[7].y = minPoint.y;
  48724. }
  48725. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  48726. // Property
  48727. get: function () {
  48728. return this._capacity;
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  48734. get: function () {
  48735. return this._minPoint;
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  48741. get: function () {
  48742. return this._maxPoint;
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. // Methods
  48748. OctreeBlock.prototype.addEntry = function (entry) {
  48749. if (this.blocks) {
  48750. for (var index = 0; index < this.blocks.length; index++) {
  48751. var block = this.blocks[index];
  48752. block.addEntry(entry);
  48753. }
  48754. return;
  48755. }
  48756. this._creationFunc(entry, this);
  48757. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  48758. this.createInnerBlocks();
  48759. }
  48760. };
  48761. OctreeBlock.prototype.addEntries = function (entries) {
  48762. for (var index = 0; index < entries.length; index++) {
  48763. var mesh = entries[index];
  48764. this.addEntry(mesh);
  48765. }
  48766. };
  48767. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  48768. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  48769. if (this.blocks) {
  48770. for (var index = 0; index < this.blocks.length; index++) {
  48771. var block = this.blocks[index];
  48772. block.select(frustumPlanes, selection, allowDuplicate);
  48773. }
  48774. return;
  48775. }
  48776. if (allowDuplicate) {
  48777. selection.concat(this.entries);
  48778. }
  48779. else {
  48780. selection.concatWithNoDuplicate(this.entries);
  48781. }
  48782. }
  48783. };
  48784. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  48785. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  48786. if (this.blocks) {
  48787. for (var index = 0; index < this.blocks.length; index++) {
  48788. var block = this.blocks[index];
  48789. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  48790. }
  48791. return;
  48792. }
  48793. if (allowDuplicate) {
  48794. selection.concat(this.entries);
  48795. }
  48796. else {
  48797. selection.concatWithNoDuplicate(this.entries);
  48798. }
  48799. }
  48800. };
  48801. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  48802. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  48803. if (this.blocks) {
  48804. for (var index = 0; index < this.blocks.length; index++) {
  48805. var block = this.blocks[index];
  48806. block.intersectsRay(ray, selection);
  48807. }
  48808. return;
  48809. }
  48810. selection.concatWithNoDuplicate(this.entries);
  48811. }
  48812. };
  48813. OctreeBlock.prototype.createInnerBlocks = function () {
  48814. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  48815. };
  48816. return OctreeBlock;
  48817. }());
  48818. BABYLON.OctreeBlock = OctreeBlock;
  48819. })(BABYLON || (BABYLON = {}));
  48820. //# sourceMappingURL=babylon.octreeBlock.js.map
  48821. var BABYLON;
  48822. (function (BABYLON) {
  48823. var BlurPostProcess = (function (_super) {
  48824. __extends(BlurPostProcess, _super);
  48825. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48827. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48828. _this.direction = direction;
  48829. _this.blurWidth = blurWidth;
  48830. _this.onApplyObservable.add(function (effect) {
  48831. effect.setFloat2("screenSize", _this.width, _this.height);
  48832. effect.setVector2("direction", _this.direction);
  48833. effect.setFloat("blurWidth", _this.blurWidth);
  48834. });
  48835. return _this;
  48836. }
  48837. return BlurPostProcess;
  48838. }(BABYLON.PostProcess));
  48839. BABYLON.BlurPostProcess = BlurPostProcess;
  48840. })(BABYLON || (BABYLON = {}));
  48841. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48842. var BABYLON;
  48843. (function (BABYLON) {
  48844. var RefractionPostProcess = (function (_super) {
  48845. __extends(RefractionPostProcess, _super);
  48846. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48847. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48848. _this.color = color;
  48849. _this.depth = depth;
  48850. _this.colorLevel = colorLevel;
  48851. _this.onActivateObservable.add(function (cam) {
  48852. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48853. });
  48854. _this.onApplyObservable.add(function (effect) {
  48855. effect.setColor3("baseColor", _this.color);
  48856. effect.setFloat("depth", _this.depth);
  48857. effect.setFloat("colorLevel", _this.colorLevel);
  48858. effect.setTexture("refractionSampler", _this._refRexture);
  48859. });
  48860. return _this;
  48861. }
  48862. // Methods
  48863. RefractionPostProcess.prototype.dispose = function (camera) {
  48864. if (this._refRexture) {
  48865. this._refRexture.dispose();
  48866. }
  48867. _super.prototype.dispose.call(this, camera);
  48868. };
  48869. return RefractionPostProcess;
  48870. }(BABYLON.PostProcess));
  48871. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48872. })(BABYLON || (BABYLON = {}));
  48873. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48874. var BABYLON;
  48875. (function (BABYLON) {
  48876. var BlackAndWhitePostProcess = (function (_super) {
  48877. __extends(BlackAndWhitePostProcess, _super);
  48878. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48879. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48880. }
  48881. return BlackAndWhitePostProcess;
  48882. }(BABYLON.PostProcess));
  48883. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48884. })(BABYLON || (BABYLON = {}));
  48885. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48886. var BABYLON;
  48887. (function (BABYLON) {
  48888. var ConvolutionPostProcess = (function (_super) {
  48889. __extends(ConvolutionPostProcess, _super);
  48890. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48891. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48892. _this.kernel = kernel;
  48893. _this.onApply = function (effect) {
  48894. effect.setFloat2("screenSize", _this.width, _this.height);
  48895. effect.setArray("kernel", _this.kernel);
  48896. };
  48897. return _this;
  48898. }
  48899. return ConvolutionPostProcess;
  48900. }(BABYLON.PostProcess));
  48901. // Statics
  48902. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48903. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48904. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48905. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48906. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48907. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48908. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48909. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48910. })(BABYLON || (BABYLON = {}));
  48911. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48912. var BABYLON;
  48913. (function (BABYLON) {
  48914. var FilterPostProcess = (function (_super) {
  48915. __extends(FilterPostProcess, _super);
  48916. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48917. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48918. _this.kernelMatrix = kernelMatrix;
  48919. _this.onApply = function (effect) {
  48920. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48921. };
  48922. return _this;
  48923. }
  48924. return FilterPostProcess;
  48925. }(BABYLON.PostProcess));
  48926. BABYLON.FilterPostProcess = FilterPostProcess;
  48927. })(BABYLON || (BABYLON = {}));
  48928. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48929. var BABYLON;
  48930. (function (BABYLON) {
  48931. var FxaaPostProcess = (function (_super) {
  48932. __extends(FxaaPostProcess, _super);
  48933. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48934. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48935. _this.onSizeChangedObservable.add(function () {
  48936. _this.texelWidth = 1.0 / _this.width;
  48937. _this.texelHeight = 1.0 / _this.height;
  48938. });
  48939. _this.onApplyObservable.add(function (effect) {
  48940. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48941. });
  48942. return _this;
  48943. }
  48944. return FxaaPostProcess;
  48945. }(BABYLON.PostProcess));
  48946. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48947. })(BABYLON || (BABYLON = {}));
  48948. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48949. var BABYLON;
  48950. (function (BABYLON) {
  48951. var StereoscopicInterlacePostProcess = (function (_super) {
  48952. __extends(StereoscopicInterlacePostProcess, _super);
  48953. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  48954. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  48955. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48956. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  48957. _this.onSizeChangedObservable.add(function () {
  48958. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  48959. });
  48960. _this.onApplyObservable.add(function (effect) {
  48961. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  48962. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  48963. });
  48964. return _this;
  48965. }
  48966. return StereoscopicInterlacePostProcess;
  48967. }(BABYLON.PostProcess));
  48968. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  48969. })(BABYLON || (BABYLON = {}));
  48970. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  48971. var BABYLON;
  48972. (function (BABYLON) {
  48973. var LensFlare = (function () {
  48974. function LensFlare(size, position, color, imgUrl, system) {
  48975. this.size = size;
  48976. this.position = position;
  48977. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  48978. this.dispose = function () {
  48979. if (this.texture) {
  48980. this.texture.dispose();
  48981. }
  48982. // Remove from scene
  48983. var index = this._system.lensFlares.indexOf(this);
  48984. this._system.lensFlares.splice(index, 1);
  48985. };
  48986. this.color = color || new BABYLON.Color3(1, 1, 1);
  48987. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  48988. this._system = system;
  48989. system.lensFlares.push(this);
  48990. }
  48991. return LensFlare;
  48992. }());
  48993. BABYLON.LensFlare = LensFlare;
  48994. })(BABYLON || (BABYLON = {}));
  48995. //# sourceMappingURL=babylon.lensFlare.js.map
  48996. var BABYLON;
  48997. (function (BABYLON) {
  48998. var LensFlareSystem = (function () {
  48999. function LensFlareSystem(name, emitter, scene) {
  49000. this.name = name;
  49001. this.lensFlares = new Array();
  49002. this.borderLimit = 300;
  49003. this.viewportBorder = 0;
  49004. this.layerMask = 0x0FFFFFFF;
  49005. this._vertexBuffers = {};
  49006. this._isEnabled = true;
  49007. this._scene = scene;
  49008. this._emitter = emitter;
  49009. this.id = name;
  49010. scene.lensFlareSystems.push(this);
  49011. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  49012. var engine = scene.getEngine();
  49013. // VBO
  49014. var vertices = [];
  49015. vertices.push(1, 1);
  49016. vertices.push(-1, 1);
  49017. vertices.push(-1, -1);
  49018. vertices.push(1, -1);
  49019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49020. // Indices
  49021. var indices = [];
  49022. indices.push(0);
  49023. indices.push(1);
  49024. indices.push(2);
  49025. indices.push(0);
  49026. indices.push(2);
  49027. indices.push(3);
  49028. this._indexBuffer = engine.createIndexBuffer(indices);
  49029. // Effects
  49030. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  49031. }
  49032. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  49033. get: function () {
  49034. return this._isEnabled;
  49035. },
  49036. set: function (value) {
  49037. this._isEnabled = value;
  49038. },
  49039. enumerable: true,
  49040. configurable: true
  49041. });
  49042. LensFlareSystem.prototype.getScene = function () {
  49043. return this._scene;
  49044. };
  49045. LensFlareSystem.prototype.getEmitter = function () {
  49046. return this._emitter;
  49047. };
  49048. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  49049. this._emitter = newEmitter;
  49050. };
  49051. LensFlareSystem.prototype.getEmitterPosition = function () {
  49052. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  49053. };
  49054. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  49055. var position = this.getEmitterPosition();
  49056. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  49057. this._positionX = position.x;
  49058. this._positionY = position.y;
  49059. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  49060. if (this.viewportBorder > 0) {
  49061. globalViewport.x -= this.viewportBorder;
  49062. globalViewport.y -= this.viewportBorder;
  49063. globalViewport.width += this.viewportBorder * 2;
  49064. globalViewport.height += this.viewportBorder * 2;
  49065. position.x += this.viewportBorder;
  49066. position.y += this.viewportBorder;
  49067. this._positionX += this.viewportBorder;
  49068. this._positionY += this.viewportBorder;
  49069. }
  49070. if (position.z > 0) {
  49071. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  49072. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  49073. return true;
  49074. }
  49075. return true;
  49076. }
  49077. return false;
  49078. };
  49079. LensFlareSystem.prototype._isVisible = function () {
  49080. if (!this._isEnabled) {
  49081. return false;
  49082. }
  49083. var emitterPosition = this.getEmitterPosition();
  49084. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  49085. var distance = direction.length();
  49086. direction.normalize();
  49087. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  49088. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  49089. return !pickInfo.hit || pickInfo.distance > distance;
  49090. };
  49091. LensFlareSystem.prototype.render = function () {
  49092. if (!this._effect.isReady())
  49093. return false;
  49094. var engine = this._scene.getEngine();
  49095. var viewport = this._scene.activeCamera.viewport;
  49096. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  49097. // Position
  49098. if (!this.computeEffectivePosition(globalViewport)) {
  49099. return false;
  49100. }
  49101. // Visibility
  49102. if (!this._isVisible()) {
  49103. return false;
  49104. }
  49105. // Intensity
  49106. var awayX;
  49107. var awayY;
  49108. if (this._positionX < this.borderLimit + globalViewport.x) {
  49109. awayX = this.borderLimit + globalViewport.x - this._positionX;
  49110. }
  49111. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  49112. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  49113. }
  49114. else {
  49115. awayX = 0;
  49116. }
  49117. if (this._positionY < this.borderLimit + globalViewport.y) {
  49118. awayY = this.borderLimit + globalViewport.y - this._positionY;
  49119. }
  49120. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  49121. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  49122. }
  49123. else {
  49124. awayY = 0;
  49125. }
  49126. var away = (awayX > awayY) ? awayX : awayY;
  49127. away -= this.viewportBorder;
  49128. if (away > this.borderLimit) {
  49129. away = this.borderLimit;
  49130. }
  49131. var intensity = 1.0 - (away / this.borderLimit);
  49132. if (intensity < 0) {
  49133. return false;
  49134. }
  49135. if (intensity > 1.0) {
  49136. intensity = 1.0;
  49137. }
  49138. if (this.viewportBorder > 0) {
  49139. globalViewport.x += this.viewportBorder;
  49140. globalViewport.y += this.viewportBorder;
  49141. globalViewport.width -= this.viewportBorder * 2;
  49142. globalViewport.height -= this.viewportBorder * 2;
  49143. this._positionX -= this.viewportBorder;
  49144. this._positionY -= this.viewportBorder;
  49145. }
  49146. // Position
  49147. var centerX = globalViewport.x + globalViewport.width / 2;
  49148. var centerY = globalViewport.y + globalViewport.height / 2;
  49149. var distX = centerX - this._positionX;
  49150. var distY = centerY - this._positionY;
  49151. // Effects
  49152. engine.enableEffect(this._effect);
  49153. engine.setState(false);
  49154. engine.setDepthBuffer(false);
  49155. // VBOs
  49156. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49157. // Flares
  49158. for (var index = 0; index < this.lensFlares.length; index++) {
  49159. var flare = this.lensFlares[index];
  49160. engine.setAlphaMode(flare.alphaMode);
  49161. var x = centerX - (distX * flare.position);
  49162. var y = centerY - (distY * flare.position);
  49163. var cw = flare.size;
  49164. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  49165. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  49166. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  49167. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  49168. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  49169. // Texture
  49170. this._effect.setTexture("textureSampler", flare.texture);
  49171. // Color
  49172. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  49173. // Draw order
  49174. engine.draw(true, 0, 6);
  49175. }
  49176. engine.setDepthBuffer(true);
  49177. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49178. return true;
  49179. };
  49180. LensFlareSystem.prototype.dispose = function () {
  49181. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49182. if (vertexBuffer) {
  49183. vertexBuffer.dispose();
  49184. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49185. }
  49186. if (this._indexBuffer) {
  49187. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49188. this._indexBuffer = null;
  49189. }
  49190. while (this.lensFlares.length) {
  49191. this.lensFlares[0].dispose();
  49192. }
  49193. // Remove from scene
  49194. var index = this._scene.lensFlareSystems.indexOf(this);
  49195. this._scene.lensFlareSystems.splice(index, 1);
  49196. };
  49197. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  49198. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  49199. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  49200. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  49201. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  49202. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  49203. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  49204. var parsedFlare = parsedLensFlareSystem.flares[index];
  49205. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  49206. }
  49207. return lensFlareSystem;
  49208. };
  49209. LensFlareSystem.prototype.serialize = function () {
  49210. var serializationObject = {};
  49211. serializationObject.id = this.id;
  49212. serializationObject.name = this.name;
  49213. serializationObject.emitterId = this.getEmitter().id;
  49214. serializationObject.borderLimit = this.borderLimit;
  49215. serializationObject.flares = [];
  49216. for (var index = 0; index < this.lensFlares.length; index++) {
  49217. var flare = this.lensFlares[index];
  49218. serializationObject.flares.push({
  49219. size: flare.size,
  49220. position: flare.position,
  49221. color: flare.color.asArray(),
  49222. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  49223. });
  49224. }
  49225. return serializationObject;
  49226. };
  49227. return LensFlareSystem;
  49228. }());
  49229. BABYLON.LensFlareSystem = LensFlareSystem;
  49230. })(BABYLON || (BABYLON = {}));
  49231. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  49232. /// <reference path="babylon.freeCamera.ts" />
  49233. var BABYLON;
  49234. (function (BABYLON) {
  49235. // We're mainly based on the logic defined into the FreeCamera code
  49236. var DeviceOrientationCamera = (function (_super) {
  49237. __extends(DeviceOrientationCamera, _super);
  49238. function DeviceOrientationCamera(name, position, scene) {
  49239. var _this = _super.call(this, name, position, scene) || this;
  49240. _this._quaternionCache = new BABYLON.Quaternion();
  49241. _this.inputs.addDeviceOrientation();
  49242. return _this;
  49243. }
  49244. DeviceOrientationCamera.prototype.getClassName = function () {
  49245. return "DeviceOrientationCamera";
  49246. };
  49247. DeviceOrientationCamera.prototype._checkInputs = function () {
  49248. _super.prototype._checkInputs.call(this);
  49249. this._quaternionCache.copyFrom(this.rotationQuaternion);
  49250. if (this._initialQuaternion) {
  49251. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49252. }
  49253. };
  49254. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  49255. var _this = this;
  49256. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  49257. //can only work if this camera has a rotation quaternion already.
  49258. if (!this.rotationQuaternion)
  49259. return;
  49260. if (!this._initialQuaternion) {
  49261. this._initialQuaternion = new BABYLON.Quaternion();
  49262. }
  49263. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  49264. ['x', 'y', 'z'].forEach(function (axisName) {
  49265. if (!axis[axisName]) {
  49266. _this._initialQuaternion[axisName] = 0;
  49267. }
  49268. else {
  49269. _this._initialQuaternion[axisName] *= -1;
  49270. }
  49271. });
  49272. this._initialQuaternion.normalize();
  49273. //force rotation update
  49274. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49275. };
  49276. return DeviceOrientationCamera;
  49277. }(BABYLON.FreeCamera));
  49278. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  49279. })(BABYLON || (BABYLON = {}));
  49280. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  49281. var BABYLON;
  49282. (function (BABYLON) {
  49283. var VRDeviceOrientationFreeCamera = (function (_super) {
  49284. __extends(VRDeviceOrientationFreeCamera, _super);
  49285. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49286. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49287. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49288. var _this = _super.call(this, name, position, scene) || this;
  49289. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49290. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49291. return _this;
  49292. }
  49293. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  49294. return "VRDeviceOrientationFreeCamera";
  49295. };
  49296. return VRDeviceOrientationFreeCamera;
  49297. }(BABYLON.DeviceOrientationCamera));
  49298. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  49299. var VRDeviceOrientationGamepadCamera = (function (_super) {
  49300. __extends(VRDeviceOrientationGamepadCamera, _super);
  49301. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49302. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49303. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49304. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  49305. _this.inputs.addGamepad();
  49306. return _this;
  49307. }
  49308. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  49309. return "VRDeviceOrientationGamepadCamera";
  49310. };
  49311. return VRDeviceOrientationGamepadCamera;
  49312. }(VRDeviceOrientationFreeCamera));
  49313. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  49314. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  49315. __extends(VRDeviceOrientationArcRotateCamera, _super);
  49316. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  49317. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49318. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49319. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  49320. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49321. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49322. _this.inputs.addVRDeviceOrientation();
  49323. return _this;
  49324. }
  49325. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  49326. return "VRDeviceOrientationArcRotateCamera";
  49327. };
  49328. return VRDeviceOrientationArcRotateCamera;
  49329. }(BABYLON.ArcRotateCamera));
  49330. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  49331. })(BABYLON || (BABYLON = {}));
  49332. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  49333. /// <reference path="babylon.touchCamera.ts" />
  49334. var BABYLON;
  49335. (function (BABYLON) {
  49336. // We're mainly based on the logic defined into the FreeCamera code
  49337. var UniversalCamera = (function (_super) {
  49338. __extends(UniversalCamera, _super);
  49339. //-- end properties for backward compatibility for inputs
  49340. function UniversalCamera(name, position, scene) {
  49341. var _this = _super.call(this, name, position, scene) || this;
  49342. _this.inputs.addGamepad();
  49343. return _this;
  49344. }
  49345. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49346. //-- Begin properties for backward compatibility for inputs
  49347. get: function () {
  49348. var gamepad = this.inputs.attached["gamepad"];
  49349. if (gamepad)
  49350. return gamepad.gamepadAngularSensibility;
  49351. },
  49352. set: function (value) {
  49353. var gamepad = this.inputs.attached["gamepad"];
  49354. if (gamepad)
  49355. gamepad.gamepadAngularSensibility = value;
  49356. },
  49357. enumerable: true,
  49358. configurable: true
  49359. });
  49360. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49361. get: function () {
  49362. var gamepad = this.inputs.attached["gamepad"];
  49363. if (gamepad)
  49364. return gamepad.gamepadMoveSensibility;
  49365. },
  49366. set: function (value) {
  49367. var gamepad = this.inputs.attached["gamepad"];
  49368. if (gamepad)
  49369. gamepad.gamepadMoveSensibility = value;
  49370. },
  49371. enumerable: true,
  49372. configurable: true
  49373. });
  49374. UniversalCamera.prototype.getClassName = function () {
  49375. return "UniversalCamera";
  49376. };
  49377. return UniversalCamera;
  49378. }(BABYLON.TouchCamera));
  49379. BABYLON.UniversalCamera = UniversalCamera;
  49380. })(BABYLON || (BABYLON = {}));
  49381. //# sourceMappingURL=babylon.universalCamera.js.map
  49382. var BABYLON;
  49383. (function (BABYLON) {
  49384. var Gamepads = (function () {
  49385. function Gamepads(ongamedpadconnected) {
  49386. var _this = this;
  49387. this.babylonGamepads = [];
  49388. this.oneGamepadConnected = false;
  49389. this.isMonitoring = false;
  49390. this.gamepadEventSupported = 'GamepadEvent' in window;
  49391. this.gamepadSupportAvailable = (navigator.getGamepads ||
  49392. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  49393. this._callbackGamepadConnected = ongamedpadconnected;
  49394. if (this.gamepadSupportAvailable) {
  49395. // Checking if the gamepad connected event is supported (like in Firefox)
  49396. if (this.gamepadEventSupported) {
  49397. this._onGamepadConnectedEvent = function (evt) {
  49398. _this._onGamepadConnected(evt);
  49399. };
  49400. this._onGamepadDisonnectedEvent = function (evt) {
  49401. _this._onGamepadDisconnected(evt);
  49402. };
  49403. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49404. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49405. }
  49406. else {
  49407. this._startMonitoringGamepads();
  49408. }
  49409. }
  49410. }
  49411. Gamepads.prototype.dispose = function () {
  49412. if (Gamepads.gamepadDOMInfo) {
  49413. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49414. }
  49415. if (this._onGamepadConnectedEvent) {
  49416. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49417. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49418. this._onGamepadConnectedEvent = null;
  49419. this._onGamepadDisonnectedEvent = null;
  49420. }
  49421. };
  49422. Gamepads.prototype._onGamepadConnected = function (evt) {
  49423. var newGamepad = this._addNewGamepad(evt.gamepad);
  49424. if (this._callbackGamepadConnected)
  49425. this._callbackGamepadConnected(newGamepad);
  49426. this._startMonitoringGamepads();
  49427. };
  49428. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49429. if (!this.oneGamepadConnected) {
  49430. this.oneGamepadConnected = true;
  49431. if (Gamepads.gamepadDOMInfo) {
  49432. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49433. Gamepads.gamepadDOMInfo = null;
  49434. }
  49435. }
  49436. var newGamepad;
  49437. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49438. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49439. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49440. }
  49441. else {
  49442. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49443. }
  49444. this.babylonGamepads.push(newGamepad);
  49445. return newGamepad;
  49446. };
  49447. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  49448. // Remove the gamepad from the list of gamepads to monitor.
  49449. for (var i in this.babylonGamepads) {
  49450. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  49451. this.babylonGamepads.splice(+i, 1);
  49452. break;
  49453. }
  49454. }
  49455. // If no gamepads are left, stop the polling loop.
  49456. if (this.babylonGamepads.length == 0) {
  49457. this._stopMonitoringGamepads();
  49458. }
  49459. };
  49460. Gamepads.prototype._startMonitoringGamepads = function () {
  49461. if (!this.isMonitoring) {
  49462. this.isMonitoring = true;
  49463. this._checkGamepadsStatus();
  49464. }
  49465. };
  49466. Gamepads.prototype._stopMonitoringGamepads = function () {
  49467. this.isMonitoring = false;
  49468. };
  49469. Gamepads.prototype._checkGamepadsStatus = function () {
  49470. var _this = this;
  49471. // updating gamepad objects
  49472. this._updateGamepadObjects();
  49473. for (var i in this.babylonGamepads) {
  49474. this.babylonGamepads[i].update();
  49475. }
  49476. if (this.isMonitoring) {
  49477. if (window.requestAnimationFrame) {
  49478. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49479. }
  49480. else if (window.mozRequestAnimationFrame) {
  49481. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49482. }
  49483. else if (window.webkitRequestAnimationFrame) {
  49484. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49485. }
  49486. }
  49487. };
  49488. // This function is called only on Chrome, which does not yet support
  49489. // connection/disconnection events, but requires you to monitor
  49490. // an array for changes.
  49491. Gamepads.prototype._updateGamepadObjects = function () {
  49492. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49493. for (var i = 0; i < gamepads.length; i++) {
  49494. if (gamepads[i]) {
  49495. if (!(gamepads[i].index in this.babylonGamepads)) {
  49496. var newGamepad = this._addNewGamepad(gamepads[i]);
  49497. if (this._callbackGamepadConnected) {
  49498. this._callbackGamepadConnected(newGamepad);
  49499. }
  49500. }
  49501. else {
  49502. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49503. }
  49504. }
  49505. }
  49506. };
  49507. return Gamepads;
  49508. }());
  49509. BABYLON.Gamepads = Gamepads;
  49510. var StickValues = (function () {
  49511. function StickValues(x, y) {
  49512. this.x = x;
  49513. this.y = y;
  49514. }
  49515. return StickValues;
  49516. }());
  49517. BABYLON.StickValues = StickValues;
  49518. var Gamepad = (function () {
  49519. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49520. if (leftStickX === void 0) { leftStickX = 0; }
  49521. if (leftStickY === void 0) { leftStickY = 1; }
  49522. if (rightStickX === void 0) { rightStickX = 2; }
  49523. if (rightStickY === void 0) { rightStickY = 3; }
  49524. this.id = id;
  49525. this.index = index;
  49526. this.browserGamepad = browserGamepad;
  49527. this._leftStickAxisX = leftStickX;
  49528. this._leftStickAxisY = leftStickY;
  49529. this._rightStickAxisX = rightStickX;
  49530. this._rightStickAxisY = rightStickY;
  49531. if (this.browserGamepad.axes.length >= 2) {
  49532. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49533. }
  49534. if (this.browserGamepad.axes.length >= 4) {
  49535. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49536. }
  49537. }
  49538. Gamepad.prototype.onleftstickchanged = function (callback) {
  49539. this._onleftstickchanged = callback;
  49540. };
  49541. Gamepad.prototype.onrightstickchanged = function (callback) {
  49542. this._onrightstickchanged = callback;
  49543. };
  49544. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49545. get: function () {
  49546. return this._leftStick;
  49547. },
  49548. set: function (newValues) {
  49549. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49550. this._onleftstickchanged(newValues);
  49551. }
  49552. this._leftStick = newValues;
  49553. },
  49554. enumerable: true,
  49555. configurable: true
  49556. });
  49557. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49558. get: function () {
  49559. return this._rightStick;
  49560. },
  49561. set: function (newValues) {
  49562. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49563. this._onrightstickchanged(newValues);
  49564. }
  49565. this._rightStick = newValues;
  49566. },
  49567. enumerable: true,
  49568. configurable: true
  49569. });
  49570. Gamepad.prototype.update = function () {
  49571. if (this._leftStick) {
  49572. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49573. }
  49574. if (this._rightStick) {
  49575. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49576. }
  49577. };
  49578. return Gamepad;
  49579. }());
  49580. BABYLON.Gamepad = Gamepad;
  49581. var GenericPad = (function (_super) {
  49582. __extends(GenericPad, _super);
  49583. function GenericPad(id, index, gamepad) {
  49584. var _this = _super.call(this, id, index, gamepad) || this;
  49585. _this.id = id;
  49586. _this.index = index;
  49587. _this.gamepad = gamepad;
  49588. _this._buttons = new Array(gamepad.buttons.length);
  49589. return _this;
  49590. }
  49591. GenericPad.prototype.onbuttondown = function (callback) {
  49592. this._onbuttondown = callback;
  49593. };
  49594. GenericPad.prototype.onbuttonup = function (callback) {
  49595. this._onbuttonup = callback;
  49596. };
  49597. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49598. if (newValue !== currentValue) {
  49599. if (this._onbuttondown && newValue === 1) {
  49600. this._onbuttondown(buttonIndex);
  49601. }
  49602. if (this._onbuttonup && newValue === 0) {
  49603. this._onbuttonup(buttonIndex);
  49604. }
  49605. }
  49606. return newValue;
  49607. };
  49608. GenericPad.prototype.update = function () {
  49609. _super.prototype.update.call(this);
  49610. for (var index = 0; index < this._buttons.length; index++) {
  49611. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  49612. }
  49613. };
  49614. return GenericPad;
  49615. }(Gamepad));
  49616. BABYLON.GenericPad = GenericPad;
  49617. var Xbox360Button;
  49618. (function (Xbox360Button) {
  49619. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49620. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49621. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49622. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49623. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49624. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49625. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49626. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49627. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49628. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49629. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49630. var Xbox360Dpad;
  49631. (function (Xbox360Dpad) {
  49632. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49633. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49634. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49635. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49636. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49637. var Xbox360Pad = (function (_super) {
  49638. __extends(Xbox360Pad, _super);
  49639. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49640. if (xboxOne === void 0) { xboxOne = false; }
  49641. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49642. _this._leftTrigger = 0;
  49643. _this._rightTrigger = 0;
  49644. _this._buttonA = 0;
  49645. _this._buttonB = 0;
  49646. _this._buttonX = 0;
  49647. _this._buttonY = 0;
  49648. _this._buttonBack = 0;
  49649. _this._buttonStart = 0;
  49650. _this._buttonLB = 0;
  49651. _this._buttonRB = 0;
  49652. _this._buttonLeftStick = 0;
  49653. _this._buttonRightStick = 0;
  49654. _this._dPadUp = 0;
  49655. _this._dPadDown = 0;
  49656. _this._dPadLeft = 0;
  49657. _this._dPadRight = 0;
  49658. _this._isXboxOnePad = false;
  49659. _this._isXboxOnePad = xboxOne;
  49660. return _this;
  49661. }
  49662. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49663. this._onlefttriggerchanged = callback;
  49664. };
  49665. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49666. this._onrighttriggerchanged = callback;
  49667. };
  49668. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49669. get: function () {
  49670. return this._leftTrigger;
  49671. },
  49672. set: function (newValue) {
  49673. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49674. this._onlefttriggerchanged(newValue);
  49675. }
  49676. this._leftTrigger = newValue;
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49682. get: function () {
  49683. return this._rightTrigger;
  49684. },
  49685. set: function (newValue) {
  49686. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49687. this._onrighttriggerchanged(newValue);
  49688. }
  49689. this._rightTrigger = newValue;
  49690. },
  49691. enumerable: true,
  49692. configurable: true
  49693. });
  49694. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49695. this._onbuttondown = callback;
  49696. };
  49697. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49698. this._onbuttonup = callback;
  49699. };
  49700. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49701. this._ondpaddown = callback;
  49702. };
  49703. Xbox360Pad.prototype.ondpadup = function (callback) {
  49704. this._ondpadup = callback;
  49705. };
  49706. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49707. if (newValue !== currentValue) {
  49708. if (this._onbuttondown && newValue === 1) {
  49709. this._onbuttondown(buttonType);
  49710. }
  49711. if (this._onbuttonup && newValue === 0) {
  49712. this._onbuttonup(buttonType);
  49713. }
  49714. }
  49715. return newValue;
  49716. };
  49717. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49718. if (newValue !== currentValue) {
  49719. if (this._ondpaddown && newValue === 1) {
  49720. this._ondpaddown(buttonType);
  49721. }
  49722. if (this._ondpadup && newValue === 0) {
  49723. this._ondpadup(buttonType);
  49724. }
  49725. }
  49726. return newValue;
  49727. };
  49728. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49729. get: function () {
  49730. return this._buttonA;
  49731. },
  49732. set: function (value) {
  49733. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49734. },
  49735. enumerable: true,
  49736. configurable: true
  49737. });
  49738. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  49739. get: function () {
  49740. return this._buttonB;
  49741. },
  49742. set: function (value) {
  49743. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  49744. },
  49745. enumerable: true,
  49746. configurable: true
  49747. });
  49748. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  49749. get: function () {
  49750. return this._buttonX;
  49751. },
  49752. set: function (value) {
  49753. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  49759. get: function () {
  49760. return this._buttonY;
  49761. },
  49762. set: function (value) {
  49763. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  49764. },
  49765. enumerable: true,
  49766. configurable: true
  49767. });
  49768. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  49769. get: function () {
  49770. return this._buttonStart;
  49771. },
  49772. set: function (value) {
  49773. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  49774. },
  49775. enumerable: true,
  49776. configurable: true
  49777. });
  49778. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  49779. get: function () {
  49780. return this._buttonBack;
  49781. },
  49782. set: function (value) {
  49783. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  49784. },
  49785. enumerable: true,
  49786. configurable: true
  49787. });
  49788. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  49789. get: function () {
  49790. return this._buttonLB;
  49791. },
  49792. set: function (value) {
  49793. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  49794. },
  49795. enumerable: true,
  49796. configurable: true
  49797. });
  49798. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  49799. get: function () {
  49800. return this._buttonRB;
  49801. },
  49802. set: function (value) {
  49803. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49804. },
  49805. enumerable: true,
  49806. configurable: true
  49807. });
  49808. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49809. get: function () {
  49810. return this._buttonLeftStick;
  49811. },
  49812. set: function (value) {
  49813. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49814. },
  49815. enumerable: true,
  49816. configurable: true
  49817. });
  49818. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49819. get: function () {
  49820. return this._buttonRightStick;
  49821. },
  49822. set: function (value) {
  49823. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49824. },
  49825. enumerable: true,
  49826. configurable: true
  49827. });
  49828. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49829. get: function () {
  49830. return this._dPadUp;
  49831. },
  49832. set: function (value) {
  49833. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49839. get: function () {
  49840. return this._dPadDown;
  49841. },
  49842. set: function (value) {
  49843. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49844. },
  49845. enumerable: true,
  49846. configurable: true
  49847. });
  49848. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49849. get: function () {
  49850. return this._dPadLeft;
  49851. },
  49852. set: function (value) {
  49853. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49854. },
  49855. enumerable: true,
  49856. configurable: true
  49857. });
  49858. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49859. get: function () {
  49860. return this._dPadRight;
  49861. },
  49862. set: function (value) {
  49863. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49864. },
  49865. enumerable: true,
  49866. configurable: true
  49867. });
  49868. Xbox360Pad.prototype.update = function () {
  49869. _super.prototype.update.call(this);
  49870. if (this._isXboxOnePad) {
  49871. this.buttonA = this.browserGamepad.buttons[0].value;
  49872. this.buttonB = this.browserGamepad.buttons[1].value;
  49873. this.buttonX = this.browserGamepad.buttons[2].value;
  49874. this.buttonY = this.browserGamepad.buttons[3].value;
  49875. this.buttonLB = this.browserGamepad.buttons[4].value;
  49876. this.buttonRB = this.browserGamepad.buttons[5].value;
  49877. this.leftTrigger = this.browserGamepad.axes[2];
  49878. this.rightTrigger = this.browserGamepad.axes[5];
  49879. this.buttonBack = this.browserGamepad.buttons[9].value;
  49880. this.buttonStart = this.browserGamepad.buttons[8].value;
  49881. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  49882. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  49883. this.dPadUp = this.browserGamepad.buttons[11].value;
  49884. this.dPadDown = this.browserGamepad.buttons[12].value;
  49885. this.dPadLeft = this.browserGamepad.buttons[13].value;
  49886. this.dPadRight = this.browserGamepad.buttons[14].value;
  49887. }
  49888. else {
  49889. this.buttonA = this.browserGamepad.buttons[0].value;
  49890. this.buttonB = this.browserGamepad.buttons[1].value;
  49891. this.buttonX = this.browserGamepad.buttons[2].value;
  49892. this.buttonY = this.browserGamepad.buttons[3].value;
  49893. this.buttonLB = this.browserGamepad.buttons[4].value;
  49894. this.buttonRB = this.browserGamepad.buttons[5].value;
  49895. this.leftTrigger = this.browserGamepad.buttons[6].value;
  49896. this.rightTrigger = this.browserGamepad.buttons[7].value;
  49897. this.buttonBack = this.browserGamepad.buttons[8].value;
  49898. this.buttonStart = this.browserGamepad.buttons[9].value;
  49899. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  49900. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  49901. this.dPadUp = this.browserGamepad.buttons[12].value;
  49902. this.dPadDown = this.browserGamepad.buttons[13].value;
  49903. this.dPadLeft = this.browserGamepad.buttons[14].value;
  49904. this.dPadRight = this.browserGamepad.buttons[15].value;
  49905. }
  49906. };
  49907. return Xbox360Pad;
  49908. }(Gamepad));
  49909. BABYLON.Xbox360Pad = Xbox360Pad;
  49910. })(BABYLON || (BABYLON = {}));
  49911. //# sourceMappingURL=babylon.gamepads.js.map
  49912. /// <reference path="babylon.universalCamera.ts" />
  49913. var BABYLON;
  49914. (function (BABYLON) {
  49915. // We're mainly based on the logic defined into the FreeCamera code
  49916. var GamepadCamera = (function (_super) {
  49917. __extends(GamepadCamera, _super);
  49918. //-- end properties for backward compatibility for inputs
  49919. function GamepadCamera(name, position, scene) {
  49920. var _this;
  49921. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  49922. _this = _super.call(this, name, position, scene) || this;
  49923. return _this;
  49924. }
  49925. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49926. //-- Begin properties for backward compatibility for inputs
  49927. get: function () {
  49928. var gamepad = this.inputs.attached["gamepad"];
  49929. if (gamepad)
  49930. return gamepad.gamepadAngularSensibility;
  49931. },
  49932. set: function (value) {
  49933. var gamepad = this.inputs.attached["gamepad"];
  49934. if (gamepad)
  49935. gamepad.gamepadAngularSensibility = value;
  49936. },
  49937. enumerable: true,
  49938. configurable: true
  49939. });
  49940. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  49941. get: function () {
  49942. var gamepad = this.inputs.attached["gamepad"];
  49943. if (gamepad)
  49944. return gamepad.gamepadMoveSensibility;
  49945. },
  49946. set: function (value) {
  49947. var gamepad = this.inputs.attached["gamepad"];
  49948. if (gamepad)
  49949. gamepad.gamepadMoveSensibility = value;
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. GamepadCamera.prototype.getClassName = function () {
  49955. return "GamepadCamera";
  49956. };
  49957. return GamepadCamera;
  49958. }(BABYLON.UniversalCamera));
  49959. BABYLON.GamepadCamera = GamepadCamera;
  49960. })(BABYLON || (BABYLON = {}));
  49961. //# sourceMappingURL=babylon.gamepadCamera.js.map
  49962. var BABYLON;
  49963. (function (BABYLON) {
  49964. var Analyser = (function () {
  49965. function Analyser(scene) {
  49966. this.SMOOTHING = 0.75;
  49967. this.FFT_SIZE = 512;
  49968. this.BARGRAPHAMPLITUDE = 256;
  49969. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49970. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49971. this._scene = scene;
  49972. this._audioEngine = BABYLON.Engine.audioEngine;
  49973. if (this._audioEngine.canUseWebAudio) {
  49974. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49975. this._webAudioAnalyser.minDecibels = -140;
  49976. this._webAudioAnalyser.maxDecibels = 0;
  49977. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49978. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49979. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49980. }
  49981. }
  49982. Analyser.prototype.getFrequencyBinCount = function () {
  49983. if (this._audioEngine.canUseWebAudio) {
  49984. return this._webAudioAnalyser.frequencyBinCount;
  49985. }
  49986. else {
  49987. return 0;
  49988. }
  49989. };
  49990. Analyser.prototype.getByteFrequencyData = function () {
  49991. if (this._audioEngine.canUseWebAudio) {
  49992. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49993. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49994. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49995. }
  49996. return this._byteFreqs;
  49997. };
  49998. Analyser.prototype.getByteTimeDomainData = function () {
  49999. if (this._audioEngine.canUseWebAudio) {
  50000. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50001. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50002. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50003. }
  50004. return this._byteTime;
  50005. };
  50006. Analyser.prototype.getFloatFrequencyData = function () {
  50007. if (this._audioEngine.canUseWebAudio) {
  50008. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50009. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50010. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50011. }
  50012. return this._floatFreqs;
  50013. };
  50014. Analyser.prototype.drawDebugCanvas = function () {
  50015. var _this = this;
  50016. if (this._audioEngine.canUseWebAudio) {
  50017. if (!this._debugCanvas) {
  50018. this._debugCanvas = document.createElement("canvas");
  50019. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50020. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50021. this._debugCanvas.style.position = "absolute";
  50022. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50023. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50024. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50025. document.body.appendChild(this._debugCanvas);
  50026. this._registerFunc = function () {
  50027. _this.drawDebugCanvas();
  50028. };
  50029. this._scene.registerBeforeRender(this._registerFunc);
  50030. }
  50031. if (this._registerFunc) {
  50032. var workingArray = this.getByteFrequencyData();
  50033. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50034. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50035. // Draw the frequency domain chart.
  50036. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50037. var value = workingArray[i];
  50038. var percent = value / this.BARGRAPHAMPLITUDE;
  50039. var height = this.DEBUGCANVASSIZE.height * percent;
  50040. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50041. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50042. var hue = i / this.getFrequencyBinCount() * 360;
  50043. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50044. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50045. }
  50046. }
  50047. }
  50048. };
  50049. Analyser.prototype.stopDebugCanvas = function () {
  50050. if (this._debugCanvas) {
  50051. this._scene.unregisterBeforeRender(this._registerFunc);
  50052. this._registerFunc = null;
  50053. document.body.removeChild(this._debugCanvas);
  50054. this._debugCanvas = null;
  50055. this._debugCanvasContext = null;
  50056. }
  50057. };
  50058. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50059. if (this._audioEngine.canUseWebAudio) {
  50060. inputAudioNode.connect(this._webAudioAnalyser);
  50061. this._webAudioAnalyser.connect(outputAudioNode);
  50062. }
  50063. };
  50064. Analyser.prototype.dispose = function () {
  50065. if (this._audioEngine.canUseWebAudio) {
  50066. this._webAudioAnalyser.disconnect();
  50067. }
  50068. };
  50069. return Analyser;
  50070. }());
  50071. BABYLON.Analyser = Analyser;
  50072. })(BABYLON || (BABYLON = {}));
  50073. //# sourceMappingURL=babylon.analyser.js.map
  50074. var BABYLON;
  50075. (function (BABYLON) {
  50076. var DepthRenderer = (function () {
  50077. function DepthRenderer(scene, type) {
  50078. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  50079. var _this = this;
  50080. this._viewMatrix = BABYLON.Matrix.Zero();
  50081. this._projectionMatrix = BABYLON.Matrix.Zero();
  50082. this._transformMatrix = BABYLON.Matrix.Zero();
  50083. this._worldViewProjection = BABYLON.Matrix.Zero();
  50084. this._scene = scene;
  50085. var engine = scene.getEngine();
  50086. // Render target
  50087. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  50088. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50089. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50090. this._depthMap.refreshRate = 1;
  50091. this._depthMap.renderParticles = false;
  50092. this._depthMap.renderList = null;
  50093. // set default depth value to 1.0 (far away)
  50094. this._depthMap.onClearObservable.add(function (engine) {
  50095. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50096. });
  50097. // Custom render function
  50098. var renderSubMesh = function (subMesh) {
  50099. var mesh = subMesh.getRenderingMesh();
  50100. var scene = _this._scene;
  50101. var engine = scene.getEngine();
  50102. // Culling
  50103. engine.setState(subMesh.getMaterial().backFaceCulling);
  50104. // Managing instances
  50105. var batch = mesh._getInstancesRenderList(subMesh._id);
  50106. if (batch.mustReturn) {
  50107. return;
  50108. }
  50109. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50110. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50111. engine.enableEffect(_this._effect);
  50112. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50113. var material = subMesh.getMaterial();
  50114. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50115. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  50116. // Alpha test
  50117. if (material && material.needAlphaTesting()) {
  50118. var alphaTexture = material.getAlphaTestTexture();
  50119. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50120. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50121. }
  50122. // Bones
  50123. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50124. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50125. }
  50126. // Draw
  50127. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50128. }
  50129. };
  50130. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50131. var index;
  50132. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50133. renderSubMesh(opaqueSubMeshes.data[index]);
  50134. }
  50135. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50136. renderSubMesh(alphaTestSubMeshes.data[index]);
  50137. }
  50138. };
  50139. }
  50140. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  50141. var material = subMesh.getMaterial();
  50142. if (material.disableDepthWrite) {
  50143. return false;
  50144. }
  50145. var defines = [];
  50146. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50147. var mesh = subMesh.getMesh();
  50148. var scene = mesh.getScene();
  50149. // Alpha test
  50150. if (material && material.needAlphaTesting()) {
  50151. defines.push("#define ALPHATEST");
  50152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50153. attribs.push(BABYLON.VertexBuffer.UVKind);
  50154. defines.push("#define UV1");
  50155. }
  50156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50157. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50158. defines.push("#define UV2");
  50159. }
  50160. }
  50161. // Bones
  50162. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50165. if (mesh.numBoneInfluencers > 4) {
  50166. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50167. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50168. }
  50169. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50170. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50171. }
  50172. else {
  50173. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50174. }
  50175. // Instances
  50176. if (useInstances) {
  50177. defines.push("#define INSTANCES");
  50178. attribs.push("world0");
  50179. attribs.push("world1");
  50180. attribs.push("world2");
  50181. attribs.push("world3");
  50182. }
  50183. // Get correct effect
  50184. var join = defines.join("\n");
  50185. if (this._cachedDefines !== join) {
  50186. this._cachedDefines = join;
  50187. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  50188. }
  50189. return this._effect.isReady();
  50190. };
  50191. DepthRenderer.prototype.getDepthMap = function () {
  50192. return this._depthMap;
  50193. };
  50194. // Methods
  50195. DepthRenderer.prototype.dispose = function () {
  50196. this._depthMap.dispose();
  50197. };
  50198. return DepthRenderer;
  50199. }());
  50200. BABYLON.DepthRenderer = DepthRenderer;
  50201. })(BABYLON || (BABYLON = {}));
  50202. //# sourceMappingURL=babylon.depthRenderer.js.map
  50203. var BABYLON;
  50204. (function (BABYLON) {
  50205. var SSAORenderingPipeline = (function (_super) {
  50206. __extends(SSAORenderingPipeline, _super);
  50207. /**
  50208. * @constructor
  50209. * @param {string} name - The rendering pipeline name
  50210. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50211. * @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 }
  50212. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50213. */
  50214. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  50215. var _this = _super.call(this, scene.getEngine(), name) || this;
  50216. // Members
  50217. /**
  50218. * The PassPostProcess id in the pipeline that contains the original scene color
  50219. * @type {string}
  50220. */
  50221. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50222. /**
  50223. * The SSAO PostProcess id in the pipeline
  50224. * @type {string}
  50225. */
  50226. _this.SSAORenderEffect = "SSAORenderEffect";
  50227. /**
  50228. * The horizontal blur PostProcess id in the pipeline
  50229. * @type {string}
  50230. */
  50231. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50232. /**
  50233. * The vertical blur PostProcess id in the pipeline
  50234. * @type {string}
  50235. */
  50236. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50237. /**
  50238. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50239. * @type {string}
  50240. */
  50241. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50242. /**
  50243. * The output strength of the SSAO post-process. Default value is 1.0.
  50244. * @type {number}
  50245. */
  50246. _this.totalStrength = 1.0;
  50247. /**
  50248. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  50249. * @type {number}
  50250. */
  50251. _this.radius = 0.0001;
  50252. /**
  50253. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  50254. * Must not be equal to fallOff and superior to fallOff.
  50255. * Default value is 0.975
  50256. * @type {number}
  50257. */
  50258. _this.area = 0.0075;
  50259. /**
  50260. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  50261. * Must not be equal to area and inferior to area.
  50262. * Default value is 0.0
  50263. * @type {number}
  50264. */
  50265. _this.fallOff = 0.000001;
  50266. /**
  50267. * The base color of the SSAO post-process
  50268. * The final result is "base + ssao" between [0, 1]
  50269. * @type {number}
  50270. */
  50271. _this.base = 0.5;
  50272. _this._firstUpdate = true;
  50273. _this._scene = scene;
  50274. // Set up assets
  50275. _this._createRandomTexture();
  50276. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50277. var ssaoRatio = ratio.ssaoRatio || ratio;
  50278. var combineRatio = ratio.combineRatio || ratio;
  50279. _this._ratio = {
  50280. ssaoRatio: ssaoRatio,
  50281. combineRatio: combineRatio
  50282. };
  50283. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50284. _this._createSSAOPostProcess(ssaoRatio);
  50285. _this._createBlurPostProcess(ssaoRatio);
  50286. _this._createSSAOCombinePostProcess(combineRatio);
  50287. // Set up pipeline
  50288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50293. // Finish
  50294. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50295. if (cameras)
  50296. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50297. return _this;
  50298. }
  50299. // Public Methods
  50300. /**
  50301. * Returns the horizontal blur PostProcess
  50302. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  50303. */
  50304. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  50305. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  50306. return null;
  50307. };
  50308. /**
  50309. * Returns the vertical blur PostProcess
  50310. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  50311. */
  50312. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  50313. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  50314. return null;
  50315. };
  50316. /**
  50317. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50318. */
  50319. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50320. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50321. for (var i = 0; i < this._scene.cameras.length; i++) {
  50322. var camera = this._scene.cameras[i];
  50323. this._originalColorPostProcess.dispose(camera);
  50324. this._ssaoPostProcess.dispose(camera);
  50325. this._blurHPostProcess.dispose(camera);
  50326. this._blurVPostProcess.dispose(camera);
  50327. this._ssaoCombinePostProcess.dispose(camera);
  50328. }
  50329. this._randomTexture.dispose();
  50330. if (disableDepthRender)
  50331. this._scene.disableDepthRenderer();
  50332. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50333. _super.prototype.dispose.call(this);
  50334. };
  50335. // Private Methods
  50336. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  50337. var _this = this;
  50338. /*
  50339. var samplerOffsets = [
  50340. -8.0, -6.0, -4.0, -2.0,
  50341. 0.0,
  50342. 2.0, 4.0, 6.0, 8.0
  50343. ];
  50344. */
  50345. var samples = 16;
  50346. var samplerOffsets = [];
  50347. for (var i = -8; i < 8; i++) {
  50348. samplerOffsets.push(i * 2);
  50349. }
  50350. 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");
  50351. this._blurHPostProcess.onApply = function (effect) {
  50352. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50353. effect.setTexture("depthSampler", _this._depthTexture);
  50354. if (_this._firstUpdate) {
  50355. effect.setArray("samplerOffsets", samplerOffsets);
  50356. }
  50357. };
  50358. 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");
  50359. this._blurVPostProcess.onApply = function (effect) {
  50360. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50361. effect.setTexture("depthSampler", _this._depthTexture);
  50362. if (_this._firstUpdate) {
  50363. effect.setArray("samplerOffsets", samplerOffsets);
  50364. _this._firstUpdate = false;
  50365. }
  50366. };
  50367. };
  50368. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50369. var _this = this;
  50370. var numSamples = 16;
  50371. var sampleSphere = [
  50372. 0.5381, 0.1856, -0.4319,
  50373. 0.1379, 0.2486, 0.4430,
  50374. 0.3371, 0.5679, -0.0057,
  50375. -0.6999, -0.0451, -0.0019,
  50376. 0.0689, -0.1598, -0.8547,
  50377. 0.0560, 0.0069, -0.1843,
  50378. -0.0146, 0.1402, 0.0762,
  50379. 0.0100, -0.1924, -0.0344,
  50380. -0.3577, -0.5301, -0.4358,
  50381. -0.3169, 0.1063, 0.0158,
  50382. 0.0103, -0.5869, 0.0046,
  50383. -0.0897, -0.4940, 0.3287,
  50384. 0.7119, -0.0154, -0.0918,
  50385. -0.0533, 0.0596, -0.5411,
  50386. 0.0352, -0.0631, 0.5460,
  50387. -0.4776, 0.2847, -0.0271
  50388. ];
  50389. var samplesFactor = 1.0 / numSamples;
  50390. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  50391. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50392. "area", "fallOff", "base", "range", "viewport"
  50393. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50394. var viewport = new BABYLON.Vector2(0, 0);
  50395. this._ssaoPostProcess.onApply = function (effect) {
  50396. if (_this._firstUpdate) {
  50397. effect.setArray3("sampleSphere", sampleSphere);
  50398. effect.setFloat("samplesFactor", samplesFactor);
  50399. effect.setFloat("randTextureTiles", 4.0);
  50400. }
  50401. effect.setFloat("totalStrength", _this.totalStrength);
  50402. effect.setFloat("radius", _this.radius);
  50403. effect.setFloat("area", _this.area);
  50404. effect.setFloat("fallOff", _this.fallOff);
  50405. effect.setFloat("base", _this.base);
  50406. effect.setTexture("textureSampler", _this._depthTexture);
  50407. effect.setTexture("randomSampler", _this._randomTexture);
  50408. };
  50409. };
  50410. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50411. var _this = this;
  50412. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50413. this._ssaoCombinePostProcess.onApply = function (effect) {
  50414. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50415. };
  50416. };
  50417. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  50418. var size = 512;
  50419. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50420. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50421. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50422. var context = this._randomTexture.getContext();
  50423. var rand = function (min, max) {
  50424. return Math.random() * (max - min) + min;
  50425. };
  50426. var randVector = BABYLON.Vector3.Zero();
  50427. for (var x = 0; x < size; x++) {
  50428. for (var y = 0; y < size; y++) {
  50429. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  50430. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  50431. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  50432. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50433. context.fillRect(x, y, 1, 1);
  50434. }
  50435. }
  50436. this._randomTexture.update(false);
  50437. };
  50438. return SSAORenderingPipeline;
  50439. }(BABYLON.PostProcessRenderPipeline));
  50440. __decorate([
  50441. BABYLON.serialize()
  50442. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  50443. __decorate([
  50444. BABYLON.serialize()
  50445. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50446. __decorate([
  50447. BABYLON.serialize()
  50448. ], SSAORenderingPipeline.prototype, "area", void 0);
  50449. __decorate([
  50450. BABYLON.serialize()
  50451. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50452. __decorate([
  50453. BABYLON.serialize()
  50454. ], SSAORenderingPipeline.prototype, "base", void 0);
  50455. __decorate([
  50456. BABYLON.serialize()
  50457. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50458. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50459. })(BABYLON || (BABYLON = {}));
  50460. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50461. var BABYLON;
  50462. (function (BABYLON) {
  50463. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  50464. var VolumetricLightScatteringPostProcess = (function (_super) {
  50465. __extends(VolumetricLightScatteringPostProcess, _super);
  50466. /**
  50467. * @constructor
  50468. * @param {string} name - The post-process name
  50469. * @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)
  50470. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  50471. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  50472. * @param {number} samples - The post-process quality, default 100
  50473. * @param {number} samplingMode - The post-process filtering mode
  50474. * @param {BABYLON.Engine} engine - The babylon engine
  50475. * @param {boolean} reusable - If the post-process is reusable
  50476. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  50477. */
  50478. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  50479. if (samples === void 0) { samples = 100; }
  50480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50481. 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;
  50482. _this._screenCoordinates = BABYLON.Vector2.Zero();
  50483. /**
  50484. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  50485. * @type {Vector3}
  50486. */
  50487. _this.customMeshPosition = BABYLON.Vector3.Zero();
  50488. /**
  50489. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  50490. * @type {boolean}
  50491. */
  50492. _this.useCustomMeshPosition = false;
  50493. /**
  50494. * If the post-process should inverse the light scattering direction
  50495. * @type {boolean}
  50496. */
  50497. _this.invert = true;
  50498. /**
  50499. * Array containing the excluded meshes not rendered in the internal pass
  50500. */
  50501. _this.excludedMeshes = new Array();
  50502. /**
  50503. * Controls the overall intensity of the post-process
  50504. * @type {number}
  50505. */
  50506. _this.exposure = 0.3;
  50507. /**
  50508. * Dissipates each sample's contribution in range [0, 1]
  50509. * @type {number}
  50510. */
  50511. _this.decay = 0.96815;
  50512. /**
  50513. * Controls the overall intensity of each sample
  50514. * @type {number}
  50515. */
  50516. _this.weight = 0.58767;
  50517. /**
  50518. * Controls the density of each sample
  50519. * @type {number}
  50520. */
  50521. _this.density = 0.926;
  50522. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  50523. var engine = scene.getEngine();
  50524. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  50525. // Configure mesh
  50526. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  50527. // Configure
  50528. _this._createPass(scene, ratio.passRatio || ratio);
  50529. _this.onActivate = function (camera) {
  50530. if (!_this.isSupported) {
  50531. _this.dispose(camera);
  50532. }
  50533. _this.onActivate = null;
  50534. };
  50535. _this.onApplyObservable.add(function (effect) {
  50536. _this._updateMeshScreenCoordinates(scene);
  50537. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  50538. effect.setFloat("exposure", _this.exposure);
  50539. effect.setFloat("decay", _this.decay);
  50540. effect.setFloat("weight", _this.weight);
  50541. effect.setFloat("density", _this.density);
  50542. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  50543. });
  50544. return _this;
  50545. }
  50546. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  50547. get: function () {
  50548. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50549. return false;
  50550. },
  50551. set: function (useDiffuseColor) {
  50552. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50553. },
  50554. enumerable: true,
  50555. configurable: true
  50556. });
  50557. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  50558. var mesh = subMesh.getMesh();
  50559. // Render this.mesh as default
  50560. if (mesh === this.mesh) {
  50561. return mesh.material.isReady(mesh);
  50562. }
  50563. var defines = [];
  50564. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50565. var material = subMesh.getMaterial();
  50566. var needUV = false;
  50567. // Alpha test
  50568. if (material) {
  50569. if (material.needAlphaTesting()) {
  50570. defines.push("#define ALPHATEST");
  50571. }
  50572. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50573. attribs.push(BABYLON.VertexBuffer.UVKind);
  50574. defines.push("#define UV1");
  50575. }
  50576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50577. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50578. defines.push("#define UV2");
  50579. }
  50580. }
  50581. // Bones
  50582. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50585. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50586. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50587. }
  50588. else {
  50589. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50590. }
  50591. // Instances
  50592. if (useInstances) {
  50593. defines.push("#define INSTANCES");
  50594. attribs.push("world0");
  50595. attribs.push("world1");
  50596. attribs.push("world2");
  50597. attribs.push("world3");
  50598. }
  50599. // Get correct effect
  50600. var join = defines.join("\n");
  50601. if (this._cachedDefines !== join) {
  50602. this._cachedDefines = join;
  50603. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  50604. }
  50605. return this._volumetricLightScatteringPass.isReady();
  50606. };
  50607. /**
  50608. * Sets the new light position for light scattering effect
  50609. * @param {BABYLON.Vector3} The new custom light position
  50610. */
  50611. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  50612. this.customMeshPosition = position;
  50613. };
  50614. /**
  50615. * Returns the light position for light scattering effect
  50616. * @return {BABYLON.Vector3} The custom light position
  50617. */
  50618. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  50619. return this.customMeshPosition;
  50620. };
  50621. /**
  50622. * Disposes the internal assets and detaches the post-process from the camera
  50623. */
  50624. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  50625. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  50626. if (rttIndex !== -1) {
  50627. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  50628. }
  50629. this._volumetricLightScatteringRTT.dispose();
  50630. _super.prototype.dispose.call(this, camera);
  50631. };
  50632. /**
  50633. * Returns the render target texture used by the post-process
  50634. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  50635. */
  50636. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  50637. return this._volumetricLightScatteringRTT;
  50638. };
  50639. // Private methods
  50640. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  50641. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  50642. return true;
  50643. }
  50644. return false;
  50645. };
  50646. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  50647. var _this = this;
  50648. var engine = scene.getEngine();
  50649. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50650. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50651. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50652. this._volumetricLightScatteringRTT.renderList = null;
  50653. this._volumetricLightScatteringRTT.renderParticles = false;
  50654. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  50655. // Custom render function for submeshes
  50656. var renderSubMesh = function (subMesh) {
  50657. var mesh = subMesh.getRenderingMesh();
  50658. if (_this._meshExcluded(mesh)) {
  50659. return;
  50660. }
  50661. var scene = mesh.getScene();
  50662. var engine = scene.getEngine();
  50663. // Culling
  50664. engine.setState(subMesh.getMaterial().backFaceCulling);
  50665. // Managing instances
  50666. var batch = mesh._getInstancesRenderList(subMesh._id);
  50667. if (batch.mustReturn) {
  50668. return;
  50669. }
  50670. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50671. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50672. var effect = _this._volumetricLightScatteringPass;
  50673. if (mesh === _this.mesh) {
  50674. effect = subMesh.getMaterial().getEffect();
  50675. }
  50676. engine.enableEffect(effect);
  50677. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  50678. if (mesh === _this.mesh) {
  50679. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  50680. }
  50681. else {
  50682. var material = subMesh.getMaterial();
  50683. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  50684. // Alpha test
  50685. if (material && material.needAlphaTesting()) {
  50686. var alphaTexture = material.getAlphaTestTexture();
  50687. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  50688. if (alphaTexture) {
  50689. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50690. }
  50691. }
  50692. // Bones
  50693. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50694. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50695. }
  50696. }
  50697. // Draw
  50698. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  50699. }
  50700. };
  50701. // Render target texture callbacks
  50702. var savedSceneClearColor;
  50703. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  50704. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  50705. savedSceneClearColor = scene.clearColor;
  50706. scene.clearColor = sceneClearColor;
  50707. });
  50708. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  50709. scene.clearColor = savedSceneClearColor;
  50710. });
  50711. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  50712. var engine = scene.getEngine();
  50713. var index;
  50714. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50715. renderSubMesh(opaqueSubMeshes.data[index]);
  50716. }
  50717. engine.setAlphaTesting(true);
  50718. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50719. renderSubMesh(alphaTestSubMeshes.data[index]);
  50720. }
  50721. engine.setAlphaTesting(false);
  50722. if (transparentSubMeshes.length) {
  50723. // Sort sub meshes
  50724. for (index = 0; index < transparentSubMeshes.length; index++) {
  50725. var submesh = transparentSubMeshes.data[index];
  50726. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  50727. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  50728. }
  50729. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  50730. sortedArray.sort(function (a, b) {
  50731. // Alpha index first
  50732. if (a._alphaIndex > b._alphaIndex) {
  50733. return 1;
  50734. }
  50735. if (a._alphaIndex < b._alphaIndex) {
  50736. return -1;
  50737. }
  50738. // Then distance to camera
  50739. if (a._distanceToCamera < b._distanceToCamera) {
  50740. return 1;
  50741. }
  50742. if (a._distanceToCamera > b._distanceToCamera) {
  50743. return -1;
  50744. }
  50745. return 0;
  50746. });
  50747. // Render sub meshes
  50748. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50749. for (index = 0; index < sortedArray.length; index++) {
  50750. renderSubMesh(sortedArray[index]);
  50751. }
  50752. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50753. }
  50754. };
  50755. };
  50756. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  50757. var transform = scene.getTransformMatrix();
  50758. var meshPosition;
  50759. if (this.useCustomMeshPosition) {
  50760. meshPosition = this.customMeshPosition;
  50761. }
  50762. else if (this.attachedNode) {
  50763. meshPosition = this.attachedNode.position;
  50764. }
  50765. else {
  50766. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  50767. }
  50768. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  50769. this._screenCoordinates.x = pos.x / this._viewPort.width;
  50770. this._screenCoordinates.y = pos.y / this._viewPort.height;
  50771. if (this.invert)
  50772. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  50773. };
  50774. // Static methods
  50775. /**
  50776. * Creates a default mesh for the Volumeric Light Scattering post-process
  50777. * @param {string} The mesh name
  50778. * @param {BABYLON.Scene} The scene where to create the mesh
  50779. * @return {BABYLON.Mesh} the default mesh
  50780. */
  50781. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  50782. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  50783. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  50784. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  50785. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  50786. mesh.material = material;
  50787. return mesh;
  50788. };
  50789. return VolumetricLightScatteringPostProcess;
  50790. }(BABYLON.PostProcess));
  50791. __decorate([
  50792. BABYLON.serializeAsVector3()
  50793. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  50794. __decorate([
  50795. BABYLON.serialize()
  50796. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  50797. __decorate([
  50798. BABYLON.serialize()
  50799. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  50800. __decorate([
  50801. BABYLON.serializeAsMeshReference()
  50802. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  50803. __decorate([
  50804. BABYLON.serialize()
  50805. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  50806. __decorate([
  50807. BABYLON.serialize()
  50808. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  50809. __decorate([
  50810. BABYLON.serialize()
  50811. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  50812. __decorate([
  50813. BABYLON.serialize()
  50814. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  50815. __decorate([
  50816. BABYLON.serialize()
  50817. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  50818. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  50819. })(BABYLON || (BABYLON = {}));
  50820. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  50821. // BABYLON.JS Chromatic Aberration GLSL Shader
  50822. // Author: Olivier Guyot
  50823. // Separates very slightly R, G and B colors on the edges of the screen
  50824. // Inspired by Francois Tarlier & Martins Upitis
  50825. var BABYLON;
  50826. (function (BABYLON) {
  50827. var LensRenderingPipeline = (function (_super) {
  50828. __extends(LensRenderingPipeline, _super);
  50829. /**
  50830. * @constructor
  50831. *
  50832. * Effect parameters are as follow:
  50833. * {
  50834. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50835. * edge_blur: number; // from 0 to x (1 for realism)
  50836. * distortion: number; // from 0 to x (1 for realism)
  50837. * grain_amount: number; // from 0 to 1
  50838. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50839. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50840. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50841. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50842. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50843. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50844. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50845. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50846. * }
  50847. * Note: if an effect parameter is unset, effect is disabled
  50848. *
  50849. * @param {string} name - The rendering pipeline name
  50850. * @param {object} parameters - An object containing all parameters (see above)
  50851. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50852. * @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)
  50853. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50854. */
  50855. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50856. if (ratio === void 0) { ratio = 1.0; }
  50857. var _this = _super.call(this, scene.getEngine(), name) || this;
  50858. // Lens effects can be of the following:
  50859. // - chromatic aberration (slight shift of RGB colors)
  50860. // - blur on the edge of the lens
  50861. // - lens distortion
  50862. // - depth-of-field blur & highlights enhancing
  50863. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50864. // - grain effect (noise or custom texture)
  50865. // Two additional texture samplers are needed:
  50866. // - depth map (for depth-of-field)
  50867. // - grain texture
  50868. /**
  50869. * The chromatic aberration PostProcess id in the pipeline
  50870. * @type {string}
  50871. */
  50872. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50873. /**
  50874. * The highlights enhancing PostProcess id in the pipeline
  50875. * @type {string}
  50876. */
  50877. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50878. /**
  50879. * The depth-of-field PostProcess id in the pipeline
  50880. * @type {string}
  50881. */
  50882. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50883. _this._scene = scene;
  50884. // Fetch texture samplers
  50885. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50886. if (parameters.grain_texture) {
  50887. _this._grainTexture = parameters.grain_texture;
  50888. }
  50889. else {
  50890. _this._createGrainTexture();
  50891. }
  50892. // save parameters
  50893. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50894. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50895. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50896. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  50897. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50898. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50899. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50900. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50901. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50902. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50903. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50904. // Create effects
  50905. _this._createChromaticAberrationPostProcess(ratio);
  50906. _this._createHighlightsPostProcess(ratio);
  50907. _this._createDepthOfFieldPostProcess(ratio / 4);
  50908. // Set up pipeline
  50909. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50910. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50911. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50912. if (_this._highlightsGain === -1) {
  50913. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  50914. }
  50915. // Finish
  50916. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50917. if (cameras) {
  50918. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50919. }
  50920. return _this;
  50921. }
  50922. // public methods (self explanatory)
  50923. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50924. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50925. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50926. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50927. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50928. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50929. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50930. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50931. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50932. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50933. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50934. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50935. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  50936. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  50937. };
  50938. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  50939. this._highlightsPostProcess.updateEffect();
  50940. };
  50941. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  50942. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  50943. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  50944. this._highlightsGain = amount;
  50945. };
  50946. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  50947. if (this._highlightsGain === -1) {
  50948. this._highlightsGain = 1.0;
  50949. }
  50950. this._highlightsThreshold = amount;
  50951. };
  50952. LensRenderingPipeline.prototype.disableHighlights = function () {
  50953. this._highlightsGain = -1;
  50954. };
  50955. /**
  50956. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  50957. */
  50958. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50959. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50960. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50961. this._chromaticAberrationPostProcess = undefined;
  50962. this._highlightsPostProcess = undefined;
  50963. this._depthOfFieldPostProcess = undefined;
  50964. this._grainTexture.dispose();
  50965. if (disableDepthRender)
  50966. this._scene.disableDepthRenderer();
  50967. };
  50968. // colors shifting and distortion
  50969. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  50970. var _this = this;
  50971. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  50972. [], // samplers
  50973. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50974. this._chromaticAberrationPostProcess.onApply = function (effect) {
  50975. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  50976. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50977. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50978. };
  50979. };
  50980. // highlights enhancing
  50981. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  50982. var _this = this;
  50983. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  50984. [], // samplers
  50985. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  50986. this._highlightsPostProcess.onApply = function (effect) {
  50987. effect.setFloat('gain', _this._highlightsGain);
  50988. effect.setFloat('threshold', _this._highlightsThreshold);
  50989. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  50990. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50991. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50992. };
  50993. };
  50994. // colors shifting and distortion
  50995. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  50996. var _this = this;
  50997. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  50998. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  50999. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  51000. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51001. this._depthOfFieldPostProcess.onApply = function (effect) {
  51002. effect.setTexture("depthSampler", _this._depthTexture);
  51003. effect.setTexture("grainSampler", _this._grainTexture);
  51004. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  51005. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  51006. effect.setFloat('grain_amount', _this._grainAmount);
  51007. effect.setBool('blur_noise', _this._blurNoise);
  51008. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51009. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51010. effect.setFloat('distortion', _this._distortion);
  51011. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  51012. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  51013. effect.setFloat('aperture', _this._dofAperture);
  51014. effect.setFloat('darken', _this._dofDarken);
  51015. effect.setFloat('edge_blur', _this._edgeBlur);
  51016. effect.setBool('highlights', (_this._highlightsGain !== -1));
  51017. effect.setFloat('near', _this._scene.activeCamera.minZ);
  51018. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  51019. };
  51020. };
  51021. // creates a black and white random noise texture, 512x512
  51022. LensRenderingPipeline.prototype._createGrainTexture = function () {
  51023. var size = 512;
  51024. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51025. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51026. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51027. var context = this._grainTexture.getContext();
  51028. var rand = function (min, max) {
  51029. return Math.random() * (max - min) + min;
  51030. };
  51031. var value;
  51032. for (var x = 0; x < size; x++) {
  51033. for (var y = 0; y < size; y++) {
  51034. value = Math.floor(rand(0.42, 0.58) * 255);
  51035. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  51036. context.fillRect(x, y, 1, 1);
  51037. }
  51038. }
  51039. this._grainTexture.update(false);
  51040. };
  51041. return LensRenderingPipeline;
  51042. }(BABYLON.PostProcessRenderPipeline));
  51043. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  51044. })(BABYLON || (BABYLON = {}));
  51045. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  51046. //
  51047. // This post-process allows the modification of rendered colors by using
  51048. // a 'look-up table' (LUT). This effect is also called Color Grading.
  51049. //
  51050. // The object needs to be provided an url to a texture containing the color
  51051. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  51052. // Use an image editing software to tweak the LUT to match your needs.
  51053. //
  51054. // For an example of a color LUT, see here:
  51055. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  51056. // For explanations on color grading, see here:
  51057. // http://udn.epicgames.com/Three/ColorGrading.html
  51058. //
  51059. var BABYLON;
  51060. (function (BABYLON) {
  51061. var ColorCorrectionPostProcess = (function (_super) {
  51062. __extends(ColorCorrectionPostProcess, _super);
  51063. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  51064. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  51065. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51066. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  51067. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51068. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51069. _this.onApply = function (effect) {
  51070. effect.setTexture("colorTable", _this._colorTableTexture);
  51071. };
  51072. return _this;
  51073. }
  51074. return ColorCorrectionPostProcess;
  51075. }(BABYLON.PostProcess));
  51076. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  51077. })(BABYLON || (BABYLON = {}));
  51078. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  51079. /// <reference path="babylon.freeCamera.ts" />
  51080. /// <reference path="babylon.arcRotateCamera.ts" />
  51081. /// <reference path="babylon.gamepadCamera.ts" />
  51082. /// <reference path="babylon.universalCamera.ts" />
  51083. var BABYLON;
  51084. (function (BABYLON) {
  51085. var AnaglyphFreeCamera = (function (_super) {
  51086. __extends(AnaglyphFreeCamera, _super);
  51087. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  51088. var _this = _super.call(this, name, position, scene) || this;
  51089. _this.interaxialDistance = interaxialDistance;
  51090. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51091. return _this;
  51092. }
  51093. AnaglyphFreeCamera.prototype.getClassName = function () {
  51094. return "AnaglyphFreeCamera";
  51095. };
  51096. return AnaglyphFreeCamera;
  51097. }(BABYLON.FreeCamera));
  51098. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  51099. var AnaglyphArcRotateCamera = (function (_super) {
  51100. __extends(AnaglyphArcRotateCamera, _super);
  51101. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  51102. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51103. _this.interaxialDistance = interaxialDistance;
  51104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51105. return _this;
  51106. }
  51107. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  51108. return "AnaglyphArcRotateCamera";
  51109. };
  51110. return AnaglyphArcRotateCamera;
  51111. }(BABYLON.ArcRotateCamera));
  51112. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  51113. var AnaglyphGamepadCamera = (function (_super) {
  51114. __extends(AnaglyphGamepadCamera, _super);
  51115. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  51116. var _this = _super.call(this, name, position, scene) || this;
  51117. _this.interaxialDistance = interaxialDistance;
  51118. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51119. return _this;
  51120. }
  51121. AnaglyphGamepadCamera.prototype.getClassName = function () {
  51122. return "AnaglyphGamepadCamera";
  51123. };
  51124. return AnaglyphGamepadCamera;
  51125. }(BABYLON.GamepadCamera));
  51126. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  51127. var AnaglyphUniversalCamera = (function (_super) {
  51128. __extends(AnaglyphUniversalCamera, _super);
  51129. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  51130. var _this = _super.call(this, name, position, scene) || this;
  51131. _this.interaxialDistance = interaxialDistance;
  51132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51133. return _this;
  51134. }
  51135. AnaglyphUniversalCamera.prototype.getClassName = function () {
  51136. return "AnaglyphUniversalCamera";
  51137. };
  51138. return AnaglyphUniversalCamera;
  51139. }(BABYLON.UniversalCamera));
  51140. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  51141. var StereoscopicFreeCamera = (function (_super) {
  51142. __extends(StereoscopicFreeCamera, _super);
  51143. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51144. var _this = _super.call(this, name, position, scene) || this;
  51145. _this.interaxialDistance = interaxialDistance;
  51146. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51147. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51148. return _this;
  51149. }
  51150. StereoscopicFreeCamera.prototype.getClassName = function () {
  51151. return "StereoscopicFreeCamera";
  51152. };
  51153. return StereoscopicFreeCamera;
  51154. }(BABYLON.FreeCamera));
  51155. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  51156. var StereoscopicArcRotateCamera = (function (_super) {
  51157. __extends(StereoscopicArcRotateCamera, _super);
  51158. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  51159. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51160. _this.interaxialDistance = interaxialDistance;
  51161. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51162. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51163. return _this;
  51164. }
  51165. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  51166. return "StereoscopicArcRotateCamera";
  51167. };
  51168. return StereoscopicArcRotateCamera;
  51169. }(BABYLON.ArcRotateCamera));
  51170. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  51171. var StereoscopicGamepadCamera = (function (_super) {
  51172. __extends(StereoscopicGamepadCamera, _super);
  51173. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51174. var _this = _super.call(this, name, position, scene) || this;
  51175. _this.interaxialDistance = interaxialDistance;
  51176. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51177. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51178. return _this;
  51179. }
  51180. StereoscopicGamepadCamera.prototype.getClassName = function () {
  51181. return "StereoscopicGamepadCamera";
  51182. };
  51183. return StereoscopicGamepadCamera;
  51184. }(BABYLON.GamepadCamera));
  51185. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  51186. var StereoscopicUniversalCamera = (function (_super) {
  51187. __extends(StereoscopicUniversalCamera, _super);
  51188. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51189. var _this = _super.call(this, name, position, scene) || this;
  51190. _this.interaxialDistance = interaxialDistance;
  51191. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51192. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51193. return _this;
  51194. }
  51195. StereoscopicUniversalCamera.prototype.getClassName = function () {
  51196. return "StereoscopicUniversalCamera";
  51197. };
  51198. return StereoscopicUniversalCamera;
  51199. }(BABYLON.UniversalCamera));
  51200. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  51201. })(BABYLON || (BABYLON = {}));
  51202. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  51203. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  51204. var BABYLON;
  51205. (function (BABYLON) {
  51206. var HDRRenderingPipeline = (function (_super) {
  51207. __extends(HDRRenderingPipeline, _super);
  51208. /**
  51209. * @constructor
  51210. * @param {string} name - The rendering pipeline name
  51211. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51212. * @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)
  51213. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  51214. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51215. */
  51216. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  51217. if (originalPostProcess === void 0) { originalPostProcess = null; }
  51218. var _this = _super.call(this, scene.getEngine(), name) || this;
  51219. /**
  51220. * Public members
  51221. */
  51222. // Gaussian Blur
  51223. /**
  51224. * Gaussian blur coefficient
  51225. * @type {number}
  51226. */
  51227. _this.gaussCoeff = 0.3;
  51228. /**
  51229. * Gaussian blur mean
  51230. * @type {number}
  51231. */
  51232. _this.gaussMean = 1.0;
  51233. /**
  51234. * Gaussian blur standard deviation
  51235. * @type {number}
  51236. */
  51237. _this.gaussStandDev = 0.8;
  51238. /**
  51239. * Gaussian blur multiplier. Multiplies the blur effect
  51240. * @type {number}
  51241. */
  51242. _this.gaussMultiplier = 4.0;
  51243. // HDR
  51244. /**
  51245. * Exposure, controls the overall intensity of the pipeline
  51246. * @type {number}
  51247. */
  51248. _this.exposure = 1.0;
  51249. /**
  51250. * Minimum luminance that the post-process can output. Luminance is >= 0
  51251. * @type {number}
  51252. */
  51253. _this.minimumLuminance = 1.0;
  51254. /**
  51255. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  51256. * @type {number}
  51257. */
  51258. _this.maximumLuminance = 1e20;
  51259. /**
  51260. * Increase rate for luminance: eye adaptation speed to dark
  51261. * @type {number}
  51262. */
  51263. _this.luminanceIncreaserate = 0.5;
  51264. /**
  51265. * Decrease rate for luminance: eye adaptation speed to bright
  51266. * @type {number}
  51267. */
  51268. _this.luminanceDecreaseRate = 0.5;
  51269. // Bright pass
  51270. /**
  51271. * Minimum luminance needed to compute HDR
  51272. * @type {number}
  51273. */
  51274. _this.brightThreshold = 0.8;
  51275. _this._needUpdate = true;
  51276. _this._scene = scene;
  51277. // Bright pass
  51278. _this._createBrightPassPostProcess(scene, ratio);
  51279. // Down sample X4
  51280. _this._createDownSampleX4PostProcess(scene, ratio);
  51281. // Create gaussian blur post-processes
  51282. _this._createGaussianBlurPostProcess(scene, ratio);
  51283. // Texture adder
  51284. _this._createTextureAdderPostProcess(scene, ratio);
  51285. // Luminance generator
  51286. _this._createLuminanceGeneratorPostProcess(scene);
  51287. // HDR
  51288. _this._createHDRPostProcess(scene, ratio);
  51289. // Pass postprocess
  51290. if (originalPostProcess === null) {
  51291. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51292. }
  51293. else {
  51294. _this._originalPostProcess = originalPostProcess;
  51295. }
  51296. // Configure pipeline
  51297. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  51298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  51299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  51300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  51301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  51302. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  51303. var addDownSamplerPostProcess = function (id) {
  51304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  51305. };
  51306. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  51307. addDownSamplerPostProcess(i);
  51308. }
  51309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  51310. // Finish
  51311. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51312. if (cameras !== null) {
  51313. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51314. }
  51315. _this.update();
  51316. return _this;
  51317. }
  51318. /**
  51319. * Tells the pipeline to update its post-processes
  51320. */
  51321. HDRRenderingPipeline.prototype.update = function () {
  51322. this._needUpdate = true;
  51323. };
  51324. /**
  51325. * Returns the current calculated luminance
  51326. */
  51327. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  51328. return this._hdrCurrentLuminance;
  51329. };
  51330. /**
  51331. * Returns the currently drawn luminance
  51332. */
  51333. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  51334. return this._hdrOutputLuminance;
  51335. };
  51336. /**
  51337. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  51338. */
  51339. HDRRenderingPipeline.prototype.dispose = function () {
  51340. for (var i = 0; i < this._scene.cameras.length; i++) {
  51341. var camera = this._scene.cameras[i];
  51342. this._originalPostProcess.dispose(camera);
  51343. this._brightPassPostProcess.dispose(camera);
  51344. this._downSampleX4PostProcess.dispose(camera);
  51345. this._guassianBlurHPostProcess.dispose(camera);
  51346. this._guassianBlurVPostProcess.dispose(camera);
  51347. this._textureAdderPostProcess.dispose(camera);
  51348. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  51349. this._downSamplePostProcesses[j].dispose(camera);
  51350. }
  51351. this._hdrPostProcess.dispose(camera);
  51352. }
  51353. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51354. _super.prototype.dispose.call(this);
  51355. };
  51356. /**
  51357. * Creates the HDR post-process and computes the luminance adaptation
  51358. */
  51359. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  51360. var _this = this;
  51361. var hdrLastLuminance = 0.0;
  51362. this._hdrOutputLuminance = -1.0;
  51363. this._hdrCurrentLuminance = 1.0;
  51364. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  51365. this._hdrPostProcess.onApply = function (effect) {
  51366. if (_this._hdrOutputLuminance < 0.0) {
  51367. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51368. }
  51369. else {
  51370. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  51371. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  51372. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  51373. }
  51374. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  51375. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  51376. }
  51377. else {
  51378. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51379. }
  51380. }
  51381. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  51382. hdrLastLuminance += scene.getEngine().getDeltaTime();
  51383. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51384. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51385. effect.setFloat("exposure", _this.exposure);
  51386. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  51387. _this._needUpdate = false;
  51388. };
  51389. };
  51390. /**
  51391. * Texture Adder post-process
  51392. */
  51393. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  51394. var _this = this;
  51395. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  51396. this._textureAdderPostProcess.onApply = function (effect) {
  51397. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51398. };
  51399. };
  51400. /**
  51401. * Down sample X4 post-process
  51402. */
  51403. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  51404. var _this = this;
  51405. var downSampleX4Offsets = new Array(32);
  51406. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  51407. this._downSampleX4PostProcess.onApply = function (effect) {
  51408. if (_this._needUpdate) {
  51409. var id = 0;
  51410. for (var i = -2; i < 2; i++) {
  51411. for (var j = -2; j < 2; j++) {
  51412. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  51413. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  51414. id += 2;
  51415. }
  51416. }
  51417. }
  51418. effect.setArray2("dsOffsets", downSampleX4Offsets);
  51419. };
  51420. };
  51421. /**
  51422. * Bright pass post-process
  51423. */
  51424. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  51425. var _this = this;
  51426. var brightOffsets = new Array(8);
  51427. var brightPassCallback = function (effect) {
  51428. if (_this._needUpdate) {
  51429. var sU = (1.0 / _this._brightPassPostProcess.width);
  51430. var sV = (1.0 / _this._brightPassPostProcess.height);
  51431. brightOffsets[0] = -0.5 * sU;
  51432. brightOffsets[1] = 0.5 * sV;
  51433. brightOffsets[2] = 0.5 * sU;
  51434. brightOffsets[3] = 0.5 * sV;
  51435. brightOffsets[4] = -0.5 * sU;
  51436. brightOffsets[5] = -0.5 * sV;
  51437. brightOffsets[6] = 0.5 * sU;
  51438. brightOffsets[7] = -0.5 * sV;
  51439. }
  51440. effect.setArray2("dsOffsets", brightOffsets);
  51441. effect.setFloat("brightThreshold", _this.brightThreshold);
  51442. };
  51443. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  51444. this._brightPassPostProcess.onApply = brightPassCallback;
  51445. };
  51446. /**
  51447. * Luminance generator. Creates the luminance post-process and down sample post-processes
  51448. */
  51449. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  51450. var _this = this;
  51451. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  51452. var luminanceOffsets = new Array(8);
  51453. var downSampleOffsets = new Array(18);
  51454. var halfDestPixelSize;
  51455. this._downSamplePostProcesses = new Array(lumSteps);
  51456. // Utils for luminance
  51457. var luminanceUpdateSourceOffsets = function (width, height) {
  51458. var sU = (1.0 / width);
  51459. var sV = (1.0 / height);
  51460. luminanceOffsets[0] = -0.5 * sU;
  51461. luminanceOffsets[1] = 0.5 * sV;
  51462. luminanceOffsets[2] = 0.5 * sU;
  51463. luminanceOffsets[3] = 0.5 * sV;
  51464. luminanceOffsets[4] = -0.5 * sU;
  51465. luminanceOffsets[5] = -0.5 * sV;
  51466. luminanceOffsets[6] = 0.5 * sU;
  51467. luminanceOffsets[7] = -0.5 * sV;
  51468. };
  51469. var luminanceUpdateDestOffsets = function (width, height) {
  51470. var id = 0;
  51471. for (var x = -1; x < 2; x++) {
  51472. for (var y = -1; y < 2; y++) {
  51473. downSampleOffsets[id] = (x) / width;
  51474. downSampleOffsets[id + 1] = (y) / height;
  51475. id += 2;
  51476. }
  51477. }
  51478. };
  51479. // Luminance callback
  51480. var luminanceCallback = function (effect) {
  51481. if (_this._needUpdate) {
  51482. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  51483. }
  51484. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51485. effect.setArray2("lumOffsets", luminanceOffsets);
  51486. };
  51487. // Down sample callbacks
  51488. var downSampleCallback = function (indice) {
  51489. var i = indice;
  51490. return function (effect) {
  51491. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51492. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51493. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  51494. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  51495. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  51496. effect.setArray2("dsOffsets", downSampleOffsets);
  51497. };
  51498. };
  51499. var downSampleAfterRenderCallback = function (effect) {
  51500. // Unpack result
  51501. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  51502. 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);
  51503. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  51504. };
  51505. // Create luminance post-process
  51506. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  51507. 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);
  51508. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  51509. // Create down sample post-processes
  51510. for (var i = lumSteps - 2; i >= 0; i--) {
  51511. var length = Math.pow(3, i);
  51512. ratio = { width: length, height: length };
  51513. var defines = "#define DOWN_SAMPLE\n";
  51514. if (i === 0) {
  51515. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  51516. }
  51517. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  51518. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  51519. if (i === 0) {
  51520. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  51521. }
  51522. }
  51523. };
  51524. /**
  51525. * Gaussian blur post-processes. Horizontal and Vertical
  51526. */
  51527. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  51528. var _this = this;
  51529. var blurOffsetsW = new Array(9);
  51530. var blurOffsetsH = new Array(9);
  51531. var blurWeights = new Array(9);
  51532. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  51533. // Utils for gaussian blur
  51534. var calculateBlurOffsets = function (height) {
  51535. var lastOutputDimensions = {
  51536. width: scene.getEngine().getRenderWidth(),
  51537. height: scene.getEngine().getRenderHeight()
  51538. };
  51539. for (var i = 0; i < 9; i++) {
  51540. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  51541. if (height) {
  51542. blurOffsetsH[i] = value;
  51543. }
  51544. else {
  51545. blurOffsetsW[i] = value;
  51546. }
  51547. }
  51548. };
  51549. var calculateWeights = function () {
  51550. var x = 0.0;
  51551. for (var i = 0; i < 9; i++) {
  51552. x = (i - 4.0) / 4.0;
  51553. 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));
  51554. }
  51555. };
  51556. // Callback
  51557. var gaussianBlurCallback = function (height) {
  51558. return function (effect) {
  51559. if (_this._needUpdate) {
  51560. calculateWeights();
  51561. calculateBlurOffsets(height);
  51562. }
  51563. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  51564. effect.setArray("blurWeights", blurWeights);
  51565. effect.setFloat("multiplier", _this.gaussMultiplier);
  51566. };
  51567. };
  51568. // Create horizontal gaussian blur post-processes
  51569. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  51570. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  51571. // Create vertical gaussian blur post-process
  51572. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  51573. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  51574. };
  51575. return HDRRenderingPipeline;
  51576. }(BABYLON.PostProcessRenderPipeline));
  51577. // Luminance generator
  51578. HDRRenderingPipeline.LUM_STEPS = 6;
  51579. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  51580. })(BABYLON || (BABYLON = {}));
  51581. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  51582. var BABYLON;
  51583. (function (BABYLON) {
  51584. var FaceAdjacencies = (function () {
  51585. function FaceAdjacencies() {
  51586. this.edges = new Array();
  51587. this.edgesConnectedCount = 0;
  51588. }
  51589. return FaceAdjacencies;
  51590. }());
  51591. var EdgesRenderer = (function () {
  51592. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  51593. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  51594. if (epsilon === void 0) { epsilon = 0.95; }
  51595. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  51596. this.edgesWidthScalerForOrthographic = 1000.0;
  51597. this.edgesWidthScalerForPerspective = 50.0;
  51598. this._linesPositions = new Array();
  51599. this._linesNormals = new Array();
  51600. this._linesIndices = new Array();
  51601. this._buffers = {};
  51602. this._checkVerticesInsteadOfIndices = false;
  51603. this._source = source;
  51604. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  51605. this._epsilon = epsilon;
  51606. this._prepareRessources();
  51607. this._generateEdgesLines();
  51608. }
  51609. EdgesRenderer.prototype._prepareRessources = function () {
  51610. if (this._lineShader) {
  51611. return;
  51612. }
  51613. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  51614. attributes: ["position", "normal"],
  51615. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  51616. });
  51617. this._lineShader.disableDepthWrite = true;
  51618. this._lineShader.backFaceCulling = false;
  51619. };
  51620. EdgesRenderer.prototype.dispose = function () {
  51621. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  51622. if (buffer) {
  51623. buffer.dispose();
  51624. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  51625. }
  51626. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  51627. if (buffer) {
  51628. buffer.dispose();
  51629. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  51630. }
  51631. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  51632. this._lineShader.dispose();
  51633. };
  51634. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  51635. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  51636. return 0;
  51637. }
  51638. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  51639. return 1;
  51640. }
  51641. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  51642. return 2;
  51643. }
  51644. return -1;
  51645. };
  51646. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  51647. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  51648. return 0;
  51649. }
  51650. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  51651. return 1;
  51652. }
  51653. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  51654. return 2;
  51655. }
  51656. return -1;
  51657. };
  51658. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  51659. var needToCreateLine;
  51660. if (edge === undefined) {
  51661. needToCreateLine = true;
  51662. }
  51663. else {
  51664. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  51665. needToCreateLine = dotProduct < this._epsilon;
  51666. }
  51667. if (needToCreateLine) {
  51668. var offset = this._linesPositions.length / 3;
  51669. var normal = p0.subtract(p1);
  51670. normal.normalize();
  51671. // Positions
  51672. this._linesPositions.push(p0.x);
  51673. this._linesPositions.push(p0.y);
  51674. this._linesPositions.push(p0.z);
  51675. this._linesPositions.push(p0.x);
  51676. this._linesPositions.push(p0.y);
  51677. this._linesPositions.push(p0.z);
  51678. this._linesPositions.push(p1.x);
  51679. this._linesPositions.push(p1.y);
  51680. this._linesPositions.push(p1.z);
  51681. this._linesPositions.push(p1.x);
  51682. this._linesPositions.push(p1.y);
  51683. this._linesPositions.push(p1.z);
  51684. // Normals
  51685. this._linesNormals.push(p1.x);
  51686. this._linesNormals.push(p1.y);
  51687. this._linesNormals.push(p1.z);
  51688. this._linesNormals.push(-1);
  51689. this._linesNormals.push(p1.x);
  51690. this._linesNormals.push(p1.y);
  51691. this._linesNormals.push(p1.z);
  51692. this._linesNormals.push(1);
  51693. this._linesNormals.push(p0.x);
  51694. this._linesNormals.push(p0.y);
  51695. this._linesNormals.push(p0.z);
  51696. this._linesNormals.push(-1);
  51697. this._linesNormals.push(p0.x);
  51698. this._linesNormals.push(p0.y);
  51699. this._linesNormals.push(p0.z);
  51700. this._linesNormals.push(1);
  51701. // Indices
  51702. this._linesIndices.push(offset);
  51703. this._linesIndices.push(offset + 1);
  51704. this._linesIndices.push(offset + 2);
  51705. this._linesIndices.push(offset);
  51706. this._linesIndices.push(offset + 2);
  51707. this._linesIndices.push(offset + 3);
  51708. }
  51709. };
  51710. EdgesRenderer.prototype._generateEdgesLines = function () {
  51711. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51712. var indices = this._source.getIndices();
  51713. // First let's find adjacencies
  51714. var adjacencies = new Array();
  51715. var faceNormals = new Array();
  51716. var index;
  51717. var faceAdjacencies;
  51718. // Prepare faces
  51719. for (index = 0; index < indices.length; index += 3) {
  51720. faceAdjacencies = new FaceAdjacencies();
  51721. var p0Index = indices[index];
  51722. var p1Index = indices[index + 1];
  51723. var p2Index = indices[index + 2];
  51724. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  51725. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  51726. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  51727. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  51728. faceNormal.normalize();
  51729. faceNormals.push(faceNormal);
  51730. adjacencies.push(faceAdjacencies);
  51731. }
  51732. // Scan
  51733. for (index = 0; index < adjacencies.length; index++) {
  51734. faceAdjacencies = adjacencies[index];
  51735. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  51736. var otherFaceAdjacencies = adjacencies[otherIndex];
  51737. if (faceAdjacencies.edgesConnectedCount === 3) {
  51738. break;
  51739. }
  51740. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  51741. continue;
  51742. }
  51743. var otherP0 = indices[otherIndex * 3];
  51744. var otherP1 = indices[otherIndex * 3 + 1];
  51745. var otherP2 = indices[otherIndex * 3 + 2];
  51746. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  51747. var otherEdgeIndex;
  51748. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  51749. continue;
  51750. }
  51751. switch (edgeIndex) {
  51752. case 0:
  51753. if (this._checkVerticesInsteadOfIndices) {
  51754. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51755. }
  51756. else {
  51757. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  51758. }
  51759. break;
  51760. case 1:
  51761. if (this._checkVerticesInsteadOfIndices) {
  51762. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51763. }
  51764. else {
  51765. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  51766. }
  51767. break;
  51768. case 2:
  51769. if (this._checkVerticesInsteadOfIndices) {
  51770. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51771. }
  51772. else {
  51773. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  51774. }
  51775. break;
  51776. }
  51777. if (otherEdgeIndex === -1) {
  51778. continue;
  51779. }
  51780. faceAdjacencies.edges[edgeIndex] = otherIndex;
  51781. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  51782. faceAdjacencies.edgesConnectedCount++;
  51783. otherFaceAdjacencies.edgesConnectedCount++;
  51784. if (faceAdjacencies.edgesConnectedCount === 3) {
  51785. break;
  51786. }
  51787. }
  51788. }
  51789. }
  51790. // Create lines
  51791. for (index = 0; index < adjacencies.length; index++) {
  51792. // 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
  51793. var current = adjacencies[index];
  51794. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  51795. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  51796. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  51797. }
  51798. // Merge into a single mesh
  51799. var engine = this._source.getScene().getEngine();
  51800. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  51801. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  51802. this._ib = engine.createIndexBuffer(this._linesIndices);
  51803. this._indicesCount = this._linesIndices.length;
  51804. };
  51805. EdgesRenderer.prototype.render = function () {
  51806. if (!this._lineShader.isReady()) {
  51807. return;
  51808. }
  51809. var scene = this._source.getScene();
  51810. var engine = scene.getEngine();
  51811. this._lineShader._preBind();
  51812. // VBOs
  51813. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  51814. scene.resetCachedMaterial();
  51815. this._lineShader.setColor4("color", this._source.edgesColor);
  51816. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  51817. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  51818. }
  51819. else {
  51820. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  51821. }
  51822. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  51823. this._lineShader.bind(this._source.getWorldMatrix());
  51824. // Draw order
  51825. engine.draw(true, 0, this._indicesCount);
  51826. this._lineShader.unbind();
  51827. engine.setDepthWrite(true);
  51828. };
  51829. return EdgesRenderer;
  51830. }());
  51831. BABYLON.EdgesRenderer = EdgesRenderer;
  51832. })(BABYLON || (BABYLON = {}));
  51833. //# sourceMappingURL=babylon.edgesRenderer.js.map
  51834. var BABYLON;
  51835. (function (BABYLON) {
  51836. var TonemappingOperator;
  51837. (function (TonemappingOperator) {
  51838. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  51839. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  51840. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  51841. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  51842. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  51843. ;
  51844. var TonemapPostProcess = (function (_super) {
  51845. __extends(TonemapPostProcess, _super);
  51846. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  51847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51848. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51849. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  51850. _this._operator = _operator;
  51851. _this.exposureAdjustment = exposureAdjustment;
  51852. var defines = "#define ";
  51853. if (_this._operator === TonemappingOperator.Hable)
  51854. defines += "HABLE_TONEMAPPING";
  51855. else if (_this._operator === TonemappingOperator.Reinhard)
  51856. defines += "REINHARD_TONEMAPPING";
  51857. else if (_this._operator === TonemappingOperator.HejiDawson)
  51858. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51859. else if (_this._operator === TonemappingOperator.Photographic)
  51860. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51861. //sadly a second call to create the effect.
  51862. _this.updateEffect(defines);
  51863. _this.onApply = function (effect) {
  51864. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51865. };
  51866. return _this;
  51867. }
  51868. return TonemapPostProcess;
  51869. }(BABYLON.PostProcess));
  51870. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51871. })(BABYLON || (BABYLON = {}));
  51872. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  51873. var BABYLON;
  51874. (function (BABYLON) {
  51875. var ReflectionProbe = (function () {
  51876. function ReflectionProbe(name, size, scene, generateMipMaps) {
  51877. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51878. var _this = this;
  51879. this.name = name;
  51880. this._viewMatrix = BABYLON.Matrix.Identity();
  51881. this._target = BABYLON.Vector3.Zero();
  51882. this._add = BABYLON.Vector3.Zero();
  51883. this.invertYAxis = false;
  51884. this.position = BABYLON.Vector3.Zero();
  51885. this._scene = scene;
  51886. this._scene.reflectionProbes.push(this);
  51887. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  51888. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  51889. switch (faceIndex) {
  51890. case 0:
  51891. _this._add.copyFromFloats(1, 0, 0);
  51892. break;
  51893. case 1:
  51894. _this._add.copyFromFloats(-1, 0, 0);
  51895. break;
  51896. case 2:
  51897. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  51898. break;
  51899. case 3:
  51900. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  51901. break;
  51902. case 4:
  51903. _this._add.copyFromFloats(0, 0, 1);
  51904. break;
  51905. case 5:
  51906. _this._add.copyFromFloats(0, 0, -1);
  51907. break;
  51908. }
  51909. if (_this._attachedMesh) {
  51910. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  51911. }
  51912. _this.position.addToRef(_this._add, _this._target);
  51913. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  51914. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  51915. });
  51916. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  51917. scene.updateTransformMatrix(true);
  51918. });
  51919. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  51920. }
  51921. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  51922. get: function () {
  51923. return this._renderTargetTexture.refreshRate;
  51924. },
  51925. set: function (value) {
  51926. this._renderTargetTexture.refreshRate = value;
  51927. },
  51928. enumerable: true,
  51929. configurable: true
  51930. });
  51931. ReflectionProbe.prototype.getScene = function () {
  51932. return this._scene;
  51933. };
  51934. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  51935. get: function () {
  51936. return this._renderTargetTexture;
  51937. },
  51938. enumerable: true,
  51939. configurable: true
  51940. });
  51941. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  51942. get: function () {
  51943. return this._renderTargetTexture.renderList;
  51944. },
  51945. enumerable: true,
  51946. configurable: true
  51947. });
  51948. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  51949. this._attachedMesh = mesh;
  51950. };
  51951. ReflectionProbe.prototype.dispose = function () {
  51952. var index = this._scene.reflectionProbes.indexOf(this);
  51953. if (index !== -1) {
  51954. // Remove from the scene if found
  51955. this._scene.reflectionProbes.splice(index, 1);
  51956. }
  51957. if (this._renderTargetTexture) {
  51958. this._renderTargetTexture.dispose();
  51959. this._renderTargetTexture = null;
  51960. }
  51961. };
  51962. return ReflectionProbe;
  51963. }());
  51964. BABYLON.ReflectionProbe = ReflectionProbe;
  51965. })(BABYLON || (BABYLON = {}));
  51966. //# sourceMappingURL=babylon.reflectionProbe.js.map
  51967. var BABYLON;
  51968. (function (BABYLON) {
  51969. var SolidParticle = (function () {
  51970. /**
  51971. * Creates a Solid Particle object.
  51972. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51973. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51974. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51975. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  51976. * `shapeId` (integer) is the model shape identifier in the SPS.
  51977. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51978. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  51979. */
  51980. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51981. this.idx = 0; // particle global index
  51982. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  51983. this.position = BABYLON.Vector3.Zero(); // position
  51984. this.rotation = BABYLON.Vector3.Zero(); // rotation
  51985. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  51986. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  51987. this.velocity = BABYLON.Vector3.Zero(); // velocity
  51988. this.alive = true; // alive
  51989. this.isVisible = true; // visibility
  51990. this._pos = 0; // index of this particle in the global "positions" array
  51991. this.shapeId = 0; // model shape id
  51992. this.idxInShape = 0; // index of the particle in its shape id
  51993. this.idx = particleIndex;
  51994. this._pos = positionIndex;
  51995. this._model = model;
  51996. this.shapeId = shapeId;
  51997. this.idxInShape = idxInShape;
  51998. this._sps = sps;
  51999. if (modelBoundingInfo) {
  52000. this._modelBoundingInfo = modelBoundingInfo;
  52001. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52002. }
  52003. }
  52004. Object.defineProperty(SolidParticle.prototype, "scale", {
  52005. /**
  52006. * legacy support, changed scale to scaling
  52007. */
  52008. get: function () {
  52009. return this.scaling;
  52010. },
  52011. set: function (scale) {
  52012. this.scaling = scale;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52018. /**
  52019. * legacy support, changed quaternion to rotationQuaternion
  52020. */
  52021. get: function () {
  52022. return this.rotationQuaternion;
  52023. },
  52024. set: function (q) {
  52025. this.rotationQuaternion = q;
  52026. },
  52027. enumerable: true,
  52028. configurable: true
  52029. });
  52030. /**
  52031. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52032. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52033. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  52034. */
  52035. SolidParticle.prototype.intersectsMesh = function (target) {
  52036. if (!this._boundingInfo || !target._boundingInfo) {
  52037. return false;
  52038. }
  52039. if (this._sps._bSphereOnly) {
  52040. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52041. }
  52042. return this._boundingInfo.intersects(target._boundingInfo, false);
  52043. };
  52044. return SolidParticle;
  52045. }());
  52046. BABYLON.SolidParticle = SolidParticle;
  52047. var ModelShape = (function () {
  52048. /**
  52049. * 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.
  52050. * SPS internal tool, don't use it manually.
  52051. */
  52052. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  52053. this.shapeID = id;
  52054. this._shape = shape;
  52055. this._shapeUV = shapeUV;
  52056. this._positionFunction = posFunction;
  52057. this._vertexFunction = vtxFunction;
  52058. }
  52059. return ModelShape;
  52060. }());
  52061. BABYLON.ModelShape = ModelShape;
  52062. })(BABYLON || (BABYLON = {}));
  52063. //# sourceMappingURL=babylon.solidParticle.js.map
  52064. var BABYLON;
  52065. (function (BABYLON) {
  52066. /**
  52067. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52068. */
  52069. var SolidParticleSystem = (function () {
  52070. /**
  52071. * Creates a SPS (Solid Particle System) object.
  52072. * `name` (String) is the SPS name, this will be the underlying mesh name.
  52073. * `scene` (Scene) is the scene in which the SPS is added.
  52074. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  52075. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  52076. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  52077. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52078. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52079. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52080. */
  52081. function SolidParticleSystem(name, scene, options) {
  52082. // public members
  52083. /**
  52084. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52085. * Example : var p = SPS.particles[i];
  52086. */
  52087. this.particles = new Array();
  52088. /**
  52089. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52090. */
  52091. this.nbParticles = 0;
  52092. /**
  52093. * If the particles must ever face the camera (default false). Useful for planar particles.
  52094. */
  52095. this.billboard = false;
  52096. /**
  52097. * Recompute normals when adding a shape
  52098. */
  52099. this.recomputeNormals = true;
  52100. /**
  52101. * This a counter ofr your own usage. It's not set by any SPS functions.
  52102. */
  52103. this.counter = 0;
  52104. /**
  52105. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52106. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52107. */
  52108. this.vars = {};
  52109. this._positions = new Array();
  52110. this._indices = new Array();
  52111. this._normals = new Array();
  52112. this._colors = new Array();
  52113. this._uvs = new Array();
  52114. this._index = 0; // indices index
  52115. this._updatable = true;
  52116. this._pickable = false;
  52117. this._isVisibilityBoxLocked = false;
  52118. this._alwaysVisible = false;
  52119. this._shapeCounter = 0;
  52120. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  52121. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52122. this._computeParticleColor = true;
  52123. this._computeParticleTexture = true;
  52124. this._computeParticleRotation = true;
  52125. this._computeParticleVertex = false;
  52126. this._computeBoundingBox = false;
  52127. this._cam_axisZ = BABYLON.Vector3.Zero();
  52128. this._cam_axisY = BABYLON.Vector3.Zero();
  52129. this._cam_axisX = BABYLON.Vector3.Zero();
  52130. this._axisX = BABYLON.Axis.X;
  52131. this._axisY = BABYLON.Axis.Y;
  52132. this._axisZ = BABYLON.Axis.Z;
  52133. this._camDir = BABYLON.Vector3.Zero();
  52134. this._rotMatrix = new BABYLON.Matrix();
  52135. this._invertMatrix = new BABYLON.Matrix();
  52136. this._rotated = BABYLON.Vector3.Zero();
  52137. this._quaternion = new BABYLON.Quaternion();
  52138. this._vertex = BABYLON.Vector3.Zero();
  52139. this._normal = BABYLON.Vector3.Zero();
  52140. this._yaw = 0.0;
  52141. this._pitch = 0.0;
  52142. this._roll = 0.0;
  52143. this._halfroll = 0.0;
  52144. this._halfpitch = 0.0;
  52145. this._halfyaw = 0.0;
  52146. this._sinRoll = 0.0;
  52147. this._cosRoll = 0.0;
  52148. this._sinPitch = 0.0;
  52149. this._cosPitch = 0.0;
  52150. this._sinYaw = 0.0;
  52151. this._cosYaw = 0.0;
  52152. this._w = 0.0;
  52153. this._mustUnrotateFixedNormals = false;
  52154. this._minimum = BABYLON.Tmp.Vector3[0];
  52155. this._maximum = BABYLON.Tmp.Vector3[1];
  52156. this._scale = BABYLON.Tmp.Vector3[2];
  52157. this._translation = BABYLON.Tmp.Vector3[3];
  52158. this._minBbox = BABYLON.Tmp.Vector3[4];
  52159. this._maxBbox = BABYLON.Tmp.Vector3[5];
  52160. this._particlesIntersect = false;
  52161. this._bSphereOnly = false;
  52162. this._bSphereRadiusFactor = 1.0;
  52163. this.name = name;
  52164. this._scene = scene;
  52165. this._camera = scene.activeCamera;
  52166. this._pickable = options ? options.isPickable : false;
  52167. this._particlesIntersect = options ? options.particleIntersection : false;
  52168. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52169. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52170. if (options && options.updatable) {
  52171. this._updatable = options.updatable;
  52172. }
  52173. else {
  52174. this._updatable = true;
  52175. }
  52176. if (this._pickable) {
  52177. this.pickedParticles = [];
  52178. }
  52179. }
  52180. /**
  52181. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52182. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52183. */
  52184. SolidParticleSystem.prototype.buildMesh = function () {
  52185. if (this.nbParticles === 0) {
  52186. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52187. this.addShape(triangle, 1);
  52188. triangle.dispose();
  52189. }
  52190. this._positions32 = new Float32Array(this._positions);
  52191. this._uvs32 = new Float32Array(this._uvs);
  52192. this._colors32 = new Float32Array(this._colors);
  52193. if (this.recomputeNormals) {
  52194. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  52195. }
  52196. this._normals32 = new Float32Array(this._normals);
  52197. this._fixedNormal32 = new Float32Array(this._normals);
  52198. if (this._mustUnrotateFixedNormals) {
  52199. this._unrotateFixedNormals();
  52200. }
  52201. var vertexData = new BABYLON.VertexData();
  52202. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52203. vertexData.indices = this._indices;
  52204. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52205. if (this._uvs32) {
  52206. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52207. ;
  52208. }
  52209. if (this._colors32) {
  52210. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52211. }
  52212. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52213. vertexData.applyToMesh(mesh, this._updatable);
  52214. this.mesh = mesh;
  52215. this.mesh.isPickable = this._pickable;
  52216. // free memory
  52217. this._positions = null;
  52218. this._normals = null;
  52219. this._uvs = null;
  52220. this._colors = null;
  52221. if (!this._updatable) {
  52222. this.particles.length = 0;
  52223. }
  52224. return mesh;
  52225. };
  52226. /**
  52227. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52228. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52229. * Thus the particles generated from `digest()` have their property `position` set yet.
  52230. * `mesh` ( Mesh ) is the mesh to be digested
  52231. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  52232. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52233. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52234. */
  52235. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52236. var size = (options && options.facetNb) || 1;
  52237. var number = (options && options.number);
  52238. var delta = (options && options.delta) || 0;
  52239. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52240. var meshInd = mesh.getIndices();
  52241. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52242. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52243. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52244. var f = 0; // facet counter
  52245. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52246. // compute size from number
  52247. if (number) {
  52248. number = (number > totalFacets) ? totalFacets : number;
  52249. size = Math.round(totalFacets / number);
  52250. delta = 0;
  52251. }
  52252. else {
  52253. size = (size > totalFacets) ? totalFacets : size;
  52254. }
  52255. var facetPos = []; // submesh positions
  52256. var facetInd = []; // submesh indices
  52257. var facetUV = []; // submesh UV
  52258. var facetCol = []; // submesh colors
  52259. var barycenter = BABYLON.Tmp.Vector3[0];
  52260. var rand;
  52261. var sizeO = size;
  52262. while (f < totalFacets) {
  52263. size = sizeO + Math.floor((1 + delta) * Math.random());
  52264. if (f > totalFacets - size) {
  52265. size = totalFacets - f;
  52266. }
  52267. // reset temp arrays
  52268. facetPos.length = 0;
  52269. facetInd.length = 0;
  52270. facetUV.length = 0;
  52271. facetCol.length = 0;
  52272. // iterate over "size" facets
  52273. var fi = 0;
  52274. for (var j = f * 3; j < (f + size) * 3; j++) {
  52275. facetInd.push(fi);
  52276. var i = meshInd[j];
  52277. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52278. if (meshUV) {
  52279. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52280. }
  52281. if (meshCol) {
  52282. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52283. }
  52284. fi++;
  52285. }
  52286. // create a model shape for each single particle
  52287. var idx = this.nbParticles;
  52288. var shape = this._posToShape(facetPos);
  52289. var shapeUV = this._uvsToShapeUV(facetUV);
  52290. // compute the barycenter of the shape
  52291. var v;
  52292. for (v = 0; v < shape.length; v++) {
  52293. barycenter.addInPlace(shape[v]);
  52294. }
  52295. barycenter.scaleInPlace(1 / shape.length);
  52296. // shift the shape from its barycenter to the origin
  52297. for (v = 0; v < shape.length; v++) {
  52298. shape[v].subtractInPlace(barycenter);
  52299. }
  52300. var bInfo;
  52301. if (this._particlesIntersect) {
  52302. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52303. }
  52304. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  52305. // add the particle in the SPS
  52306. var currentPos = this._positions.length;
  52307. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52308. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  52309. // initialize the particle position
  52310. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52311. this._index += shape.length;
  52312. idx++;
  52313. this.nbParticles++;
  52314. this._shapeCounter++;
  52315. f += size;
  52316. }
  52317. return this;
  52318. };
  52319. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52320. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52321. var index = 0;
  52322. var idx = 0;
  52323. for (var p = 0; p < this.particles.length; p++) {
  52324. this._particle = this.particles[p];
  52325. this._shape = this._particle._model._shape;
  52326. if (this._particle.rotationQuaternion) {
  52327. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52328. }
  52329. else {
  52330. this._yaw = this._particle.rotation.y;
  52331. this._pitch = this._particle.rotation.x;
  52332. this._roll = this._particle.rotation.z;
  52333. this._quaternionRotationYPR();
  52334. }
  52335. this._quaternionToRotationMatrix();
  52336. this._rotMatrix.invertToRef(this._invertMatrix);
  52337. for (var pt = 0; pt < this._shape.length; pt++) {
  52338. idx = index + pt * 3;
  52339. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52340. this._fixedNormal32[idx] = this._normal.x;
  52341. this._fixedNormal32[idx + 1] = this._normal.y;
  52342. this._fixedNormal32[idx + 2] = this._normal.z;
  52343. }
  52344. index = idx + 3;
  52345. }
  52346. };
  52347. //reset copy
  52348. SolidParticleSystem.prototype._resetCopy = function () {
  52349. this._copy.position.x = 0;
  52350. this._copy.position.y = 0;
  52351. this._copy.position.z = 0;
  52352. this._copy.rotation.x = 0;
  52353. this._copy.rotation.y = 0;
  52354. this._copy.rotation.z = 0;
  52355. this._copy.rotationQuaternion = null;
  52356. this._copy.scaling.x = 1;
  52357. this._copy.scaling.y = 1;
  52358. this._copy.scaling.z = 1;
  52359. this._copy.uvs.x = 0;
  52360. this._copy.uvs.y = 0;
  52361. this._copy.uvs.z = 1;
  52362. this._copy.uvs.w = 1;
  52363. this._copy.color = null;
  52364. };
  52365. // _meshBuilder : inserts the shape model in the global SPS mesh
  52366. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52367. var i;
  52368. var u = 0;
  52369. var c = 0;
  52370. var n = 0;
  52371. this._resetCopy();
  52372. if (options && options.positionFunction) {
  52373. options.positionFunction(this._copy, idx, idxInShape);
  52374. this._mustUnrotateFixedNormals = true;
  52375. }
  52376. if (this._copy.rotationQuaternion) {
  52377. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52378. }
  52379. else {
  52380. this._yaw = this._copy.rotation.y;
  52381. this._pitch = this._copy.rotation.x;
  52382. this._roll = this._copy.rotation.z;
  52383. this._quaternionRotationYPR();
  52384. }
  52385. this._quaternionToRotationMatrix();
  52386. for (i = 0; i < shape.length; i++) {
  52387. this._vertex.x = shape[i].x;
  52388. this._vertex.y = shape[i].y;
  52389. this._vertex.z = shape[i].z;
  52390. if (options && options.vertexFunction) {
  52391. options.vertexFunction(this._copy, this._vertex, i);
  52392. }
  52393. this._vertex.x *= this._copy.scaling.x;
  52394. this._vertex.y *= this._copy.scaling.y;
  52395. this._vertex.z *= this._copy.scaling.z;
  52396. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52397. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52398. if (meshUV) {
  52399. 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);
  52400. u += 2;
  52401. }
  52402. if (this._copy.color) {
  52403. this._color = this._copy.color;
  52404. }
  52405. else if (meshCol && meshCol[c] !== undefined) {
  52406. this._color.r = meshCol[c];
  52407. this._color.g = meshCol[c + 1];
  52408. this._color.b = meshCol[c + 2];
  52409. this._color.a = meshCol[c + 3];
  52410. }
  52411. else {
  52412. this._color.r = 1;
  52413. this._color.g = 1;
  52414. this._color.b = 1;
  52415. this._color.a = 1;
  52416. }
  52417. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52418. c += 4;
  52419. if (!this.recomputeNormals && meshNor) {
  52420. this._normal.x = meshNor[n];
  52421. this._normal.y = meshNor[n + 1];
  52422. this._normal.z = meshNor[n + 2];
  52423. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52424. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52425. n += 3;
  52426. }
  52427. }
  52428. for (i = 0; i < meshInd.length; i++) {
  52429. indices.push(p + meshInd[i]);
  52430. }
  52431. if (this._pickable) {
  52432. var nbfaces = meshInd.length / 3;
  52433. for (i = 0; i < nbfaces; i++) {
  52434. this.pickedParticles.push({ idx: idx, faceId: i });
  52435. }
  52436. }
  52437. return this._copy;
  52438. };
  52439. // returns a shape array from positions array
  52440. SolidParticleSystem.prototype._posToShape = function (positions) {
  52441. var shape = [];
  52442. for (var i = 0; i < positions.length; i += 3) {
  52443. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52444. }
  52445. return shape;
  52446. };
  52447. // returns a shapeUV array from a Vector4 uvs
  52448. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52449. var shapeUV = [];
  52450. if (uvs) {
  52451. for (var i = 0; i < uvs.length; i++)
  52452. shapeUV.push(uvs[i]);
  52453. }
  52454. return shapeUV;
  52455. };
  52456. // adds a new particle object in the particles array
  52457. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  52458. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  52459. this.particles.push(sp);
  52460. return sp;
  52461. };
  52462. /**
  52463. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52464. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52465. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  52466. * `nb` (positive integer) the number of particles to be created from this model
  52467. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  52468. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  52469. */
  52470. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52471. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52472. var meshInd = mesh.getIndices();
  52473. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52474. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52475. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52476. var bbInfo;
  52477. if (this._particlesIntersect) {
  52478. bbInfo = mesh.getBoundingInfo();
  52479. }
  52480. var shape = this._posToShape(meshPos);
  52481. var shapeUV = this._uvsToShapeUV(meshUV);
  52482. var posfunc = options ? options.positionFunction : null;
  52483. var vtxfunc = options ? options.vertexFunction : null;
  52484. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  52485. // particles
  52486. var sp;
  52487. var currentCopy;
  52488. var idx = this.nbParticles;
  52489. for (var i = 0; i < nb; i++) {
  52490. var currentPos = this._positions.length;
  52491. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52492. if (this._updatable) {
  52493. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  52494. sp.position.copyFrom(currentCopy.position);
  52495. sp.rotation.copyFrom(currentCopy.rotation);
  52496. if (currentCopy.rotationQuaternion) {
  52497. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52498. }
  52499. if (currentCopy.color) {
  52500. sp.color.copyFrom(currentCopy.color);
  52501. }
  52502. sp.scaling.copyFrom(currentCopy.scaling);
  52503. sp.uvs.copyFrom(currentCopy.uvs);
  52504. }
  52505. this._index += shape.length;
  52506. idx++;
  52507. }
  52508. this.nbParticles += nb;
  52509. this._shapeCounter++;
  52510. return this._shapeCounter - 1;
  52511. };
  52512. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52513. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52514. this._resetCopy();
  52515. if (particle._model._positionFunction) {
  52516. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52517. }
  52518. if (this._copy.rotationQuaternion) {
  52519. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52520. }
  52521. else {
  52522. this._yaw = this._copy.rotation.y;
  52523. this._pitch = this._copy.rotation.x;
  52524. this._roll = this._copy.rotation.z;
  52525. this._quaternionRotationYPR();
  52526. }
  52527. this._quaternionToRotationMatrix();
  52528. this._shape = particle._model._shape;
  52529. for (var pt = 0; pt < this._shape.length; pt++) {
  52530. this._vertex.x = this._shape[pt].x;
  52531. this._vertex.y = this._shape[pt].y;
  52532. this._vertex.z = this._shape[pt].z;
  52533. if (particle._model._vertexFunction) {
  52534. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52535. }
  52536. this._vertex.x *= this._copy.scaling.x;
  52537. this._vertex.y *= this._copy.scaling.y;
  52538. this._vertex.z *= this._copy.scaling.z;
  52539. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52540. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52541. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52542. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52543. }
  52544. particle.position.x = 0.0;
  52545. particle.position.y = 0.0;
  52546. particle.position.z = 0.0;
  52547. particle.rotation.x = 0.0;
  52548. particle.rotation.y = 0.0;
  52549. particle.rotation.z = 0.0;
  52550. particle.rotationQuaternion = null;
  52551. particle.scaling.x = 1.0;
  52552. particle.scaling.y = 1.0;
  52553. particle.scaling.z = 1.0;
  52554. };
  52555. /**
  52556. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52557. * Returns the SPS.
  52558. */
  52559. SolidParticleSystem.prototype.rebuildMesh = function () {
  52560. for (var p = 0; p < this.particles.length; p++) {
  52561. this._rebuildParticle(this.particles[p]);
  52562. }
  52563. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52564. return this;
  52565. };
  52566. /**
  52567. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52568. * This method calls `updateParticle()` for each particle of the SPS.
  52569. * For an animated SPS, it is usually called within the render loop.
  52570. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52571. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52572. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52573. * Returns the SPS.
  52574. */
  52575. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52576. if (start === void 0) { start = 0; }
  52577. if (end === void 0) { end = this.nbParticles - 1; }
  52578. if (update === void 0) { update = true; }
  52579. if (!this._updatable) {
  52580. return;
  52581. }
  52582. // custom beforeUpdate
  52583. this.beforeUpdateParticles(start, end, update);
  52584. this._cam_axisX.x = 1.0;
  52585. this._cam_axisX.y = 0.0;
  52586. this._cam_axisX.z = 0.0;
  52587. this._cam_axisY.x = 0.0;
  52588. this._cam_axisY.y = 1.0;
  52589. this._cam_axisY.z = 0.0;
  52590. this._cam_axisZ.x = 0.0;
  52591. this._cam_axisZ.y = 0.0;
  52592. this._cam_axisZ.z = 1.0;
  52593. // if the particles will always face the camera
  52594. if (this.billboard) {
  52595. // compute the camera position and un-rotate it by the current mesh rotation
  52596. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  52597. this._quaternionToRotationMatrix();
  52598. this._rotMatrix.invertToRef(this._invertMatrix);
  52599. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  52600. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52601. this._cam_axisZ.normalize();
  52602. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  52603. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  52604. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52605. this._cam_axisY.normalize();
  52606. this._cam_axisX.normalize();
  52607. }
  52608. }
  52609. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52610. var idx = 0; // current position index in the global array positions32
  52611. var index = 0; // position start index in the global array positions32 of the current particle
  52612. var colidx = 0; // current color index in the global array colors32
  52613. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52614. var uvidx = 0; // current uv index in the global array uvs32
  52615. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52616. var pt = 0; // current index in the particle model shape
  52617. if (this.mesh.isFacetDataEnabled) {
  52618. this._computeBoundingBox = true;
  52619. }
  52620. if (this._computeBoundingBox) {
  52621. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52622. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52623. }
  52624. // particle loop
  52625. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52626. index = this.particles[start]._pos;
  52627. for (var p = start; p <= end; p++) {
  52628. this._particle = this.particles[p];
  52629. this._shape = this._particle._model._shape;
  52630. this._shapeUV = this._particle._model._shapeUV;
  52631. // call to custom user function to update the particle properties
  52632. this.updateParticle(this._particle);
  52633. if (this._particle.isVisible) {
  52634. // particle rotation matrix
  52635. if (this.billboard) {
  52636. this._particle.rotation.x = 0.0;
  52637. this._particle.rotation.y = 0.0;
  52638. }
  52639. if (this._computeParticleRotation || this.billboard) {
  52640. if (this._particle.rotationQuaternion) {
  52641. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52642. }
  52643. else {
  52644. this._yaw = this._particle.rotation.y;
  52645. this._pitch = this._particle.rotation.x;
  52646. this._roll = this._particle.rotation.z;
  52647. this._quaternionRotationYPR();
  52648. }
  52649. this._quaternionToRotationMatrix();
  52650. }
  52651. // particle vertex loop
  52652. for (pt = 0; pt < this._shape.length; pt++) {
  52653. idx = index + pt * 3;
  52654. colidx = colorIndex + pt * 4;
  52655. uvidx = uvIndex + pt * 2;
  52656. this._vertex.x = this._shape[pt].x;
  52657. this._vertex.y = this._shape[pt].y;
  52658. this._vertex.z = this._shape[pt].z;
  52659. if (this._computeParticleVertex) {
  52660. this.updateParticleVertex(this._particle, this._vertex, pt);
  52661. }
  52662. // positions
  52663. this._vertex.x *= this._particle.scaling.x;
  52664. this._vertex.y *= this._particle.scaling.y;
  52665. this._vertex.z *= this._particle.scaling.z;
  52666. 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];
  52667. 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;
  52668. 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;
  52669. 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;
  52670. 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;
  52671. 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;
  52672. 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;
  52673. if (this._computeBoundingBox) {
  52674. if (this._positions32[idx] < this._minimum.x) {
  52675. this._minimum.x = this._positions32[idx];
  52676. }
  52677. if (this._positions32[idx] > this._maximum.x) {
  52678. this._maximum.x = this._positions32[idx];
  52679. }
  52680. if (this._positions32[idx + 1] < this._minimum.y) {
  52681. this._minimum.y = this._positions32[idx + 1];
  52682. }
  52683. if (this._positions32[idx + 1] > this._maximum.y) {
  52684. this._maximum.y = this._positions32[idx + 1];
  52685. }
  52686. if (this._positions32[idx + 2] < this._minimum.z) {
  52687. this._minimum.z = this._positions32[idx + 2];
  52688. }
  52689. if (this._positions32[idx + 2] > this._maximum.z) {
  52690. this._maximum.z = this._positions32[idx + 2];
  52691. }
  52692. }
  52693. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52694. if (!this._computeParticleVertex) {
  52695. this._normal.x = this._fixedNormal32[idx];
  52696. this._normal.y = this._fixedNormal32[idx + 1];
  52697. this._normal.z = this._fixedNormal32[idx + 2];
  52698. 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]);
  52699. 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]);
  52700. 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]);
  52701. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52702. 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;
  52703. 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;
  52704. }
  52705. if (this._computeParticleColor) {
  52706. this._colors32[colidx] = this._particle.color.r;
  52707. this._colors32[colidx + 1] = this._particle.color.g;
  52708. this._colors32[colidx + 2] = this._particle.color.b;
  52709. this._colors32[colidx + 3] = this._particle.color.a;
  52710. }
  52711. if (this._computeParticleTexture) {
  52712. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52713. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52714. }
  52715. }
  52716. }
  52717. else {
  52718. for (pt = 0; pt < this._shape.length; pt++) {
  52719. idx = index + pt * 3;
  52720. colidx = colorIndex + pt * 4;
  52721. uvidx = uvIndex + pt * 2;
  52722. this._positions32[idx] = this._camera.position.x;
  52723. this._positions32[idx + 1] = this._camera.position.y;
  52724. this._positions32[idx + 2] = this._camera.position.z;
  52725. this._normals32[idx] = 0.0;
  52726. this._normals32[idx + 1] = 0.0;
  52727. this._normals32[idx + 2] = 0.0;
  52728. if (this._computeParticleColor) {
  52729. this._colors32[colidx] = this._particle.color.r;
  52730. this._colors32[colidx + 1] = this._particle.color.g;
  52731. this._colors32[colidx + 2] = this._particle.color.b;
  52732. this._colors32[colidx + 3] = this._particle.color.a;
  52733. }
  52734. if (this._computeParticleTexture) {
  52735. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52736. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52737. }
  52738. }
  52739. }
  52740. // if the particle intersections must be computed : update the bbInfo
  52741. if (this._particlesIntersect) {
  52742. var bInfo = this._particle._boundingInfo;
  52743. var bBox = bInfo.boundingBox;
  52744. var bSphere = bInfo.boundingSphere;
  52745. if (!this._bSphereOnly) {
  52746. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52747. for (var b = 0; b < bBox.vectors.length; b++) {
  52748. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52749. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52750. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52751. 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];
  52752. 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;
  52753. 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;
  52754. 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;
  52755. 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;
  52756. 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;
  52757. 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;
  52758. }
  52759. bBox._update(this.mesh._worldMatrix);
  52760. }
  52761. // place and scale the particle bouding sphere in the SPS local system, then update it
  52762. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52763. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52764. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52765. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52766. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52767. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52768. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52769. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52770. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52771. 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));
  52772. bSphere._update(this.mesh._worldMatrix);
  52773. }
  52774. // increment indexes for the next particle
  52775. index = idx + 3;
  52776. colorIndex = colidx + 4;
  52777. uvIndex = uvidx + 2;
  52778. }
  52779. // if the VBO must be updated
  52780. if (update) {
  52781. if (this._computeParticleColor) {
  52782. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52783. }
  52784. if (this._computeParticleTexture) {
  52785. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52786. }
  52787. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52788. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52789. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52790. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52791. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52792. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  52793. for (var i = 0; i < this._normals32.length; i++) {
  52794. this._fixedNormal32[i] = this._normals32[i];
  52795. }
  52796. }
  52797. if (!this.mesh.areNormalsFrozen) {
  52798. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52799. }
  52800. }
  52801. }
  52802. if (this._computeBoundingBox) {
  52803. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52804. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52805. }
  52806. this.afterUpdateParticles(start, end, update);
  52807. return this;
  52808. };
  52809. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52810. this._halfroll = this._roll * 0.5;
  52811. this._halfpitch = this._pitch * 0.5;
  52812. this._halfyaw = this._yaw * 0.5;
  52813. this._sinRoll = Math.sin(this._halfroll);
  52814. this._cosRoll = Math.cos(this._halfroll);
  52815. this._sinPitch = Math.sin(this._halfpitch);
  52816. this._cosPitch = Math.cos(this._halfpitch);
  52817. this._sinYaw = Math.sin(this._halfyaw);
  52818. this._cosYaw = Math.cos(this._halfyaw);
  52819. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  52820. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  52821. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  52822. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  52823. };
  52824. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52825. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52826. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52827. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52828. this._rotMatrix.m[3] = 0;
  52829. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52830. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52831. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52832. this._rotMatrix.m[7] = 0;
  52833. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52834. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52835. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52836. this._rotMatrix.m[11] = 0;
  52837. this._rotMatrix.m[12] = 0;
  52838. this._rotMatrix.m[13] = 0;
  52839. this._rotMatrix.m[14] = 0;
  52840. this._rotMatrix.m[15] = 1.0;
  52841. };
  52842. /**
  52843. * Disposes the SPS.
  52844. * Returns nothing.
  52845. */
  52846. SolidParticleSystem.prototype.dispose = function () {
  52847. this.mesh.dispose();
  52848. this.vars = null;
  52849. // drop references to internal big arrays for the GC
  52850. this._positions = null;
  52851. this._indices = null;
  52852. this._normals = null;
  52853. this._uvs = null;
  52854. this._colors = null;
  52855. this._positions32 = null;
  52856. this._normals32 = null;
  52857. this._fixedNormal32 = null;
  52858. this._uvs32 = null;
  52859. this._colors32 = null;
  52860. this.pickedParticles = null;
  52861. };
  52862. /**
  52863. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52864. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52865. * Returns the SPS.
  52866. */
  52867. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52868. if (!this._isVisibilityBoxLocked) {
  52869. this.mesh.refreshBoundingInfo();
  52870. }
  52871. return this;
  52872. };
  52873. /**
  52874. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52875. * @param size the size (float) of the visibility box
  52876. * note : this doesn't lock the SPS mesh bounding box.
  52877. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52878. */
  52879. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52880. var vis = size / 2;
  52881. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52882. };
  52883. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52884. // getter and setter
  52885. get: function () {
  52886. return this._alwaysVisible;
  52887. },
  52888. /**
  52889. * Sets the SPS as always visible or not
  52890. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52891. */
  52892. set: function (val) {
  52893. this._alwaysVisible = val;
  52894. this.mesh.alwaysSelectAsActiveMesh = val;
  52895. },
  52896. enumerable: true,
  52897. configurable: true
  52898. });
  52899. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52900. get: function () {
  52901. return this._isVisibilityBoxLocked;
  52902. },
  52903. /**
  52904. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52905. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52906. */
  52907. set: function (val) {
  52908. this._isVisibilityBoxLocked = val;
  52909. this.mesh.getBoundingInfo().isLocked = val;
  52910. },
  52911. enumerable: true,
  52912. configurable: true
  52913. });
  52914. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52915. // getters
  52916. get: function () {
  52917. return this._computeParticleRotation;
  52918. },
  52919. // Optimizer setters
  52920. /**
  52921. * Tells to `setParticles()` to compute the particle rotations or not.
  52922. * Default value : true. The SPS is faster when it's set to false.
  52923. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52924. */
  52925. set: function (val) {
  52926. this._computeParticleRotation = val;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52932. get: function () {
  52933. return this._computeParticleColor;
  52934. },
  52935. /**
  52936. * Tells to `setParticles()` to compute the particle colors or not.
  52937. * Default value : true. The SPS is faster when it's set to false.
  52938. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52939. */
  52940. set: function (val) {
  52941. this._computeParticleColor = val;
  52942. },
  52943. enumerable: true,
  52944. configurable: true
  52945. });
  52946. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52947. get: function () {
  52948. return this._computeParticleTexture;
  52949. },
  52950. /**
  52951. * Tells to `setParticles()` to compute the particle textures or not.
  52952. * Default value : true. The SPS is faster when it's set to false.
  52953. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52954. */
  52955. set: function (val) {
  52956. this._computeParticleTexture = val;
  52957. },
  52958. enumerable: true,
  52959. configurable: true
  52960. });
  52961. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52962. get: function () {
  52963. return this._computeParticleVertex;
  52964. },
  52965. /**
  52966. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52967. * Default value : false. The SPS is faster when it's set to false.
  52968. * Note : the particle custom vertex positions aren't stored values.
  52969. */
  52970. set: function (val) {
  52971. this._computeParticleVertex = val;
  52972. },
  52973. enumerable: true,
  52974. configurable: true
  52975. });
  52976. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52977. get: function () {
  52978. return this._computeBoundingBox;
  52979. },
  52980. /**
  52981. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52982. */
  52983. set: function (val) {
  52984. this._computeBoundingBox = val;
  52985. },
  52986. enumerable: true,
  52987. configurable: true
  52988. });
  52989. // =======================================================================
  52990. // Particle behavior logic
  52991. // these following methods may be overwritten by the user to fit his needs
  52992. /**
  52993. * This function does nothing. It may be overwritten to set all the particle first values.
  52994. * The SPS doesn't call this function, you may have to call it by your own.
  52995. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52996. */
  52997. SolidParticleSystem.prototype.initParticles = function () {
  52998. };
  52999. /**
  53000. * This function does nothing. It may be overwritten to recycle a particle.
  53001. * The SPS doesn't call this function, you may have to call it by your own.
  53002. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53003. */
  53004. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53005. return particle;
  53006. };
  53007. /**
  53008. * Updates a particle : this function should be overwritten by the user.
  53009. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53010. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53011. * ex : just set a particle position or velocity and recycle conditions
  53012. */
  53013. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53014. return particle;
  53015. };
  53016. /**
  53017. * Updates a vertex of a particle : it can be overwritten by the user.
  53018. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53019. * @param particle the current particle
  53020. * @param vertex the current index of the current particle
  53021. * @param pt the index of the current vertex in the particle shape
  53022. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53023. * ex : just set a vertex particle position
  53024. */
  53025. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53026. return vertex;
  53027. };
  53028. /**
  53029. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53030. * This does nothing and may be overwritten by the user.
  53031. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53032. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53033. * @param update the boolean update value actually passed to setParticles()
  53034. */
  53035. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53036. };
  53037. /**
  53038. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53039. * This will be passed three parameters.
  53040. * This does nothing and may be overwritten by the user.
  53041. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53042. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53043. * @param update the boolean update value actually passed to setParticles()
  53044. */
  53045. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53046. };
  53047. return SolidParticleSystem;
  53048. }());
  53049. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53050. })(BABYLON || (BABYLON = {}));
  53051. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. var Internals;
  53055. (function (Internals) {
  53056. var FileFaceOrientation = (function () {
  53057. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53058. this.name = name;
  53059. this.worldAxisForNormal = worldAxisForNormal;
  53060. this.worldAxisForFileX = worldAxisForFileX;
  53061. this.worldAxisForFileY = worldAxisForFileY;
  53062. }
  53063. return FileFaceOrientation;
  53064. }());
  53065. ;
  53066. /**
  53067. * Helper class dealing with the extraction of spherical polynomial dataArray
  53068. * from a cube map.
  53069. */
  53070. var CubeMapToSphericalPolynomialTools = (function () {
  53071. function CubeMapToSphericalPolynomialTools() {
  53072. }
  53073. /**
  53074. * Converts a cubemap to the according Spherical Polynomial data.
  53075. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53076. *
  53077. * @param cubeInfo The Cube map to extract the information from.
  53078. * @return The Spherical Polynomial data.
  53079. */
  53080. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53081. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53082. var totalSolidAngle = 0.0;
  53083. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53084. var du = 2.0 / cubeInfo.size;
  53085. var dv = du;
  53086. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53087. var minUV = du * 0.5 - 1.0;
  53088. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53089. var fileFace = this.FileFaces[faceIndex];
  53090. var dataArray = cubeInfo[fileFace.name];
  53091. var v = minUV;
  53092. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53093. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53094. // Because SP is still linear, so summation is fine in that basis.
  53095. for (var y = 0; y < cubeInfo.size; y++) {
  53096. var u = minUV;
  53097. for (var x = 0; x < cubeInfo.size; x++) {
  53098. // World direction (not normalised)
  53099. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53100. worldDirection.normalize();
  53101. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53102. if (1) {
  53103. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53104. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53105. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53106. var color = new BABYLON.Color3(r, g, b);
  53107. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53108. }
  53109. else {
  53110. if (faceIndex == 0) {
  53111. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53112. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53113. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53114. }
  53115. else if (faceIndex == 1) {
  53116. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53117. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53118. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53119. }
  53120. else if (faceIndex == 2) {
  53121. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53122. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53123. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53124. }
  53125. else if (faceIndex == 3) {
  53126. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53127. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53128. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53129. }
  53130. else if (faceIndex == 4) {
  53131. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53132. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53133. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53134. }
  53135. else if (faceIndex == 5) {
  53136. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53137. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53138. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53139. }
  53140. 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]);
  53141. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53142. }
  53143. totalSolidAngle += deltaSolidAngle;
  53144. u += du;
  53145. }
  53146. v += dv;
  53147. }
  53148. }
  53149. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53150. var correction = correctSolidAngle / totalSolidAngle;
  53151. sphericalHarmonics.scale(correction);
  53152. // Additionally scale by pi -- audit needed
  53153. sphericalHarmonics.scale(1.0 / Math.PI);
  53154. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53155. };
  53156. return CubeMapToSphericalPolynomialTools;
  53157. }());
  53158. CubeMapToSphericalPolynomialTools.FileFaces = [
  53159. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53160. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53161. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53162. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53163. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53164. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53165. ];
  53166. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53168. })(BABYLON || (BABYLON = {}));
  53169. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  53170. var BABYLON;
  53171. (function (BABYLON) {
  53172. var Internals;
  53173. (function (Internals) {
  53174. /**
  53175. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53176. */
  53177. var PanoramaToCubeMapTools = (function () {
  53178. function PanoramaToCubeMapTools() {
  53179. }
  53180. /**
  53181. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53182. *
  53183. * @param float32Array The source data.
  53184. * @param inputWidth The width of the input panorama.
  53185. * @param inputhHeight The height of the input panorama.
  53186. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53187. * @return The cubemap data
  53188. */
  53189. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53190. if (!float32Array) {
  53191. throw "ConvertPanoramaToCubemap: input cannot be null";
  53192. }
  53193. if (float32Array.length != inputWidth * inputHeight * 3) {
  53194. throw "ConvertPanoramaToCubemap: input size is wrong";
  53195. }
  53196. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53197. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53198. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53199. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53200. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53201. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53202. return {
  53203. front: textureFront,
  53204. back: textureBack,
  53205. left: textureLeft,
  53206. right: textureRight,
  53207. up: textureUp,
  53208. down: textureDown,
  53209. size: size
  53210. };
  53211. };
  53212. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53213. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53214. var textureArray = new Float32Array(buffer);
  53215. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53216. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53217. var dy = 1 / texSize;
  53218. var fy = 0;
  53219. for (var y = 0; y < texSize; y++) {
  53220. var xv1 = faceData[0];
  53221. var xv2 = faceData[2];
  53222. for (var x = 0; x < texSize; x++) {
  53223. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53224. v.normalize();
  53225. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53226. // 3 channels per pixels
  53227. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53228. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53229. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53230. xv1 = xv1.add(rotDX1);
  53231. xv2 = xv2.add(rotDX2);
  53232. }
  53233. fy += dy;
  53234. }
  53235. return textureArray;
  53236. };
  53237. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53238. var theta = Math.atan2(vDir.z, vDir.x);
  53239. var phi = Math.acos(vDir.y);
  53240. while (theta < -Math.PI)
  53241. theta += 2 * Math.PI;
  53242. while (theta > Math.PI)
  53243. theta -= 2 * Math.PI;
  53244. var dx = theta / Math.PI;
  53245. var dy = phi / Math.PI;
  53246. // recenter.
  53247. dx = dx * 0.5 + 0.5;
  53248. var px = Math.round(dx * inputWidth);
  53249. if (px < 0)
  53250. px = 0;
  53251. else if (px >= inputWidth)
  53252. px = inputWidth - 1;
  53253. var py = Math.round(dy * inputHeight);
  53254. if (py < 0)
  53255. py = 0;
  53256. else if (py >= inputHeight)
  53257. py = inputHeight - 1;
  53258. var inputY = (inputHeight - py - 1);
  53259. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53260. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53261. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53262. return {
  53263. r: r,
  53264. g: g,
  53265. b: b
  53266. };
  53267. };
  53268. return PanoramaToCubeMapTools;
  53269. }());
  53270. PanoramaToCubeMapTools.FACE_FRONT = [
  53271. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53272. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53273. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53274. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53275. ];
  53276. PanoramaToCubeMapTools.FACE_BACK = [
  53277. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53278. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53279. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53280. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53281. ];
  53282. PanoramaToCubeMapTools.FACE_RIGHT = [
  53283. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53284. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53285. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53286. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53287. ];
  53288. PanoramaToCubeMapTools.FACE_LEFT = [
  53289. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53290. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53291. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53292. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53293. ];
  53294. PanoramaToCubeMapTools.FACE_DOWN = [
  53295. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53296. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53297. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53298. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53299. ];
  53300. PanoramaToCubeMapTools.FACE_UP = [
  53301. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53302. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53303. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53304. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53305. ];
  53306. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53308. })(BABYLON || (BABYLON = {}));
  53309. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  53310. var BABYLON;
  53311. (function (BABYLON) {
  53312. var Internals;
  53313. (function (Internals) {
  53314. ;
  53315. /**
  53316. * This groups tools to convert HDR texture to native colors array.
  53317. */
  53318. var HDRTools = (function () {
  53319. function HDRTools() {
  53320. }
  53321. HDRTools.Ldexp = function (mantissa, exponent) {
  53322. if (exponent > 1023) {
  53323. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53324. }
  53325. if (exponent < -1074) {
  53326. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53327. }
  53328. return mantissa * Math.pow(2, exponent);
  53329. };
  53330. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53331. if (exponent > 0) {
  53332. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53333. float32array[index + 0] = red * exponent;
  53334. float32array[index + 1] = green * exponent;
  53335. float32array[index + 2] = blue * exponent;
  53336. }
  53337. else {
  53338. float32array[index + 0] = 0;
  53339. float32array[index + 1] = 0;
  53340. float32array[index + 2] = 0;
  53341. }
  53342. };
  53343. HDRTools.readStringLine = function (uint8array, startIndex) {
  53344. var line = "";
  53345. var character = "";
  53346. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  53347. character = String.fromCharCode(uint8array[i]);
  53348. if (character == "\n") {
  53349. break;
  53350. }
  53351. line += character;
  53352. }
  53353. return line;
  53354. };
  53355. /**
  53356. * Reads header information from an RGBE texture stored in a native array.
  53357. * More information on this format are available here:
  53358. * https://en.wikipedia.org/wiki/RGBE_image_format
  53359. *
  53360. * @param uint8array The binary file stored in native array.
  53361. * @return The header information.
  53362. */
  53363. HDRTools.RGBE_ReadHeader = function (uint8array) {
  53364. var height = 0;
  53365. var width = 0;
  53366. var line = this.readStringLine(uint8array, 0);
  53367. if (line[0] != '#' || line[1] != '?') {
  53368. throw "Bad HDR Format.";
  53369. }
  53370. var endOfHeader = false;
  53371. var findFormat = false;
  53372. var lineIndex = 0;
  53373. do {
  53374. lineIndex += (line.length + 1);
  53375. line = this.readStringLine(uint8array, lineIndex);
  53376. if (line == "FORMAT=32-bit_rle_rgbe") {
  53377. findFormat = true;
  53378. }
  53379. else if (line.length == 0) {
  53380. endOfHeader = true;
  53381. }
  53382. } while (!endOfHeader);
  53383. if (!findFormat) {
  53384. throw "HDR Bad header format, unsupported FORMAT";
  53385. }
  53386. lineIndex += (line.length + 1);
  53387. line = this.readStringLine(uint8array, lineIndex);
  53388. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  53389. var match = sizeRegexp.exec(line);
  53390. // TODO. Support +Y and -X if needed.
  53391. if (match.length < 3) {
  53392. throw "HDR Bad header format, no size";
  53393. }
  53394. width = parseInt(match[2]);
  53395. height = parseInt(match[1]);
  53396. if (width < 8 || width > 0x7fff) {
  53397. throw "HDR Bad header format, unsupported size";
  53398. }
  53399. lineIndex += (line.length + 1);
  53400. return {
  53401. height: height,
  53402. width: width,
  53403. dataPosition: lineIndex
  53404. };
  53405. };
  53406. /**
  53407. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  53408. * This RGBE texture needs to store the information as a panorama.
  53409. *
  53410. * More information on this format are available here:
  53411. * https://en.wikipedia.org/wiki/RGBE_image_format
  53412. *
  53413. * @param buffer The binary file stored in an array buffer.
  53414. * @param size The expected size of the extracted cubemap.
  53415. * @return The Cube Map information.
  53416. */
  53417. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  53418. var uint8array = new Uint8Array(buffer);
  53419. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  53420. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53421. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  53422. return cubeMapData;
  53423. };
  53424. /**
  53425. * Returns the pixels data extracted from an RGBE texture.
  53426. * This pixels will be stored left to right up to down in the R G B order in one array.
  53427. *
  53428. * More information on this format are available here:
  53429. * https://en.wikipedia.org/wiki/RGBE_image_format
  53430. *
  53431. * @param uint8array The binary file stored in an array buffer.
  53432. * @param hdrInfo The header information of the file.
  53433. * @return The pixels data in RGB right to left up to down order.
  53434. */
  53435. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  53436. // Keep for multi format supports.
  53437. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53438. };
  53439. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  53440. var num_scanlines = hdrInfo.height;
  53441. var scanline_width = hdrInfo.width;
  53442. var a, b, c, d, count;
  53443. var dataIndex = hdrInfo.dataPosition;
  53444. var index = 0, endIndex = 0, i = 0;
  53445. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  53446. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  53447. // 3 channels of 4 bytes per pixel in float.
  53448. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  53449. var resultArray = new Float32Array(resultBuffer);
  53450. // read in each successive scanline
  53451. while (num_scanlines > 0) {
  53452. a = uint8array[dataIndex++];
  53453. b = uint8array[dataIndex++];
  53454. c = uint8array[dataIndex++];
  53455. d = uint8array[dataIndex++];
  53456. if (a != 2 || b != 2 || (c & 0x80)) {
  53457. // this file is not run length encoded
  53458. throw "HDR Bad header format, not RLE";
  53459. }
  53460. if (((c << 8) | d) != scanline_width) {
  53461. throw "HDR Bad header format, wrong scan line width";
  53462. }
  53463. index = 0;
  53464. // read each of the four channels for the scanline into the buffer
  53465. for (i = 0; i < 4; i++) {
  53466. endIndex = (i + 1) * scanline_width;
  53467. while (index < endIndex) {
  53468. a = uint8array[dataIndex++];
  53469. b = uint8array[dataIndex++];
  53470. if (a > 128) {
  53471. // a run of the same value
  53472. count = a - 128;
  53473. if ((count == 0) || (count > endIndex - index)) {
  53474. throw "HDR Bad Format, bad scanline data (run)";
  53475. }
  53476. while (count-- > 0) {
  53477. scanLineArray[index++] = b;
  53478. }
  53479. }
  53480. else {
  53481. // a non-run
  53482. count = a;
  53483. if ((count == 0) || (count > endIndex - index)) {
  53484. throw "HDR Bad Format, bad scanline data (non-run)";
  53485. }
  53486. scanLineArray[index++] = b;
  53487. if (--count > 0) {
  53488. for (var j = 0; j < count; j++) {
  53489. scanLineArray[index++] = uint8array[dataIndex++];
  53490. }
  53491. }
  53492. }
  53493. }
  53494. }
  53495. // now convert data from buffer into floats
  53496. for (i = 0; i < scanline_width; i++) {
  53497. a = scanLineArray[i];
  53498. b = scanLineArray[i + scanline_width];
  53499. c = scanLineArray[i + 2 * scanline_width];
  53500. d = scanLineArray[i + 3 * scanline_width];
  53501. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  53502. }
  53503. num_scanlines--;
  53504. }
  53505. return resultArray;
  53506. };
  53507. return HDRTools;
  53508. }());
  53509. Internals.HDRTools = HDRTools;
  53510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53511. })(BABYLON || (BABYLON = {}));
  53512. //# sourceMappingURL=babylon.tools.hdr.js.map
  53513. //_______________________________________________________________
  53514. // Extracted from CubeMapGen:
  53515. // https://code.google.com/archive/p/cubemapgen/
  53516. //
  53517. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53518. //_______________________________________________________________
  53519. var BABYLON;
  53520. (function (BABYLON) {
  53521. var Internals;
  53522. (function (Internals) {
  53523. /**
  53524. * The bounding box information used during the conversion process.
  53525. */
  53526. var CMGBoundinBox = (function () {
  53527. function CMGBoundinBox() {
  53528. this.min = new BABYLON.Vector3(0, 0, 0);
  53529. this.max = new BABYLON.Vector3(0, 0, 0);
  53530. this.clear();
  53531. }
  53532. CMGBoundinBox.prototype.clear = function () {
  53533. this.min.x = CMGBoundinBox.MAX;
  53534. this.min.y = CMGBoundinBox.MAX;
  53535. this.min.z = CMGBoundinBox.MAX;
  53536. this.max.x = CMGBoundinBox.MIN;
  53537. this.max.y = CMGBoundinBox.MIN;
  53538. this.max.z = CMGBoundinBox.MIN;
  53539. };
  53540. CMGBoundinBox.prototype.augment = function (x, y, z) {
  53541. this.min.x = Math.min(this.min.x, x);
  53542. this.min.y = Math.min(this.min.y, y);
  53543. this.min.z = Math.min(this.min.z, z);
  53544. this.max.x = Math.max(this.max.x, x);
  53545. this.max.y = Math.max(this.max.y, y);
  53546. this.max.z = Math.max(this.max.z, z);
  53547. };
  53548. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  53549. this.min.x = Math.max(this.min.x, x);
  53550. this.min.y = Math.max(this.min.y, y);
  53551. this.min.z = Math.max(this.min.z, z);
  53552. };
  53553. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  53554. this.max.x = Math.min(this.max.x, x);
  53555. this.max.y = Math.min(this.max.y, y);
  53556. this.max.z = Math.min(this.max.z, z);
  53557. };
  53558. CMGBoundinBox.prototype.empty = function () {
  53559. if ((this.min.x > this.max.y) ||
  53560. (this.min.y > this.max.y) ||
  53561. (this.min.z > this.max.y)) {
  53562. return true;
  53563. }
  53564. else {
  53565. return false;
  53566. }
  53567. };
  53568. return CMGBoundinBox;
  53569. }());
  53570. CMGBoundinBox.MAX = Number.MAX_VALUE;
  53571. CMGBoundinBox.MIN = Number.MIN_VALUE;
  53572. /**
  53573. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  53574. * required by the glossinees of a material.
  53575. *
  53576. * This only supports the cosine drop power as well as Warp fixup generation method.
  53577. *
  53578. * This is using the process from CubeMapGen described here:
  53579. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53580. */
  53581. var PMREMGenerator = (function () {
  53582. /**
  53583. * Constructor of the generator.
  53584. *
  53585. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  53586. * @param inputSize The size of the cubemap faces
  53587. * @param outputSize The size of the output cubemap faces
  53588. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  53589. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  53590. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  53591. * @param specularPower The max specular level of the desired cubemap
  53592. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  53593. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  53594. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  53595. */
  53596. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  53597. this.input = input;
  53598. this.inputSize = inputSize;
  53599. this.outputSize = outputSize;
  53600. this.maxNumMipLevels = maxNumMipLevels;
  53601. this.numChannels = numChannels;
  53602. this.isFloat = isFloat;
  53603. this.specularPower = specularPower;
  53604. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  53605. this.excludeBase = excludeBase;
  53606. this.fixup = fixup;
  53607. this._outputSurface = [];
  53608. this._numMipLevels = 0;
  53609. }
  53610. /**
  53611. * Launches the filter process and return the result.
  53612. *
  53613. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  53614. */
  53615. PMREMGenerator.prototype.filterCubeMap = function () {
  53616. // Init cubemap processor
  53617. this.init();
  53618. // Filters the cubemap
  53619. this.filterCubeMapMipChain();
  53620. // Returns the filtered mips.
  53621. return this._outputSurface;
  53622. };
  53623. PMREMGenerator.prototype.init = function () {
  53624. var i;
  53625. var j;
  53626. var mipLevelSize;
  53627. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  53628. if (this.maxNumMipLevels == 0) {
  53629. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  53630. }
  53631. //first miplevel size
  53632. mipLevelSize = this.outputSize;
  53633. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  53634. for (j = 0; j < this.maxNumMipLevels; j++) {
  53635. this._outputSurface.length++;
  53636. this._outputSurface[j] = [];
  53637. //Iterate over faces for output images
  53638. for (i = 0; i < 6; i++) {
  53639. this._outputSurface[j].length++;
  53640. // Initializes a new array for the output.
  53641. if (this.isFloat) {
  53642. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53643. }
  53644. else {
  53645. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53646. }
  53647. }
  53648. //next mip level is half size
  53649. mipLevelSize >>= 1;
  53650. this._numMipLevels++;
  53651. //terminate if mip chain becomes too small
  53652. if (mipLevelSize == 0) {
  53653. this.maxNumMipLevels = j;
  53654. return;
  53655. }
  53656. }
  53657. };
  53658. //--------------------------------------------------------------------------------------
  53659. //Cube map filtering and mip chain generation.
  53660. // the cube map filtereing is specified using a number of parameters:
  53661. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  53662. // indicates the region of the hemisphere to filter over for each tap.
  53663. //
  53664. // Note that the top mip level is also a filtered version of the original input images
  53665. // as well in order to create mip chains for diffuse environment illumination.
  53666. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  53667. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  53668. //
  53669. // Then the mip angle used to genreate the next level of the mip chain from the first level
  53670. // is a_InitialMipAngle
  53671. //
  53672. // The angle for the subsequent levels of the mip chain are specified by their parents
  53673. // filtering angle and a per-level scale and bias
  53674. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  53675. //
  53676. //--------------------------------------------------------------------------------------
  53677. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  53678. // First, take count of the lighting model to modify SpecularPower
  53679. // 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;
  53680. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  53681. //Cone angle start (for generating subsequent mip levels)
  53682. var currentSpecularPower = this.specularPower;
  53683. //Build filter lookup tables based on the source miplevel size
  53684. this.precomputeFilterLookupTables(this.inputSize);
  53685. // Note that we need to filter the first level before generating mipmap
  53686. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  53687. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  53688. // TODO : Write a function to copy and scale the base mipmap in output
  53689. // I am just lazy here and just put a high specular power value, and do some if.
  53690. if (this.excludeBase && (levelIndex == 0)) {
  53691. // 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).
  53692. currentSpecularPower = 100000.0;
  53693. }
  53694. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  53695. var srcCubeImage = this.input;
  53696. var dstCubeImage = this._outputSurface[levelIndex];
  53697. var dstSize = this.outputSize >> levelIndex;
  53698. // Compute required angle.
  53699. var angle = this.getBaseFilterAngle(currentSpecularPower);
  53700. // filter cube surfaces
  53701. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  53702. // fix seams
  53703. if (this.fixup) {
  53704. this.fixupCubeEdges(dstCubeImage, dstSize);
  53705. }
  53706. // Decrease the specular power to generate the mipmap chain
  53707. // TODO : Use another method for Exclude (see first comment at start of the function
  53708. if (this.excludeBase && (levelIndex == 0)) {
  53709. currentSpecularPower = this.specularPower;
  53710. }
  53711. currentSpecularPower *= this.cosinePowerDropPerMip;
  53712. }
  53713. };
  53714. //--------------------------------------------------------------------------------------
  53715. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  53716. // It allow to optimize the texel to access base on the specular power.
  53717. //--------------------------------------------------------------------------------------
  53718. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  53719. // We want to find the alpha such that:
  53720. // cos(alpha)^cosinePower = epsilon
  53721. // That's: acos(epsilon^(1/cosinePower))
  53722. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  53723. var angle = 180.0;
  53724. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  53725. angle *= 180.0 / Math.PI; // Convert to degree
  53726. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  53727. return angle;
  53728. };
  53729. //--------------------------------------------------------------------------------------
  53730. //Builds the following lookup tables prior to filtering:
  53731. // -normalizer cube map
  53732. // -tap weight lookup table
  53733. //
  53734. //--------------------------------------------------------------------------------------
  53735. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  53736. var srcTexelAngle;
  53737. var iCubeFace;
  53738. //clear pre-existing normalizer cube map
  53739. this._normCubeMap = [];
  53740. //Normalized vectors per cubeface and per-texel solid angle
  53741. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  53742. };
  53743. //--------------------------------------------------------------------------------------
  53744. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  53745. //
  53746. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  53747. //
  53748. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  53749. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  53750. // below
  53751. //--------------------------------------------------------------------------------------
  53752. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  53753. var iCubeFace;
  53754. var u;
  53755. var v;
  53756. //iterate over cube faces
  53757. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53758. //First three channels for norm cube, and last channel for solid angle
  53759. this._normCubeMap.push(new Float32Array(size * size * 4));
  53760. //fast texture walk, build normalizer cube map
  53761. var facesData = this.input[iCubeFace];
  53762. for (v = 0; v < size; v++) {
  53763. for (u = 0; u < size; u++) {
  53764. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  53765. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  53766. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  53767. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  53768. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  53769. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  53770. }
  53771. }
  53772. }
  53773. };
  53774. //--------------------------------------------------------------------------------------
  53775. // Convert cubemap face texel coordinates and face idx to 3D vector
  53776. // note the U and V coords are integer coords and range from 0 to size-1
  53777. // this routine can be used to generate a normalizer cube map
  53778. //--------------------------------------------------------------------------------------
  53779. // SL BEGIN
  53780. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  53781. var nvcU;
  53782. var nvcV;
  53783. var tempVec;
  53784. // Change from original AMD code
  53785. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53786. // + 0.5f is for texel center addressing
  53787. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  53788. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  53789. // warp fixup
  53790. if (fixup && size > 1) {
  53791. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  53792. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  53793. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  53794. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  53795. }
  53796. // Get current vector
  53797. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  53798. // U contribution
  53799. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53800. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  53801. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  53802. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  53803. // V contribution and Sum
  53804. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53805. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  53806. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  53807. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  53808. //add face axis
  53809. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  53810. PMREMGenerator._vectorTemp.x += faceAxis[0];
  53811. PMREMGenerator._vectorTemp.y += faceAxis[1];
  53812. PMREMGenerator._vectorTemp.z += faceAxis[2];
  53813. //normalize vector
  53814. PMREMGenerator._vectorTemp.normalize();
  53815. return PMREMGenerator._vectorTemp;
  53816. };
  53817. //--------------------------------------------------------------------------------------
  53818. // Convert 3D vector to cubemap face texel coordinates and face idx
  53819. // note the U and V coords are integer coords and range from 0 to size-1
  53820. // this routine can be used to generate a normalizer cube map
  53821. //
  53822. // returns face IDX and texel coords
  53823. //--------------------------------------------------------------------------------------
  53824. // SL BEGIN
  53825. /*
  53826. Mapping Texture Coordinates to Cube Map Faces
  53827. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  53828. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  53829. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  53830. map arrangement in Pixar's RenderMan package.
  53831. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  53832. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  53833. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  53834. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  53835. the major axis direction). The target column in the table below explains how the major axis direction
  53836. maps to the 2D image of a particular cube map target.
  53837. major axis
  53838. direction target sc tc ma
  53839. ---------- --------------------------------- --- --- ---
  53840. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  53841. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  53842. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  53843. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  53844. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  53845. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  53846. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  53847. an updated (s,t) is calculated as follows
  53848. s = ( sc/|ma| + 1 ) / 2
  53849. t = ( tc/|ma| + 1 ) / 2
  53850. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  53851. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  53852. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  53853. */
  53854. // Note this method return U and V in range from 0 to size-1
  53855. // SL END
  53856. // Store the information in vector3 for convenience (faceindex, u, v)
  53857. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  53858. var maxCoord;
  53859. var faceIdx;
  53860. //absolute value 3
  53861. var absX = Math.abs(x);
  53862. var absY = Math.abs(y);
  53863. var absZ = Math.abs(z);
  53864. if (absX >= absY && absX >= absZ) {
  53865. maxCoord = absX;
  53866. if (x >= 0) {
  53867. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  53868. }
  53869. else {
  53870. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  53871. }
  53872. }
  53873. else if (absY >= absX && absY >= absZ) {
  53874. maxCoord = absY;
  53875. if (y >= 0) {
  53876. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  53877. }
  53878. else {
  53879. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  53880. }
  53881. }
  53882. else {
  53883. maxCoord = absZ;
  53884. if (z >= 0) {
  53885. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  53886. }
  53887. else {
  53888. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  53889. }
  53890. }
  53891. //divide through by max coord so face vector lies on cube face
  53892. var scale = 1 / maxCoord;
  53893. x *= scale;
  53894. y *= scale;
  53895. z *= scale;
  53896. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53897. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  53898. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53899. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  53900. // Modify original AMD code to return value from 0 to Size - 1
  53901. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  53902. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  53903. PMREMGenerator._vectorTemp.x = faceIdx;
  53904. PMREMGenerator._vectorTemp.y = u;
  53905. PMREMGenerator._vectorTemp.z = v;
  53906. return PMREMGenerator._vectorTemp;
  53907. };
  53908. //--------------------------------------------------------------------------------------
  53909. //Original code from Ignacio CastaÒo
  53910. // This formula is from Manne ÷hrstrˆm's thesis.
  53911. // Take two coordiantes in the range [-1, 1] that define a portion of a
  53912. // cube face and return the area of the projection of that portion on the
  53913. // surface of the sphere.
  53914. //--------------------------------------------------------------------------------------
  53915. PMREMGenerator.prototype.areaElement = function (x, y) {
  53916. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  53917. };
  53918. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  53919. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53920. // (+ 0.5f is for texel center addressing)
  53921. u = (2.0 * (u + 0.5) / size) - 1.0;
  53922. v = (2.0 * (v + 0.5) / size) - 1.0;
  53923. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  53924. var invResolution = 1.0 / size;
  53925. // U and V are the -1..1 texture coordinate on the current face.
  53926. // Get projected area for this texel
  53927. var x0 = u - invResolution;
  53928. var y0 = v - invResolution;
  53929. var x1 = u + invResolution;
  53930. var y1 = v + invResolution;
  53931. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  53932. return solidAngle;
  53933. };
  53934. //--------------------------------------------------------------------------------------
  53935. //The key to the speed of these filtering routines is to quickly define a per-face
  53936. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  53937. // Later these pixels are selectively processed based on their dot products to see if
  53938. // they reside within the filtering cone.
  53939. //
  53940. //This is done by computing the smallest per-texel angle to get a conservative estimate
  53941. // of the number of texels needed to be covered in width and height order to filter the
  53942. // region. the bounding box for the center taps face is defined first, and if the
  53943. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  53944. // defined next
  53945. //--------------------------------------------------------------------------------------
  53946. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  53947. // note that pixels within these regions may be rejected
  53948. // based on the anlge
  53949. var iCubeFace;
  53950. var u;
  53951. var v;
  53952. // bounding box per face to specify region to process
  53953. var filterExtents = [];
  53954. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53955. filterExtents.push(new CMGBoundinBox());
  53956. }
  53957. // min angle a src texel can cover (in degrees)
  53958. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  53959. // angle about center tap to define filter cone
  53960. // filter angle is 1/2 the cone angle
  53961. var filterAngle = filterConeAngle / 2.0;
  53962. //ensure filter angle is larger than a texel
  53963. if (filterAngle < srcTexelAngle) {
  53964. filterAngle = srcTexelAngle;
  53965. }
  53966. //ensure filter cone is always smaller than the hemisphere
  53967. if (filterAngle > 90.0) {
  53968. filterAngle = 90.0;
  53969. }
  53970. // the maximum number of texels in 1D the filter cone angle will cover
  53971. // used to determine bounding box size for filter extents
  53972. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  53973. // ensure conservative region always covers at least one texel
  53974. if (filterSize < 1) {
  53975. filterSize = 1;
  53976. }
  53977. // dotProdThresh threshold based on cone angle to determine whether or not taps
  53978. // reside within the cone angle
  53979. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  53980. // process required faces
  53981. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53982. //iterate over dst cube map face texel
  53983. for (v = 0; v < dstSize; v++) {
  53984. for (u = 0; u < dstSize; u++) {
  53985. //get center tap direction
  53986. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  53987. //clear old per-face filter extents
  53988. this.clearFilterExtents(filterExtents);
  53989. //define per-face filter extents
  53990. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  53991. //perform filtering of src faces using filter extents
  53992. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  53993. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  53994. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  53995. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  53996. }
  53997. }
  53998. }
  53999. };
  54000. //--------------------------------------------------------------------------------------
  54001. //Clear filter extents for the 6 cube map faces
  54002. //--------------------------------------------------------------------------------------
  54003. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54004. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54005. filterExtents[iCubeFaces].clear();
  54006. }
  54007. };
  54008. //--------------------------------------------------------------------------------------
  54009. //Define per-face bounding box filter extents
  54010. //
  54011. // These define conservative texel regions in each of the faces the filter can possibly
  54012. // process. When the pixels in the regions are actually processed, the dot product
  54013. // between the tap vector and the center tap vector is used to determine the weight of
  54014. // the tap and whether or not the tap is within the cone.
  54015. //
  54016. //--------------------------------------------------------------------------------------
  54017. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54018. //neighboring face and bleed over amount, and width of BBOX for
  54019. // left, right, top, and bottom edges of this face
  54020. var bleedOverAmount = [0, 0, 0, 0];
  54021. var bleedOverBBoxMin = [0, 0, 0, 0];
  54022. var bleedOverBBoxMax = [0, 0, 0, 0];
  54023. var neighborFace;
  54024. var neighborEdge;
  54025. var oppositeFaceIdx;
  54026. //get face idx, and u, v info from center tap dir
  54027. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54028. var faceIdx = result.x;
  54029. var u = result.y;
  54030. var v = result.z;
  54031. //define bbox size within face
  54032. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54033. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54034. filterExtents[faceIdx].clampMin(0, 0, 0);
  54035. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54036. //u and v extent in face corresponding to center tap
  54037. var minU = filterExtents[faceIdx].min.x;
  54038. var minV = filterExtents[faceIdx].min.y;
  54039. var maxU = filterExtents[faceIdx].max.x;
  54040. var maxV = filterExtents[faceIdx].max.y;
  54041. //bleed over amounts for face across u=0 edge (left)
  54042. bleedOverAmount[0] = (bboxSize - u);
  54043. bleedOverBBoxMin[0] = minV;
  54044. bleedOverBBoxMax[0] = maxV;
  54045. //bleed over amounts for face across u=1 edge (right)
  54046. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54047. bleedOverBBoxMin[1] = minV;
  54048. bleedOverBBoxMax[1] = maxV;
  54049. //bleed over to face across v=0 edge (up)
  54050. bleedOverAmount[2] = (bboxSize - v);
  54051. bleedOverBBoxMin[2] = minU;
  54052. bleedOverBBoxMax[2] = maxU;
  54053. //bleed over to face across v=1 edge (down)
  54054. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54055. bleedOverBBoxMin[3] = minU;
  54056. bleedOverBBoxMax[3] = maxU;
  54057. //compute bleed over regions in neighboring faces
  54058. for (var i = 0; i < 4; i++) {
  54059. if (bleedOverAmount[i] > 0) {
  54060. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54061. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54062. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54063. // be flipped: the cases are
  54064. // if a left edge mates with a left or bottom edge on the neighbor
  54065. // if a top edge mates with a top or right edge on the neighbor
  54066. // if a right edge mates with a right or top edge on the neighbor
  54067. // if a bottom edge mates with a bottom or left edge on the neighbor
  54068. //Seeing as the edges are enumerated as follows
  54069. // left =0
  54070. // right =1
  54071. // top =2
  54072. // bottom =3
  54073. //
  54074. // so if the edge enums are the same, or the sum of the enums == 3,
  54075. // the bbox needs to be flipped
  54076. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54077. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54078. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54079. }
  54080. //The way the bounding box is extended onto the neighboring face
  54081. // depends on which edge of neighboring face abuts with this one
  54082. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54083. case PMREMGenerator.CP_EDGE_LEFT:
  54084. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54085. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54086. break;
  54087. case PMREMGenerator.CP_EDGE_RIGHT:
  54088. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54089. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54090. break;
  54091. case PMREMGenerator.CP_EDGE_TOP:
  54092. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54093. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54094. break;
  54095. case PMREMGenerator.CP_EDGE_BOTTOM:
  54096. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54097. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54098. break;
  54099. }
  54100. //clamp filter extents in non-center tap faces to remain within surface
  54101. filterExtents[neighborFace].clampMin(0, 0, 0);
  54102. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54103. }
  54104. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54105. // from the center tap face, then process the opposite face entirely for now.
  54106. //Note that the cases in which this happens, what usually happens is that
  54107. // more than one edge bleeds onto the opposite face, and the bounding box
  54108. // encompasses the entire cube map face.
  54109. if (bleedOverAmount[i] > srcSize) {
  54110. //determine opposite face
  54111. switch (faceIdx) {
  54112. case PMREMGenerator.CP_FACE_X_POS:
  54113. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54114. break;
  54115. case PMREMGenerator.CP_FACE_X_NEG:
  54116. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54117. break;
  54118. case PMREMGenerator.CP_FACE_Y_POS:
  54119. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54120. break;
  54121. case PMREMGenerator.CP_FACE_Y_NEG:
  54122. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54123. break;
  54124. case PMREMGenerator.CP_FACE_Z_POS:
  54125. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54126. break;
  54127. case PMREMGenerator.CP_FACE_Z_NEG:
  54128. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54129. break;
  54130. default:
  54131. break;
  54132. }
  54133. //just encompass entire face for now
  54134. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54135. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54136. }
  54137. }
  54138. };
  54139. //--------------------------------------------------------------------------------------
  54140. //ProcessFilterExtents
  54141. // Process bounding box in each cube face
  54142. //
  54143. //--------------------------------------------------------------------------------------
  54144. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54145. //accumulators are 64-bit floats in order to have the precision needed
  54146. // over a summation of a large number of pixels
  54147. var dstAccum = [0, 0, 0, 0];
  54148. var weightAccum = 0;
  54149. var k = 0;
  54150. var nSrcChannels = this.numChannels;
  54151. // norm cube map and srcCubeMap have same face width
  54152. var faceWidth = srcSize;
  54153. //amount to add to pointer to move to next scanline in images
  54154. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54155. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54156. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54157. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54158. // iterate over cubefaces
  54159. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54160. //if bbox is non empty
  54161. if (!filterExtents[iFaceIdx].empty()) {
  54162. var uStart = filterExtents[iFaceIdx].min.x;
  54163. var vStart = filterExtents[iFaceIdx].min.y;
  54164. var uEnd = filterExtents[iFaceIdx].max.x;
  54165. var vEnd = filterExtents[iFaceIdx].max.y;
  54166. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54167. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54168. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54169. for (var v = vStart; v <= vEnd; v++) {
  54170. var normCubeRowWalk = 0;
  54171. var srcCubeRowWalk = 0;
  54172. for (var u = uStart; u <= uEnd; u++) {
  54173. //pointer to direction in cube map associated with texel
  54174. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54175. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54176. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54177. //check dot product to see if texel is within cone
  54178. var tapDotProd = texelVectX * centerTapDir.x +
  54179. texelVectY * centerTapDir.y +
  54180. texelVectZ * centerTapDir.z;
  54181. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54182. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54183. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54184. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54185. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54186. // so just adding one to specularpower do the trick.
  54187. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54188. //iterate over channels
  54189. for (k = 0; k < nSrcChannels; k++) {
  54190. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54191. srcCubeRowWalk++;
  54192. }
  54193. weightAccum += weight; //accumulate weight
  54194. }
  54195. else {
  54196. //step across source pixel
  54197. srcCubeRowWalk += nSrcChannels;
  54198. }
  54199. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54200. }
  54201. startIndexNormCubeMap += normCubePitch;
  54202. startIndexSrcCubeMap += srcCubePitch;
  54203. }
  54204. }
  54205. }
  54206. //divide through by weights if weight is non zero
  54207. if (weightAccum != 0.0) {
  54208. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54209. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54210. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54211. if (this.numChannels > 3) {
  54212. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54213. }
  54214. }
  54215. else {
  54216. // otherwise sample nearest
  54217. // get face idx and u, v texel coordinate in face
  54218. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54219. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54220. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54221. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54222. if (this.numChannels > 3) {
  54223. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54224. }
  54225. }
  54226. return PMREMGenerator._vectorTemp;
  54227. };
  54228. //--------------------------------------------------------------------------------------
  54229. // Fixup cube edges
  54230. //
  54231. // average texels on cube map faces across the edges
  54232. // WARP/BENT Method Only.
  54233. //--------------------------------------------------------------------------------------
  54234. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54235. var k;
  54236. var j;
  54237. var i;
  54238. var iFace;
  54239. var iCorner = 0;
  54240. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54241. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54242. // note that if functionality to filter across the three texels for each corner, then
  54243. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54244. var cornerPtr = [
  54245. [[], [], []],
  54246. [[], [], []],
  54247. [[], [], []],
  54248. [[], [], []],
  54249. [[], [], []],
  54250. [[], [], []],
  54251. [[], [], []],
  54252. [[], [], []]
  54253. ];
  54254. //if there is no fixup, or fixup width = 0, do nothing
  54255. if (cubeMapSize < 1) {
  54256. return;
  54257. }
  54258. //special case 1x1 cubemap, average face colors
  54259. if (cubeMapSize == 1) {
  54260. //iterate over channels
  54261. for (k = 0; k < this.numChannels; k++) {
  54262. var accum = 0.0;
  54263. //iterate over faces to accumulate face colors
  54264. for (iFace = 0; iFace < 6; iFace++) {
  54265. accum += cubeMap[iFace][k];
  54266. }
  54267. //compute average over 6 face colors
  54268. accum /= 6.0;
  54269. //iterate over faces to distribute face colors
  54270. for (iFace = 0; iFace < 6; iFace++) {
  54271. cubeMap[iFace][k] = accum;
  54272. }
  54273. }
  54274. return;
  54275. }
  54276. //iterate over faces to collect list of corner texel pointers
  54277. for (iFace = 0; iFace < 6; iFace++) {
  54278. //the 4 corner pointers for this face
  54279. faceCornerStartIndicies[0] = [iFace, 0];
  54280. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54281. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54282. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54283. //iterate over face corners to collect cube corner pointers
  54284. for (iCorner = 0; iCorner < 4; iCorner++) {
  54285. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54286. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54287. cornerNumPtrs[corner]++;
  54288. }
  54289. }
  54290. //iterate over corners to average across corner tap values
  54291. for (iCorner = 0; iCorner < 8; iCorner++) {
  54292. for (k = 0; k < this.numChannels; k++) {
  54293. var cornerTapAccum = 0.0;
  54294. //iterate over corner texels and average results
  54295. for (i = 0; i < 3; i++) {
  54296. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54297. }
  54298. //divide by 3 to compute average of corner tap values
  54299. cornerTapAccum *= (1.0 / 3.0);
  54300. //iterate over corner texels and average results
  54301. for (i = 0; i < 3; i++) {
  54302. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54303. }
  54304. }
  54305. }
  54306. //iterate over the twelve edges of the cube to average across edges
  54307. for (i = 0; i < 12; i++) {
  54308. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54309. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54310. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54311. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54312. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54313. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54314. var edgeWalk = 0;
  54315. var neighborEdgeWalk = 0;
  54316. //Determine walking pointers based on edge type
  54317. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54318. switch (edge) {
  54319. case PMREMGenerator.CP_EDGE_LEFT:
  54320. // no change to faceEdgeStartPtr
  54321. edgeWalk = this.numChannels * cubeMapSize;
  54322. break;
  54323. case PMREMGenerator.CP_EDGE_RIGHT:
  54324. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54325. edgeWalk = this.numChannels * cubeMapSize;
  54326. break;
  54327. case PMREMGenerator.CP_EDGE_TOP:
  54328. // no change to faceEdgeStartPtr
  54329. edgeWalk = this.numChannels;
  54330. break;
  54331. case PMREMGenerator.CP_EDGE_BOTTOM:
  54332. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54333. edgeWalk = this.numChannels;
  54334. break;
  54335. }
  54336. //For certain types of edge abutments, the neighbor edge walk needs to
  54337. // be flipped: the cases are
  54338. // if a left edge mates with a left or bottom edge on the neighbor
  54339. // if a top edge mates with a top or right edge on the neighbor
  54340. // if a right edge mates with a right or top edge on the neighbor
  54341. // if a bottom edge mates with a bottom or left edge on the neighbor
  54342. //Seeing as the edges are enumerated as follows
  54343. // left =0
  54344. // right =1
  54345. // top =2
  54346. // bottom =3
  54347. //
  54348. //If the edge enums are the same, or the sum of the enums == 3,
  54349. // the neighbor edge walk needs to be flipped
  54350. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  54351. switch (neighborEdge) {
  54352. case PMREMGenerator.CP_EDGE_LEFT:
  54353. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  54354. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54355. break;
  54356. case PMREMGenerator.CP_EDGE_RIGHT:
  54357. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54358. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54359. break;
  54360. case PMREMGenerator.CP_EDGE_TOP:
  54361. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54362. neighborEdgeWalk = -this.numChannels;
  54363. break;
  54364. case PMREMGenerator.CP_EDGE_BOTTOM:
  54365. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54366. neighborEdgeWalk = -this.numChannels;
  54367. break;
  54368. }
  54369. }
  54370. else {
  54371. //swapped direction neighbor edge walk
  54372. switch (neighborEdge) {
  54373. case PMREMGenerator.CP_EDGE_LEFT:
  54374. //no change to neighborEdgeStartPtr for this case since it points
  54375. // to the upper left corner already
  54376. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54377. break;
  54378. case PMREMGenerator.CP_EDGE_RIGHT:
  54379. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54380. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54381. break;
  54382. case PMREMGenerator.CP_EDGE_TOP:
  54383. //no change to neighborEdgeStartPtr for this case since it points
  54384. // to the upper left corner already
  54385. neighborEdgeWalk = this.numChannels;
  54386. break;
  54387. case PMREMGenerator.CP_EDGE_BOTTOM:
  54388. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54389. neighborEdgeWalk = this.numChannels;
  54390. break;
  54391. }
  54392. }
  54393. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  54394. //nearby neighborhood
  54395. //step ahead one texel on edge
  54396. edgeStartIndex += edgeWalk;
  54397. neighborEdgeStartIndex += neighborEdgeWalk;
  54398. // note that this loop does not process the corner texels, since they have already been
  54399. // averaged across faces across earlier
  54400. for (j = 1; j < (cubeMapSize - 1); j++) {
  54401. //for each set of taps along edge, average them
  54402. // and rewrite the results into the edges
  54403. for (k = 0; k < this.numChannels; k++) {
  54404. var edgeTap = cubeMap[face][edgeStartIndex + k];
  54405. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  54406. //compute average of tap intensity values
  54407. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  54408. //propagate average of taps to edge taps
  54409. cubeMap[face][edgeStartIndex + k] = avgTap;
  54410. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  54411. }
  54412. edgeStartIndex += edgeWalk;
  54413. neighborEdgeStartIndex += neighborEdgeWalk;
  54414. }
  54415. }
  54416. };
  54417. return PMREMGenerator;
  54418. }());
  54419. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  54420. PMREMGenerator.CP_UDIR = 0;
  54421. PMREMGenerator.CP_VDIR = 1;
  54422. PMREMGenerator.CP_FACEAXIS = 2;
  54423. //used to index cube faces
  54424. PMREMGenerator.CP_FACE_X_POS = 0;
  54425. PMREMGenerator.CP_FACE_X_NEG = 1;
  54426. PMREMGenerator.CP_FACE_Y_POS = 2;
  54427. PMREMGenerator.CP_FACE_Y_NEG = 3;
  54428. PMREMGenerator.CP_FACE_Z_POS = 4;
  54429. PMREMGenerator.CP_FACE_Z_NEG = 5;
  54430. //used to index image edges
  54431. // NOTE.. the actual number corresponding to the edge is important
  54432. // do not change these, or the code will break
  54433. //
  54434. // CP_EDGE_LEFT is u = 0
  54435. // CP_EDGE_RIGHT is u = width-1
  54436. // CP_EDGE_TOP is v = 0
  54437. // CP_EDGE_BOTTOM is v = height-1
  54438. PMREMGenerator.CP_EDGE_LEFT = 0;
  54439. PMREMGenerator.CP_EDGE_RIGHT = 1;
  54440. PMREMGenerator.CP_EDGE_TOP = 2;
  54441. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  54442. //corners of CUBE map (P or N specifys if it corresponds to the
  54443. // positive or negative direction each of X, Y, and Z
  54444. PMREMGenerator.CP_CORNER_NNN = 0;
  54445. PMREMGenerator.CP_CORNER_NNP = 1;
  54446. PMREMGenerator.CP_CORNER_NPN = 2;
  54447. PMREMGenerator.CP_CORNER_NPP = 3;
  54448. PMREMGenerator.CP_CORNER_PNN = 4;
  54449. PMREMGenerator.CP_CORNER_PNP = 5;
  54450. PMREMGenerator.CP_CORNER_PPN = 6;
  54451. PMREMGenerator.CP_CORNER_PPP = 7;
  54452. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  54453. //3x2 matrices that map cube map indexing vectors in 3d
  54454. // (after face selection and divide through by the
  54455. // _ABSOLUTE VALUE_ of the max coord)
  54456. // into NVC space
  54457. //Note this currently assumes the D3D cube face ordering and orientation
  54458. PMREMGenerator._sgFace2DMapping = [
  54459. //XPOS face
  54460. [[0, 0, -1],
  54461. [0, -1, 0],
  54462. [1, 0, 0]],
  54463. //XNEG face
  54464. [[0, 0, 1],
  54465. [0, -1, 0],
  54466. [-1, 0, 0]],
  54467. //YPOS face
  54468. [[1, 0, 0],
  54469. [0, 0, 1],
  54470. [0, 1, 0]],
  54471. //YNEG face
  54472. [[1, 0, 0],
  54473. [0, 0, -1],
  54474. [0, -1, 0]],
  54475. //ZPOS face
  54476. [[1, 0, 0],
  54477. [0, -1, 0],
  54478. [0, 0, 1]],
  54479. //ZNEG face
  54480. [[-1, 0, 0],
  54481. [0, -1, 0],
  54482. [0, 0, -1]],
  54483. ];
  54484. //------------------------------------------------------------------------------
  54485. // D3D cube map face specification
  54486. // mapping from 3D x,y,z cube map lookup coordinates
  54487. // to 2D within face u,v coordinates
  54488. //
  54489. // --------------------> U direction
  54490. // | (within-face texture space)
  54491. // | _____
  54492. // | | |
  54493. // | | +Y |
  54494. // | _____|_____|_____ _____
  54495. // | | | | | |
  54496. // | | -X | +Z | +X | -Z |
  54497. // | |_____|_____|_____|_____|
  54498. // | | |
  54499. // | | -Y |
  54500. // | |_____|
  54501. // |
  54502. // v V direction
  54503. // (within-face texture space)
  54504. //------------------------------------------------------------------------------
  54505. //Information about neighbors and how texture coorrdinates change across faces
  54506. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  54507. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  54508. //Note this currently assumes the D3D cube face ordering and orientation
  54509. PMREMGenerator._sgCubeNgh = [
  54510. //XPOS face
  54511. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54512. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54513. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54514. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  54515. //XNEG face
  54516. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54517. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  54518. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  54519. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  54520. //YPOS face
  54521. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54522. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54523. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54524. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  54525. //YNEG face
  54526. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54527. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54528. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54529. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  54530. //ZPOS face
  54531. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54532. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54533. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54534. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  54535. //ZNEG face
  54536. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54537. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54538. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  54539. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  54540. ];
  54541. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  54542. // this table is used to average over the edges.
  54543. PMREMGenerator._sgCubeEdgeList = [
  54544. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54545. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54546. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54547. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54548. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54549. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54550. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54551. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54552. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  54553. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54554. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54555. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  54556. ];
  54557. //Information about which of the 8 cube corners are correspond to the
  54558. // the 4 corners in each cube face
  54559. // the order is upper left, upper right, lower left, lower right
  54560. PMREMGenerator._sgCubeCornerList = [
  54561. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  54562. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  54563. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  54564. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  54565. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  54566. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  54567. ];
  54568. Internals.PMREMGenerator = PMREMGenerator;
  54569. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54570. })(BABYLON || (BABYLON = {}));
  54571. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  54572. var BABYLON;
  54573. (function (BABYLON) {
  54574. /**
  54575. * This represents a texture coming from an HDR input.
  54576. *
  54577. * The only supported format is currently panorama picture stored in RGBE format.
  54578. * Example of such files can be found on HDRLib: http://hdrlib.com/
  54579. */
  54580. var HDRCubeTexture = (function (_super) {
  54581. __extends(HDRCubeTexture, _super);
  54582. /**
  54583. * Instantiates an HDRTexture from the following parameters.
  54584. *
  54585. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  54586. * @param scene The scene the texture will be used in
  54587. * @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.
  54588. * @param noMipmap Forces to not generate the mipmap if true
  54589. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  54590. * @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)
  54591. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  54592. */
  54593. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  54594. if (noMipmap === void 0) { noMipmap = false; }
  54595. if (generateHarmonics === void 0) { generateHarmonics = true; }
  54596. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  54597. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  54598. if (onLoad === void 0) { onLoad = null; }
  54599. if (onError === void 0) { onError = null; }
  54600. var _this = _super.call(this, scene) || this;
  54601. _this._useInGammaSpace = false;
  54602. _this._generateHarmonics = true;
  54603. _this._isBABYLONPreprocessed = false;
  54604. _this._onLoad = null;
  54605. _this._onError = null;
  54606. /**
  54607. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  54608. */
  54609. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54610. /**
  54611. * The spherical polynomial data extracted from the texture.
  54612. */
  54613. _this.sphericalPolynomial = null;
  54614. /**
  54615. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  54616. * This is usefull at run time to apply the good shader.
  54617. */
  54618. _this.isPMREM = false;
  54619. if (!url) {
  54620. return _this;
  54621. }
  54622. _this.name = url;
  54623. _this.url = url;
  54624. _this.hasAlpha = false;
  54625. _this.isCube = true;
  54626. _this._textureMatrix = BABYLON.Matrix.Identity();
  54627. _this._onLoad = onLoad;
  54628. _this._onError = onError;
  54629. if (size) {
  54630. _this._isBABYLONPreprocessed = false;
  54631. _this._noMipmap = noMipmap;
  54632. _this._size = size;
  54633. _this._useInGammaSpace = useInGammaSpace;
  54634. _this._usePMREMGenerator = usePMREMGenerator &&
  54635. scene.getEngine().getCaps().textureLOD &&
  54636. _this.getScene().getEngine().getCaps().textureFloat &&
  54637. !_this._useInGammaSpace;
  54638. }
  54639. else {
  54640. _this._isBABYLONPreprocessed = true;
  54641. _this._noMipmap = false;
  54642. _this._useInGammaSpace = false;
  54643. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  54644. _this.getScene().getEngine().getCaps().textureFloat &&
  54645. !_this._useInGammaSpace;
  54646. }
  54647. _this.isPMREM = _this._usePMREMGenerator;
  54648. _this._texture = _this._getFromCache(url, _this._noMipmap);
  54649. if (!_this._texture) {
  54650. if (!scene.useDelayedTextureLoading) {
  54651. _this.loadTexture();
  54652. }
  54653. else {
  54654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54655. }
  54656. }
  54657. return _this;
  54658. }
  54659. /**
  54660. * Occurs when the file is a preprocessed .babylon.hdr file.
  54661. */
  54662. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  54663. var _this = this;
  54664. var mipLevels = 0;
  54665. var floatArrayView = null;
  54666. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  54667. var mips = [];
  54668. var startIndex = 30;
  54669. for (var level = 0; level < mipLevels; level++) {
  54670. mips.push([]);
  54671. // Fill each pixel of the mip level.
  54672. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  54673. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54674. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  54675. mips[level].push(faceData);
  54676. startIndex += faceSize;
  54677. }
  54678. }
  54679. return mips;
  54680. } : null;
  54681. var callback = function (buffer) {
  54682. // Create Native Array Views
  54683. var intArrayView = new Int32Array(buffer);
  54684. floatArrayView = new Float32Array(buffer);
  54685. // Fill header.
  54686. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  54687. _this._size = intArrayView[1]; // CubeMap max mip face size.
  54688. // Update Texture Information.
  54689. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  54690. // Fill polynomial information.
  54691. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  54692. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  54693. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  54694. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  54695. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  54696. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  54697. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  54698. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  54699. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  54700. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  54701. // Fill pixel data.
  54702. mipLevels = intArrayView[29]; // Number of mip levels.
  54703. var startIndex = 30;
  54704. var data = [];
  54705. var faceSize = Math.pow(_this._size, 2) * 3;
  54706. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54707. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  54708. startIndex += faceSize;
  54709. }
  54710. var results = [];
  54711. var byteArray = null;
  54712. // Push each faces.
  54713. for (var k = 0; k < 6; k++) {
  54714. var dataFace = null;
  54715. // If special cases.
  54716. if (!mipmapGenerator) {
  54717. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  54718. dataFace = data[j];
  54719. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54720. // 3 channels of 1 bytes per pixel in bytes.
  54721. var byteBuffer = new ArrayBuffer(faceSize);
  54722. byteArray = new Uint8Array(byteBuffer);
  54723. }
  54724. for (var i = 0; i < _this._size * _this._size; i++) {
  54725. // Put in gamma space if requested.
  54726. if (_this._useInGammaSpace) {
  54727. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54728. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54729. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54730. }
  54731. // Convert to int texture for fallback.
  54732. if (byteArray) {
  54733. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54734. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54735. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54736. // May use luminance instead if the result is not accurate.
  54737. var max = Math.max(Math.max(r, g), b);
  54738. if (max > 255) {
  54739. var scale = 255 / max;
  54740. r *= scale;
  54741. g *= scale;
  54742. b *= scale;
  54743. }
  54744. byteArray[(i * 3) + 0] = r;
  54745. byteArray[(i * 3) + 1] = g;
  54746. byteArray[(i * 3) + 2] = b;
  54747. }
  54748. }
  54749. }
  54750. else {
  54751. dataFace = data[k];
  54752. }
  54753. // Fill the array accordingly.
  54754. if (byteArray) {
  54755. results.push(byteArray);
  54756. }
  54757. else {
  54758. results.push(dataFace);
  54759. }
  54760. }
  54761. return results;
  54762. };
  54763. 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);
  54764. };
  54765. /**
  54766. * Occurs when the file is raw .hdr file.
  54767. */
  54768. HDRCubeTexture.prototype.loadHDRTexture = function () {
  54769. var _this = this;
  54770. var callback = function (buffer) {
  54771. // Extract the raw linear data.
  54772. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  54773. // Generate harmonics if needed.
  54774. if (_this._generateHarmonics) {
  54775. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  54776. }
  54777. var results = [];
  54778. var byteArray = null;
  54779. // Push each faces.
  54780. for (var j = 0; j < 6; j++) {
  54781. // Create uintarray fallback.
  54782. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54783. // 3 channels of 1 bytes per pixel in bytes.
  54784. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  54785. byteArray = new Uint8Array(byteBuffer);
  54786. }
  54787. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  54788. // If special cases.
  54789. if (_this._useInGammaSpace || byteArray) {
  54790. for (var i = 0; i < _this._size * _this._size; i++) {
  54791. // Put in gamma space if requested.
  54792. if (_this._useInGammaSpace) {
  54793. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54794. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54795. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54796. }
  54797. // Convert to int texture for fallback.
  54798. if (byteArray) {
  54799. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54800. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54801. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54802. // May use luminance instead if the result is not accurate.
  54803. var max = Math.max(Math.max(r, g), b);
  54804. if (max > 255) {
  54805. var scale = 255 / max;
  54806. r *= scale;
  54807. g *= scale;
  54808. b *= scale;
  54809. }
  54810. byteArray[(i * 3) + 0] = r;
  54811. byteArray[(i * 3) + 1] = g;
  54812. byteArray[(i * 3) + 2] = b;
  54813. }
  54814. }
  54815. }
  54816. if (byteArray) {
  54817. results.push(byteArray);
  54818. }
  54819. else {
  54820. results.push(dataFace);
  54821. }
  54822. }
  54823. return results;
  54824. };
  54825. var mipmapGenerator = null;
  54826. if (!this._noMipmap &&
  54827. this._usePMREMGenerator) {
  54828. mipmapGenerator = function (data) {
  54829. // Custom setup of the generator matching with the PBR shader values.
  54830. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  54831. return generator.filterCubeMap();
  54832. };
  54833. }
  54834. 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);
  54835. };
  54836. /**
  54837. * Starts the loading process of the texture.
  54838. */
  54839. HDRCubeTexture.prototype.loadTexture = function () {
  54840. if (this._isBABYLONPreprocessed) {
  54841. this.loadBabylonTexture();
  54842. }
  54843. else {
  54844. this.loadHDRTexture();
  54845. }
  54846. };
  54847. HDRCubeTexture.prototype.clone = function () {
  54848. var size = this._isBABYLONPreprocessed ? null : this._size;
  54849. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  54850. // Base texture
  54851. newTexture.level = this.level;
  54852. newTexture.wrapU = this.wrapU;
  54853. newTexture.wrapV = this.wrapV;
  54854. newTexture.coordinatesIndex = this.coordinatesIndex;
  54855. newTexture.coordinatesMode = this.coordinatesMode;
  54856. return newTexture;
  54857. };
  54858. // Methods
  54859. HDRCubeTexture.prototype.delayLoad = function () {
  54860. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54861. return;
  54862. }
  54863. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54864. this._texture = this._getFromCache(this.url, this._noMipmap);
  54865. if (!this._texture) {
  54866. this.loadTexture();
  54867. }
  54868. };
  54869. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  54870. return this._textureMatrix;
  54871. };
  54872. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54873. var texture = null;
  54874. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  54875. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  54876. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  54877. texture.name = parsedTexture.name;
  54878. texture.hasAlpha = parsedTexture.hasAlpha;
  54879. texture.level = parsedTexture.level;
  54880. texture.coordinatesMode = parsedTexture.coordinatesMode;
  54881. }
  54882. return texture;
  54883. };
  54884. HDRCubeTexture.prototype.serialize = function () {
  54885. if (!this.name) {
  54886. return null;
  54887. }
  54888. var serializationObject = {};
  54889. serializationObject.name = this.name;
  54890. serializationObject.hasAlpha = this.hasAlpha;
  54891. serializationObject.isCube = true;
  54892. serializationObject.level = this.level;
  54893. serializationObject.size = this._size;
  54894. serializationObject.coordinatesMode = this.coordinatesMode;
  54895. serializationObject.useInGammaSpace = this._useInGammaSpace;
  54896. serializationObject.generateHarmonics = this._generateHarmonics;
  54897. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  54898. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  54899. serializationObject.customType = "BABYLON.HDRCubeTexture";
  54900. serializationObject.noMipmap = this._noMipmap;
  54901. return serializationObject;
  54902. };
  54903. /**
  54904. * Saves as a file the data contained in the texture in a binary format.
  54905. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54906. * as the spherical used in the lighting.
  54907. * @param url The HDR file url.
  54908. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54909. * @param onError Method called if any error happens during download.
  54910. * @return The packed binary data.
  54911. */
  54912. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  54913. if (onError === void 0) { onError = null; }
  54914. var callback = function (buffer) {
  54915. var data = new Blob([buffer], { type: 'application/octet-stream' });
  54916. // Returns a URL you can use as a href.
  54917. var objUrl = window.URL.createObjectURL(data);
  54918. // Simulates a link to it and click to dowload.
  54919. var a = document.createElement("a");
  54920. document.body.appendChild(a);
  54921. a.style.display = "none";
  54922. a.href = objUrl;
  54923. a.download = "envmap.babylon.hdr";
  54924. a.click();
  54925. };
  54926. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  54927. };
  54928. /**
  54929. * Serializes the data contained in the texture in a binary format.
  54930. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54931. * as the spherical used in the lighting.
  54932. * @param url The HDR file url.
  54933. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54934. * @param onError Method called if any error happens during download.
  54935. * @return The packed binary data.
  54936. */
  54937. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  54938. if (onError === void 0) { onError = null; }
  54939. // Needs the url tho create the texture.
  54940. if (!url) {
  54941. return null;
  54942. }
  54943. // Check Power of two size.
  54944. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  54945. return null;
  54946. }
  54947. var getDataCallback = function (dataBuffer) {
  54948. // Extract the raw linear data.
  54949. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  54950. // Generate harmonics if needed.
  54951. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  54952. // Generate seamless faces
  54953. var mipGeneratorArray = [];
  54954. // Data are known to be in +X +Y +Z -X -Y -Z
  54955. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  54956. mipGeneratorArray.push(cubeData.right); // +X
  54957. mipGeneratorArray.push(cubeData.left); // -X
  54958. mipGeneratorArray.push(cubeData.up); // +Y
  54959. mipGeneratorArray.push(cubeData.down); // -Y
  54960. mipGeneratorArray.push(cubeData.front); // +Z
  54961. mipGeneratorArray.push(cubeData.back); // -Z
  54962. // Custom setup of the generator matching with the PBR shader values.
  54963. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  54964. var mippedData = generator.filterCubeMap();
  54965. // Compute required byte length.
  54966. var byteLength = 1 * 4; // Raw Data Version int32.
  54967. byteLength += 4; // CubeMap max mip face size int32.
  54968. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  54969. // Add data size.
  54970. byteLength += 4; // Number of mip levels int32.
  54971. for (var level = 0; level < mippedData.length; level++) {
  54972. var mipSize = size >> level;
  54973. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  54974. }
  54975. // Prepare binary structure.
  54976. var buffer = new ArrayBuffer(byteLength);
  54977. var intArrayView = new Int32Array(buffer);
  54978. var floatArrayView = new Float32Array(buffer);
  54979. // Fill header.
  54980. intArrayView[0] = 1; // Version 1.
  54981. intArrayView[1] = size; // CubeMap max mip face size.
  54982. // Fill polynomial information.
  54983. sphericalPolynomial.x.toArray(floatArrayView, 2);
  54984. sphericalPolynomial.y.toArray(floatArrayView, 5);
  54985. sphericalPolynomial.z.toArray(floatArrayView, 8);
  54986. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  54987. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  54988. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  54989. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  54990. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  54991. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  54992. // Fill pixel data.
  54993. intArrayView[29] = mippedData.length; // Number of mip levels.
  54994. var startIndex = 30;
  54995. for (var level = 0; level < mippedData.length; level++) {
  54996. // Fill each pixel of the mip level.
  54997. var faceSize = Math.pow(size >> level, 2) * 3;
  54998. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54999. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55000. startIndex += faceSize;
  55001. }
  55002. }
  55003. // Callback.
  55004. callback(buffer);
  55005. };
  55006. // Download and process.
  55007. BABYLON.Tools.LoadFile(url, function (data) {
  55008. getDataCallback(data);
  55009. }, null, null, true, onError);
  55010. };
  55011. return HDRCubeTexture;
  55012. }(BABYLON.BaseTexture));
  55013. HDRCubeTexture._facesMapping = [
  55014. "right",
  55015. "up",
  55016. "front",
  55017. "left",
  55018. "down",
  55019. "back"
  55020. ];
  55021. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55022. })(BABYLON || (BABYLON = {}));
  55023. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55024. var BABYLON;
  55025. (function (BABYLON) {
  55026. var Debug;
  55027. (function (Debug) {
  55028. /**
  55029. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55030. */
  55031. var SkeletonViewer = (function () {
  55032. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  55033. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  55034. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  55035. this.skeleton = skeleton;
  55036. this.mesh = mesh;
  55037. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  55038. this.renderingGroupId = renderingGroupId;
  55039. this.color = BABYLON.Color3.White();
  55040. this._debugLines = [];
  55041. this._isEnabled = false;
  55042. this._scene = scene;
  55043. this.update();
  55044. this._renderFunction = this.update.bind(this);
  55045. }
  55046. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  55047. get: function () {
  55048. return this._isEnabled;
  55049. },
  55050. set: function (value) {
  55051. if (this._isEnabled === value) {
  55052. return;
  55053. }
  55054. this._isEnabled = value;
  55055. if (value) {
  55056. this._scene.registerBeforeRender(this._renderFunction);
  55057. }
  55058. else {
  55059. this._scene.unregisterBeforeRender(this._renderFunction);
  55060. }
  55061. },
  55062. enumerable: true,
  55063. configurable: true
  55064. });
  55065. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  55066. if (x === void 0) { x = 0; }
  55067. if (y === void 0) { y = 0; }
  55068. if (z === void 0) { z = 0; }
  55069. var tmat = BABYLON.Tmp.Matrix[0];
  55070. var parentBone = bone.getParent();
  55071. tmat.copyFrom(bone.getLocalMatrix());
  55072. if (x !== 0 || y !== 0 || z !== 0) {
  55073. var tmat2 = BABYLON.Tmp.Matrix[1];
  55074. BABYLON.Matrix.IdentityToRef(tmat2);
  55075. tmat2.m[12] = x;
  55076. tmat2.m[13] = y;
  55077. tmat2.m[14] = z;
  55078. tmat2.multiplyToRef(tmat, tmat);
  55079. }
  55080. if (parentBone) {
  55081. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  55082. }
  55083. tmat.multiplyToRef(meshMat, tmat);
  55084. position.x = tmat.m[12];
  55085. position.y = tmat.m[13];
  55086. position.z = tmat.m[14];
  55087. };
  55088. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  55089. var len = bones.length;
  55090. for (var i = 0; i < len; i++) {
  55091. var bone = bones[i];
  55092. var points = this._debugLines[i];
  55093. if (!points) {
  55094. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55095. this._debugLines[i] = points;
  55096. }
  55097. this._getBonePosition(points[0], bone, meshMat);
  55098. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  55099. }
  55100. };
  55101. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  55102. var len = bones.length;
  55103. var boneNum = 0;
  55104. for (var i = len - 1; i >= 0; i--) {
  55105. var childBone = bones[i];
  55106. var parentBone = childBone.getParent();
  55107. if (!parentBone) {
  55108. continue;
  55109. }
  55110. var points = this._debugLines[boneNum];
  55111. if (!points) {
  55112. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55113. this._debugLines[boneNum] = points;
  55114. }
  55115. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  55116. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  55117. boneNum++;
  55118. }
  55119. };
  55120. SkeletonViewer.prototype.update = function () {
  55121. if (this.autoUpdateBonesMatrices) {
  55122. this.skeleton.computeAbsoluteTransforms();
  55123. }
  55124. if (this.skeleton.bones[0].length === undefined) {
  55125. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55126. }
  55127. else {
  55128. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55129. }
  55130. if (!this._debugMesh) {
  55131. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  55132. this._debugMesh.renderingGroupId = this.renderingGroupId;
  55133. }
  55134. else {
  55135. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  55136. }
  55137. this._debugMesh.color = this.color;
  55138. };
  55139. SkeletonViewer.prototype.dispose = function () {
  55140. if (this._debugMesh) {
  55141. this.isEnabled = false;
  55142. this._debugMesh.dispose();
  55143. this._debugMesh = null;
  55144. }
  55145. };
  55146. return SkeletonViewer;
  55147. }());
  55148. Debug.SkeletonViewer = SkeletonViewer;
  55149. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55150. })(BABYLON || (BABYLON = {}));
  55151. //# sourceMappingURL=babylon.skeletonViewer.js.map
  55152. var BABYLON;
  55153. (function (BABYLON) {
  55154. var Debug;
  55155. (function (Debug) {
  55156. var AxesViewer = (function () {
  55157. function AxesViewer(scene, scaleLines) {
  55158. if (scaleLines === void 0) { scaleLines = 1; }
  55159. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55160. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55161. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55162. this.scaleLines = 1;
  55163. this.scaleLines = scaleLines;
  55164. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  55165. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  55166. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  55167. this._xmesh.renderingGroupId = 2;
  55168. this._ymesh.renderingGroupId = 2;
  55169. this._zmesh.renderingGroupId = 2;
  55170. this._xmesh.material.checkReadyOnlyOnce = true;
  55171. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  55172. this._ymesh.material.checkReadyOnlyOnce = true;
  55173. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  55174. this._zmesh.material.checkReadyOnlyOnce = true;
  55175. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  55176. this.scene = scene;
  55177. }
  55178. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  55179. var scaleLines = this.scaleLines;
  55180. var point1 = this._xline[0];
  55181. var point2 = this._xline[1];
  55182. point1.x = position.x;
  55183. point1.y = position.y;
  55184. point1.z = position.z;
  55185. point2.x = point1.x + xaxis.x * scaleLines;
  55186. point2.y = point1.y + xaxis.y * scaleLines;
  55187. point2.z = point1.z + xaxis.z * scaleLines;
  55188. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  55189. point1 = this._yline[0];
  55190. point2 = this._yline[1];
  55191. point1.x = position.x;
  55192. point1.y = position.y;
  55193. point1.z = position.z;
  55194. point2.x = point1.x + yaxis.x * scaleLines;
  55195. point2.y = point1.y + yaxis.y * scaleLines;
  55196. point2.z = point1.z + yaxis.z * scaleLines;
  55197. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  55198. point1 = this._zline[0];
  55199. point2 = this._zline[1];
  55200. point1.x = position.x;
  55201. point1.y = position.y;
  55202. point1.z = position.z;
  55203. point2.x = point1.x + zaxis.x * scaleLines;
  55204. point2.y = point1.y + zaxis.y * scaleLines;
  55205. point2.z = point1.z + zaxis.z * scaleLines;
  55206. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  55207. };
  55208. AxesViewer.prototype.dispose = function () {
  55209. if (this._xmesh) {
  55210. this._xmesh.dispose();
  55211. this._ymesh.dispose();
  55212. this._zmesh.dispose();
  55213. this._xmesh = null;
  55214. this._ymesh = null;
  55215. this._zmesh = null;
  55216. this._xline = null;
  55217. this._yline = null;
  55218. this._zline = null;
  55219. this.scene = null;
  55220. }
  55221. };
  55222. return AxesViewer;
  55223. }());
  55224. Debug.AxesViewer = AxesViewer;
  55225. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55226. })(BABYLON || (BABYLON = {}));
  55227. //# sourceMappingURL=babylon.axesViewer.js.map
  55228. var BABYLON;
  55229. (function (BABYLON) {
  55230. var Debug;
  55231. (function (Debug) {
  55232. var BoneAxesViewer = (function (_super) {
  55233. __extends(BoneAxesViewer, _super);
  55234. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  55235. if (scaleLines === void 0) { scaleLines = 1; }
  55236. var _this = _super.call(this, scene, scaleLines) || this;
  55237. _this.pos = BABYLON.Vector3.Zero();
  55238. _this.xaxis = BABYLON.Vector3.Zero();
  55239. _this.yaxis = BABYLON.Vector3.Zero();
  55240. _this.zaxis = BABYLON.Vector3.Zero();
  55241. _this.mesh = mesh;
  55242. _this.bone = bone;
  55243. return _this;
  55244. }
  55245. BoneAxesViewer.prototype.update = function () {
  55246. var bone = this.bone;
  55247. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  55248. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  55249. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  55250. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  55251. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  55252. };
  55253. BoneAxesViewer.prototype.dispose = function () {
  55254. if (this.pos) {
  55255. this.pos = null;
  55256. this.xaxis = null;
  55257. this.yaxis = null;
  55258. this.zaxis = null;
  55259. this.mesh = null;
  55260. this.bone = null;
  55261. _super.prototype.dispose.call(this);
  55262. }
  55263. };
  55264. return BoneAxesViewer;
  55265. }(Debug.AxesViewer));
  55266. Debug.BoneAxesViewer = BoneAxesViewer;
  55267. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55268. })(BABYLON || (BABYLON = {}));
  55269. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  55270. var BABYLON;
  55271. (function (BABYLON) {
  55272. /**
  55273. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  55274. * It can help converting any input color in a desired output one. This can then be used to create effects
  55275. * from sepia, black and white to sixties or futuristic rendering...
  55276. *
  55277. * The only supported format is currently 3dl.
  55278. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  55279. */
  55280. var ColorGradingTexture = (function (_super) {
  55281. __extends(ColorGradingTexture, _super);
  55282. /**
  55283. * Instantiates a ColorGradingTexture from the following parameters.
  55284. *
  55285. * @param url The location of the color gradind data (currently only supporting 3dl)
  55286. * @param scene The scene the texture will be used in
  55287. */
  55288. function ColorGradingTexture(url, scene) {
  55289. var _this = _super.call(this, scene) || this;
  55290. if (!url) {
  55291. return _this;
  55292. }
  55293. _this._textureMatrix = BABYLON.Matrix.Identity();
  55294. _this.name = url;
  55295. _this.url = url;
  55296. _this.hasAlpha = false;
  55297. _this.isCube = false;
  55298. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55299. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55300. _this.anisotropicFilteringLevel = 1;
  55301. _this._texture = _this._getFromCache(url, true);
  55302. if (!_this._texture) {
  55303. if (!scene.useDelayedTextureLoading) {
  55304. _this.loadTexture();
  55305. }
  55306. else {
  55307. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55308. }
  55309. }
  55310. return _this;
  55311. }
  55312. /**
  55313. * Returns the texture matrix used in most of the material.
  55314. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  55315. */
  55316. ColorGradingTexture.prototype.getTextureMatrix = function () {
  55317. return this._textureMatrix;
  55318. };
  55319. /**
  55320. * Occurs when the file being loaded is a .3dl LUT file.
  55321. */
  55322. ColorGradingTexture.prototype.load3dlTexture = function () {
  55323. var _this = this;
  55324. var mipLevels = 0;
  55325. var floatArrayView = null;
  55326. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55327. this._texture = texture;
  55328. var callback = function (text) {
  55329. var data;
  55330. var tempData;
  55331. var line;
  55332. var lines = text.split('\n');
  55333. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  55334. var maxColor = 0;
  55335. for (var i = 0; i < lines.length; i++) {
  55336. line = lines[i];
  55337. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  55338. continue;
  55339. if (line.indexOf('#') === 0)
  55340. continue;
  55341. var words = line.split(" ");
  55342. if (size === 0) {
  55343. // Number of space + one
  55344. size = words.length;
  55345. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  55346. tempData = new Float32Array(size * size * size * 4);
  55347. continue;
  55348. }
  55349. if (size != 0) {
  55350. var r = Math.max(parseInt(words[0]), 0);
  55351. var g = Math.max(parseInt(words[1]), 0);
  55352. var b = Math.max(parseInt(words[2]), 0);
  55353. maxColor = Math.max(r, maxColor);
  55354. maxColor = Math.max(g, maxColor);
  55355. maxColor = Math.max(b, maxColor);
  55356. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  55357. tempData[pixelStorageIndex + 0] = r;
  55358. tempData[pixelStorageIndex + 1] = g;
  55359. tempData[pixelStorageIndex + 2] = b;
  55360. tempData[pixelStorageIndex + 3] = 0;
  55361. pixelIndexSlice++;
  55362. if (pixelIndexSlice % size == 0) {
  55363. pixelIndexH++;
  55364. pixelIndexSlice = 0;
  55365. if (pixelIndexH % size == 0) {
  55366. pixelIndexW++;
  55367. pixelIndexH = 0;
  55368. }
  55369. }
  55370. }
  55371. }
  55372. for (var i = 0; i < tempData.length; i++) {
  55373. var value = tempData[i];
  55374. data[i] = (value / maxColor * 255);
  55375. }
  55376. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  55377. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  55378. };
  55379. BABYLON.Tools.LoadFile(this.url, callback);
  55380. return this._texture;
  55381. };
  55382. /**
  55383. * Starts the loading process of the texture.
  55384. */
  55385. ColorGradingTexture.prototype.loadTexture = function () {
  55386. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  55387. this.load3dlTexture();
  55388. }
  55389. };
  55390. /**
  55391. * Clones the color gradind texture.
  55392. */
  55393. ColorGradingTexture.prototype.clone = function () {
  55394. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  55395. // Base texture
  55396. newTexture.level = this.level;
  55397. return newTexture;
  55398. };
  55399. /**
  55400. * Called during delayed load for textures.
  55401. */
  55402. ColorGradingTexture.prototype.delayLoad = function () {
  55403. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55404. return;
  55405. }
  55406. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55407. this._texture = this._getFromCache(this.url, true);
  55408. if (!this._texture) {
  55409. this.loadTexture();
  55410. }
  55411. };
  55412. /**
  55413. * Binds the color grading to the shader.
  55414. * @param colorGrading The texture to bind
  55415. * @param effect The effect to bind to
  55416. */
  55417. ColorGradingTexture.Bind = function (colorGrading, effect) {
  55418. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  55419. var x = colorGrading.level; // Texture Level
  55420. var y = colorGrading.getSize().height; // Texture Size example with 8
  55421. var z = y - 1.0; // SizeMinusOne 8 - 1
  55422. var w = 1 / y; // Space of 1 slice 1 / 8
  55423. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  55424. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  55425. 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
  55426. 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
  55427. 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
  55428. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  55429. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  55430. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  55431. };
  55432. /**
  55433. * Prepare the list of uniforms associated with the ColorGrading effects.
  55434. * @param uniformsList The list of uniforms used in the effect
  55435. * @param samplersList The list of samplers used in the effect
  55436. */
  55437. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  55438. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  55439. samplersList.push("cameraColorGrading2DSampler");
  55440. };
  55441. /**
  55442. * Parses a color grading texture serialized by Babylon.
  55443. * @param parsedTexture The texture information being parsedTexture
  55444. * @param scene The scene to load the texture in
  55445. * @param rootUrl The root url of the data assets to load
  55446. * @return A color gradind texture
  55447. */
  55448. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55449. var texture = null;
  55450. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55451. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  55452. texture.name = parsedTexture.name;
  55453. texture.level = parsedTexture.level;
  55454. }
  55455. return texture;
  55456. };
  55457. /**
  55458. * Serializes the LUT texture to json format.
  55459. */
  55460. ColorGradingTexture.prototype.serialize = function () {
  55461. if (!this.name) {
  55462. return null;
  55463. }
  55464. var serializationObject = {};
  55465. serializationObject.name = this.name;
  55466. serializationObject.level = this.level;
  55467. serializationObject.customType = "BABYLON.ColorGradingTexture";
  55468. return serializationObject;
  55469. };
  55470. return ColorGradingTexture;
  55471. }(BABYLON.BaseTexture));
  55472. /**
  55473. * Empty line regex stored for GC.
  55474. */
  55475. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  55476. BABYLON.ColorGradingTexture = ColorGradingTexture;
  55477. })(BABYLON || (BABYLON = {}));
  55478. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  55479. var BABYLON;
  55480. (function (BABYLON) {
  55481. /**
  55482. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  55483. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  55484. * 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;
  55485. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  55486. */
  55487. var ColorCurves = (function () {
  55488. function ColorCurves() {
  55489. this._dirty = true;
  55490. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  55491. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  55492. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55493. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  55494. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55495. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  55496. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  55497. this._globalHue = 30;
  55498. this._globalDensity = 0;
  55499. this._globalSaturation = 0;
  55500. this._globalExposure = 0;
  55501. this._highlightsHue = 30;
  55502. this._highlightsDensity = 0;
  55503. this._highlightsSaturation = 0;
  55504. this._highlightsExposure = 0;
  55505. this._midtonesHue = 30;
  55506. this._midtonesDensity = 0;
  55507. this._midtonesSaturation = 0;
  55508. this._midtonesExposure = 0;
  55509. this._shadowsHue = 30;
  55510. this._shadowsDensity = 0;
  55511. this._shadowsSaturation = 0;
  55512. this._shadowsExposure = 0;
  55513. }
  55514. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  55515. /**
  55516. * Gets the global Hue value.
  55517. * 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).
  55518. */
  55519. get: function () {
  55520. return this._globalHue;
  55521. },
  55522. /**
  55523. * Sets the global Hue value.
  55524. * 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).
  55525. */
  55526. set: function (value) {
  55527. this._globalHue = value;
  55528. this._dirty = true;
  55529. },
  55530. enumerable: true,
  55531. configurable: true
  55532. });
  55533. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  55534. /**
  55535. * Gets the global Density value.
  55536. * 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.
  55537. * Values less than zero provide a filter of opposite hue.
  55538. */
  55539. get: function () {
  55540. return this._globalDensity;
  55541. },
  55542. /**
  55543. * Sets the global Density value.
  55544. * 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.
  55545. * Values less than zero provide a filter of opposite hue.
  55546. */
  55547. set: function (value) {
  55548. this._globalDensity = value;
  55549. this._dirty = true;
  55550. },
  55551. enumerable: true,
  55552. configurable: true
  55553. });
  55554. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  55555. /**
  55556. * Gets the global Saturation value.
  55557. * 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.
  55558. */
  55559. get: function () {
  55560. return this._globalSaturation;
  55561. },
  55562. /**
  55563. * Sets the global Saturation value.
  55564. * 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.
  55565. */
  55566. set: function (value) {
  55567. this._globalSaturation = value;
  55568. this._dirty = true;
  55569. },
  55570. enumerable: true,
  55571. configurable: true
  55572. });
  55573. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  55574. /**
  55575. * Gets the highlights Hue value.
  55576. * 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).
  55577. */
  55578. get: function () {
  55579. return this._highlightsHue;
  55580. },
  55581. /**
  55582. * Sets the highlights Hue value.
  55583. * 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).
  55584. */
  55585. set: function (value) {
  55586. this._highlightsHue = value;
  55587. this._dirty = true;
  55588. },
  55589. enumerable: true,
  55590. configurable: true
  55591. });
  55592. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  55593. /**
  55594. * Gets the highlights Density value.
  55595. * 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.
  55596. * Values less than zero provide a filter of opposite hue.
  55597. */
  55598. get: function () {
  55599. return this._highlightsDensity;
  55600. },
  55601. /**
  55602. * Sets the highlights Density value.
  55603. * 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.
  55604. * Values less than zero provide a filter of opposite hue.
  55605. */
  55606. set: function (value) {
  55607. this._highlightsDensity = value;
  55608. this._dirty = true;
  55609. },
  55610. enumerable: true,
  55611. configurable: true
  55612. });
  55613. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  55614. /**
  55615. * Gets the highlights Saturation value.
  55616. * 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.
  55617. */
  55618. get: function () {
  55619. return this._highlightsSaturation;
  55620. },
  55621. /**
  55622. * Sets the highlights Saturation value.
  55623. * 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.
  55624. */
  55625. set: function (value) {
  55626. this._highlightsSaturation = value;
  55627. this._dirty = true;
  55628. },
  55629. enumerable: true,
  55630. configurable: true
  55631. });
  55632. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  55633. /**
  55634. * Gets the highlights Exposure value.
  55635. * 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.
  55636. */
  55637. get: function () {
  55638. return this._highlightsExposure;
  55639. },
  55640. /**
  55641. * Sets the highlights Exposure value.
  55642. * 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.
  55643. */
  55644. set: function (value) {
  55645. this._highlightsExposure = value;
  55646. this._dirty = true;
  55647. },
  55648. enumerable: true,
  55649. configurable: true
  55650. });
  55651. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  55652. /**
  55653. * Gets the midtones Hue value.
  55654. * 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).
  55655. */
  55656. get: function () {
  55657. return this._midtonesHue;
  55658. },
  55659. /**
  55660. * Sets the midtones Hue value.
  55661. * 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).
  55662. */
  55663. set: function (value) {
  55664. this._midtonesHue = value;
  55665. this._dirty = true;
  55666. },
  55667. enumerable: true,
  55668. configurable: true
  55669. });
  55670. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  55671. /**
  55672. * Gets the midtones Density value.
  55673. * 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.
  55674. * Values less than zero provide a filter of opposite hue.
  55675. */
  55676. get: function () {
  55677. return this._midtonesDensity;
  55678. },
  55679. /**
  55680. * Sets the midtones Density value.
  55681. * 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.
  55682. * Values less than zero provide a filter of opposite hue.
  55683. */
  55684. set: function (value) {
  55685. this._midtonesDensity = value;
  55686. this._dirty = true;
  55687. },
  55688. enumerable: true,
  55689. configurable: true
  55690. });
  55691. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  55692. /**
  55693. * Gets the midtones Saturation value.
  55694. * 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.
  55695. */
  55696. get: function () {
  55697. return this._midtonesSaturation;
  55698. },
  55699. /**
  55700. * Sets the midtones Saturation value.
  55701. * 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.
  55702. */
  55703. set: function (value) {
  55704. this._midtonesSaturation = value;
  55705. this._dirty = true;
  55706. },
  55707. enumerable: true,
  55708. configurable: true
  55709. });
  55710. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  55711. /**
  55712. * Gets the midtones Exposure value.
  55713. * 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.
  55714. */
  55715. get: function () {
  55716. return this._midtonesExposure;
  55717. },
  55718. /**
  55719. * Sets the midtones Exposure value.
  55720. * 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.
  55721. */
  55722. set: function (value) {
  55723. this._midtonesExposure = value;
  55724. this._dirty = true;
  55725. },
  55726. enumerable: true,
  55727. configurable: true
  55728. });
  55729. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  55730. /**
  55731. * Gets the shadows Hue value.
  55732. * 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).
  55733. */
  55734. get: function () {
  55735. return this._shadowsHue;
  55736. },
  55737. /**
  55738. * Sets the shadows Hue value.
  55739. * 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).
  55740. */
  55741. set: function (value) {
  55742. this._shadowsHue = value;
  55743. this._dirty = true;
  55744. },
  55745. enumerable: true,
  55746. configurable: true
  55747. });
  55748. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  55749. /**
  55750. * Gets the shadows Density value.
  55751. * 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.
  55752. * Values less than zero provide a filter of opposite hue.
  55753. */
  55754. get: function () {
  55755. return this._shadowsDensity;
  55756. },
  55757. /**
  55758. * Sets the shadows Density value.
  55759. * 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.
  55760. * Values less than zero provide a filter of opposite hue.
  55761. */
  55762. set: function (value) {
  55763. this._shadowsDensity = value;
  55764. this._dirty = true;
  55765. },
  55766. enumerable: true,
  55767. configurable: true
  55768. });
  55769. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  55770. /**
  55771. * Gets the shadows Saturation value.
  55772. * 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.
  55773. */
  55774. get: function () {
  55775. return this._shadowsSaturation;
  55776. },
  55777. /**
  55778. * Sets the shadows Saturation value.
  55779. * 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.
  55780. */
  55781. set: function (value) {
  55782. this._shadowsSaturation = value;
  55783. this._dirty = true;
  55784. },
  55785. enumerable: true,
  55786. configurable: true
  55787. });
  55788. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  55789. /**
  55790. * Gets the shadows Exposure value.
  55791. * 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.
  55792. */
  55793. get: function () {
  55794. return this._shadowsExposure;
  55795. },
  55796. /**
  55797. * Sets the shadows Exposure value.
  55798. * 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.
  55799. */
  55800. set: function (value) {
  55801. this._shadowsExposure = value;
  55802. this._dirty = true;
  55803. },
  55804. enumerable: true,
  55805. configurable: true
  55806. });
  55807. /**
  55808. * Binds the color curves to the shader.
  55809. * @param colorCurves The color curve to bind
  55810. * @param effect The effect to bind to
  55811. */
  55812. ColorCurves.Bind = function (colorCurves, effect) {
  55813. if (colorCurves._dirty) {
  55814. colorCurves._dirty = false;
  55815. // Fill in global info.
  55816. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  55817. // Compute highlights info.
  55818. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  55819. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  55820. // Compute midtones info.
  55821. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  55822. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  55823. // Compute shadows info.
  55824. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  55825. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  55826. // Compute deltas (neutral is midtones).
  55827. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  55828. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  55829. }
  55830. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  55831. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  55832. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  55833. };
  55834. /**
  55835. * Prepare the list of uniforms associated with the ColorCurves effects.
  55836. * @param uniformsList The list of uniforms used in the effect
  55837. */
  55838. ColorCurves.PrepareUniforms = function (uniformsList) {
  55839. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  55840. };
  55841. /**
  55842. * Returns color grading data based on a hue, density, saturation and exposure value.
  55843. * @param filterHue The hue of the color filter.
  55844. * @param filterDensity The density of the color filter.
  55845. * @param saturation The saturation.
  55846. * @param exposure The exposure.
  55847. * @param result The result data container.
  55848. */
  55849. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  55850. if (hue == null) {
  55851. return;
  55852. }
  55853. hue = ColorCurves.clamp(hue, 0, 360);
  55854. density = ColorCurves.clamp(density, -100, 100);
  55855. saturation = ColorCurves.clamp(saturation, -100, 100);
  55856. exposure = ColorCurves.clamp(exposure, -100, 100);
  55857. // Remap the slider/config filter density with non-linear mapping and also scale by half
  55858. // so that the maximum filter density is only 50% control. This provides fine control
  55859. // for small values and reasonable range.
  55860. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  55861. density *= 0.5;
  55862. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  55863. if (density < 0) {
  55864. density *= -1;
  55865. hue = (hue + 180) % 360;
  55866. }
  55867. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  55868. result.scaleToRef(2, result);
  55869. result.a = 1 + 0.01 * saturation;
  55870. };
  55871. /**
  55872. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  55873. * @param value The input slider value in range [-100,100].
  55874. * @returns Adjusted value.
  55875. */
  55876. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  55877. value /= 100;
  55878. var x = Math.abs(value);
  55879. x = Math.pow(x, 2);
  55880. if (value < 0) {
  55881. x *= -1;
  55882. }
  55883. x *= 100;
  55884. return x;
  55885. };
  55886. /**
  55887. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  55888. * @param hue The hue (H) input.
  55889. * @param saturation The saturation (S) input.
  55890. * @param brightness The brightness (B) input.
  55891. * @result An RGBA color represented as Vector4.
  55892. */
  55893. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  55894. var h = ColorCurves.clamp(hue, 0, 360);
  55895. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  55896. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  55897. if (s === 0) {
  55898. result.r = v;
  55899. result.g = v;
  55900. result.b = v;
  55901. }
  55902. else {
  55903. // sector 0 to 5
  55904. h /= 60;
  55905. var i = Math.floor(h);
  55906. // fractional part of h
  55907. var f = h - i;
  55908. var p = v * (1 - s);
  55909. var q = v * (1 - s * f);
  55910. var t = v * (1 - s * (1 - f));
  55911. switch (i) {
  55912. case 0:
  55913. result.r = v;
  55914. result.g = t;
  55915. result.b = p;
  55916. break;
  55917. case 1:
  55918. result.r = q;
  55919. result.g = v;
  55920. result.b = p;
  55921. break;
  55922. case 2:
  55923. result.r = p;
  55924. result.g = v;
  55925. result.b = t;
  55926. break;
  55927. case 3:
  55928. result.r = p;
  55929. result.g = q;
  55930. result.b = v;
  55931. break;
  55932. case 4:
  55933. result.r = t;
  55934. result.g = p;
  55935. result.b = v;
  55936. break;
  55937. default:
  55938. result.r = v;
  55939. result.g = p;
  55940. result.b = q;
  55941. break;
  55942. }
  55943. }
  55944. result.a = 1;
  55945. };
  55946. /**
  55947. * Returns a value clamped between min and max
  55948. * @param value The value to clamp
  55949. * @param min The minimum of value
  55950. * @param max The maximum of value
  55951. * @returns The clamped value.
  55952. */
  55953. ColorCurves.clamp = function (value, min, max) {
  55954. return Math.min(Math.max(value, min), max);
  55955. };
  55956. /**
  55957. * Clones the current color curve instance.
  55958. * @return The cloned curves
  55959. */
  55960. ColorCurves.prototype.clone = function () {
  55961. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  55962. };
  55963. /**
  55964. * Serializes the current color curve instance to a json representation.
  55965. * @return a JSON representation
  55966. */
  55967. ColorCurves.prototype.serialize = function () {
  55968. return BABYLON.SerializationHelper.Serialize(this);
  55969. };
  55970. /**
  55971. * Parses the color curve from a json representation.
  55972. * @param source the JSON source to parse
  55973. * @return The parsed curves
  55974. */
  55975. ColorCurves.Parse = function (source) {
  55976. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  55977. };
  55978. return ColorCurves;
  55979. }());
  55980. __decorate([
  55981. BABYLON.serialize()
  55982. ], ColorCurves.prototype, "_globalHue", void 0);
  55983. __decorate([
  55984. BABYLON.serialize()
  55985. ], ColorCurves.prototype, "_globalDensity", void 0);
  55986. __decorate([
  55987. BABYLON.serialize()
  55988. ], ColorCurves.prototype, "_globalSaturation", void 0);
  55989. __decorate([
  55990. BABYLON.serialize()
  55991. ], ColorCurves.prototype, "_globalExposure", void 0);
  55992. __decorate([
  55993. BABYLON.serialize()
  55994. ], ColorCurves.prototype, "_highlightsHue", void 0);
  55995. __decorate([
  55996. BABYLON.serialize()
  55997. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  55998. __decorate([
  55999. BABYLON.serialize()
  56000. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56001. __decorate([
  56002. BABYLON.serialize()
  56003. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56004. __decorate([
  56005. BABYLON.serialize()
  56006. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56007. __decorate([
  56008. BABYLON.serialize()
  56009. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56010. __decorate([
  56011. BABYLON.serialize()
  56012. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56013. __decorate([
  56014. BABYLON.serialize()
  56015. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56016. BABYLON.ColorCurves = ColorCurves;
  56017. })(BABYLON || (BABYLON = {}));
  56018. //# sourceMappingURL=babylon.colorCurves.js.map
  56019. var BABYLON;
  56020. (function (BABYLON) {
  56021. var PBRMaterialDefines = (function (_super) {
  56022. __extends(PBRMaterialDefines, _super);
  56023. function PBRMaterialDefines() {
  56024. var _this = _super.call(this) || this;
  56025. _this.ALBEDO = false;
  56026. _this.AMBIENT = false;
  56027. _this.OPACITY = false;
  56028. _this.OPACITYRGB = false;
  56029. _this.REFLECTION = false;
  56030. _this.EMISSIVE = false;
  56031. _this.REFLECTIVITY = false;
  56032. _this.BUMP = false;
  56033. _this.PARALLAX = false;
  56034. _this.PARALLAXOCCLUSION = false;
  56035. _this.SPECULAROVERALPHA = false;
  56036. _this.CLIPPLANE = false;
  56037. _this.ALPHATEST = false;
  56038. _this.ALPHAFROMALBEDO = false;
  56039. _this.POINTSIZE = false;
  56040. _this.FOG = false;
  56041. _this.SPECULARTERM = false;
  56042. _this.OPACITYFRESNEL = false;
  56043. _this.EMISSIVEFRESNEL = false;
  56044. _this.FRESNEL = false;
  56045. _this.NORMAL = false;
  56046. _this.UV1 = false;
  56047. _this.UV2 = false;
  56048. _this.VERTEXCOLOR = false;
  56049. _this.VERTEXALPHA = false;
  56050. _this.NUM_BONE_INFLUENCERS = 0;
  56051. _this.BonesPerMesh = 0;
  56052. _this.INSTANCES = false;
  56053. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  56054. _this.MICROSURFACEAUTOMATIC = false;
  56055. _this.EMISSIVEASILLUMINATION = false;
  56056. _this.LINKEMISSIVEWITHALBEDO = false;
  56057. _this.LIGHTMAP = false;
  56058. _this.USELIGHTMAPASSHADOWMAP = false;
  56059. _this.REFLECTIONMAP_3D = false;
  56060. _this.REFLECTIONMAP_SPHERICAL = false;
  56061. _this.REFLECTIONMAP_PLANAR = false;
  56062. _this.REFLECTIONMAP_CUBIC = false;
  56063. _this.REFLECTIONMAP_PROJECTION = false;
  56064. _this.REFLECTIONMAP_SKYBOX = false;
  56065. _this.REFLECTIONMAP_EXPLICIT = false;
  56066. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  56067. _this.INVERTCUBICMAP = false;
  56068. _this.LOGARITHMICDEPTH = false;
  56069. _this.CAMERATONEMAP = false;
  56070. _this.CAMERACONTRAST = false;
  56071. _this.CAMERACOLORGRADING = false;
  56072. _this.CAMERACOLORCURVES = false;
  56073. _this.OVERLOADEDVALUES = false;
  56074. _this.OVERLOADEDSHADOWVALUES = false;
  56075. _this.USESPHERICALFROMREFLECTIONMAP = false;
  56076. _this.REFRACTION = false;
  56077. _this.REFRACTIONMAP_3D = false;
  56078. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  56079. _this.REFRACTIONMAPINLINEARSPACE = false;
  56080. _this.LODBASEDMICROSFURACE = false;
  56081. _this.USEPHYSICALLIGHTFALLOFF = false;
  56082. _this.RADIANCEOVERALPHA = false;
  56083. _this.USEPMREMREFLECTION = false;
  56084. _this.USEPMREMREFRACTION = false;
  56085. _this.OPENGLNORMALMAP = false;
  56086. _this.INVERTNORMALMAPX = false;
  56087. _this.INVERTNORMALMAPY = false;
  56088. _this.SHADOWFULLFLOAT = false;
  56089. _this.METALLICWORKFLOW = false;
  56090. _this.METALLICROUGHNESSMAP = false;
  56091. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  56092. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  56093. _this.rebuild();
  56094. return _this;
  56095. }
  56096. return PBRMaterialDefines;
  56097. }(BABYLON.MaterialDefines));
  56098. /**
  56099. * The Physically based material of BJS.
  56100. *
  56101. * This offers the main features of a standard PBR material.
  56102. * For more information, please refer to the documentation :
  56103. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  56104. */
  56105. var PBRMaterial = (function (_super) {
  56106. __extends(PBRMaterial, _super);
  56107. /**
  56108. * Instantiates a new PBRMaterial instance.
  56109. *
  56110. * @param name The material name
  56111. * @param scene The scene the material will be use in.
  56112. */
  56113. function PBRMaterial(name, scene) {
  56114. var _this = _super.call(this, name, scene) || this;
  56115. /**
  56116. * Intensity of the direct lights e.g. the four lights available in your scene.
  56117. * This impacts both the direct diffuse and specular highlights.
  56118. */
  56119. _this.directIntensity = 1.0;
  56120. /**
  56121. * Intensity of the emissive part of the material.
  56122. * This helps controlling the emissive effect without modifying the emissive color.
  56123. */
  56124. _this.emissiveIntensity = 1.0;
  56125. /**
  56126. * Intensity of the environment e.g. how much the environment will light the object
  56127. * either through harmonics for rough material or through the refelction for shiny ones.
  56128. */
  56129. _this.environmentIntensity = 1.0;
  56130. /**
  56131. * This is a special control allowing the reduction of the specular highlights coming from the
  56132. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  56133. */
  56134. _this.specularIntensity = 1.0;
  56135. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  56136. /**
  56137. * Debug Control allowing disabling the bump map on this material.
  56138. */
  56139. _this.disableBumpMap = false;
  56140. /**
  56141. * Debug Control helping enforcing or dropping the darkness of shadows.
  56142. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  56143. */
  56144. _this.overloadedShadowIntensity = 1.0;
  56145. /**
  56146. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  56147. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  56148. */
  56149. _this.overloadedShadeIntensity = 1.0;
  56150. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  56151. /**
  56152. * The camera exposure used on this material.
  56153. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  56154. * This corresponds to a photographic exposure.
  56155. */
  56156. _this.cameraExposure = 1.0;
  56157. /**
  56158. * The camera contrast used on this material.
  56159. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  56160. */
  56161. _this.cameraContrast = 1.0;
  56162. /**
  56163. * Color Grading 2D Lookup Texture.
  56164. * This allows special effects like sepia, black and white to sixties rendering style.
  56165. */
  56166. _this.cameraColorGradingTexture = null;
  56167. /**
  56168. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56169. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56170. * 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;
  56171. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56172. */
  56173. _this.cameraColorCurves = null;
  56174. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  56175. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  56176. /**
  56177. * Debug Control allowing to overload the ambient color.
  56178. * This as to be use with the overloadedAmbientIntensity parameter.
  56179. */
  56180. _this.overloadedAmbient = BABYLON.Color3.White();
  56181. /**
  56182. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  56183. */
  56184. _this.overloadedAmbientIntensity = 0.0;
  56185. /**
  56186. * Debug Control allowing to overload the albedo color.
  56187. * This as to be use with the overloadedAlbedoIntensity parameter.
  56188. */
  56189. _this.overloadedAlbedo = BABYLON.Color3.White();
  56190. /**
  56191. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  56192. */
  56193. _this.overloadedAlbedoIntensity = 0.0;
  56194. /**
  56195. * Debug Control allowing to overload the reflectivity color.
  56196. * This as to be use with the overloadedReflectivityIntensity parameter.
  56197. */
  56198. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  56199. /**
  56200. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  56201. */
  56202. _this.overloadedReflectivityIntensity = 0.0;
  56203. /**
  56204. * Debug Control allowing to overload the emissive color.
  56205. * This as to be use with the overloadedEmissiveIntensity parameter.
  56206. */
  56207. _this.overloadedEmissive = BABYLON.Color3.White();
  56208. /**
  56209. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  56210. */
  56211. _this.overloadedEmissiveIntensity = 0.0;
  56212. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  56213. /**
  56214. * Debug Control allowing to overload the reflection color.
  56215. * This as to be use with the overloadedReflectionIntensity parameter.
  56216. */
  56217. _this.overloadedReflection = BABYLON.Color3.White();
  56218. /**
  56219. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  56220. */
  56221. _this.overloadedReflectionIntensity = 0.0;
  56222. /**
  56223. * Debug Control allowing to overload the microsurface.
  56224. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  56225. */
  56226. _this.overloadedMicroSurface = 0.0;
  56227. /**
  56228. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  56229. */
  56230. _this.overloadedMicroSurfaceIntensity = 0.0;
  56231. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  56232. /**
  56233. * AKA Occlusion Texture Intensity in other nomenclature.
  56234. */
  56235. _this.ambientTextureStrength = 1.0;
  56236. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  56237. /**
  56238. * AKA Diffuse Color in other nomenclature.
  56239. */
  56240. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  56241. /**
  56242. * AKA Specular Color in other nomenclature.
  56243. */
  56244. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  56245. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  56246. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  56247. /**
  56248. * AKA Glossiness in other nomenclature.
  56249. */
  56250. _this.microSurface = 0.9;
  56251. /**
  56252. * source material index of refraction (IOR)' / 'destination material IOR.
  56253. */
  56254. _this.indexOfRefraction = 0.66;
  56255. /**
  56256. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  56257. */
  56258. _this.invertRefractionY = false;
  56259. /**
  56260. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  56261. * Materials half opaque for instance using refraction could benefit from this control.
  56262. */
  56263. _this.linkRefractionWithTransparency = false;
  56264. /**
  56265. * The emissive and albedo are linked to never be more than one (Energy conservation).
  56266. */
  56267. _this.linkEmissiveWithAlbedo = false;
  56268. _this.useLightmapAsShadowmap = false;
  56269. /**
  56270. * In this mode, the emissive informtaion will always be added to the lighting once.
  56271. * A light for instance can be thought as emissive.
  56272. */
  56273. _this.useEmissiveAsIllumination = false;
  56274. /**
  56275. * Secifies that the alpha is coming form the albedo channel alpha channel.
  56276. */
  56277. _this.useAlphaFromAlbedoTexture = false;
  56278. /**
  56279. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  56280. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  56281. */
  56282. _this.useSpecularOverAlpha = true;
  56283. /**
  56284. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  56285. */
  56286. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  56287. /**
  56288. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  56289. */
  56290. _this.useRoughnessFromMetallicTextureAlpha = true;
  56291. /**
  56292. * Specifies if the metallic texture contains the roughness information in its green channel.
  56293. */
  56294. _this.useRoughnessFromMetallicTextureGreen = false;
  56295. /**
  56296. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  56297. * The material will try to infer what glossiness each pixel should be.
  56298. */
  56299. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  56300. /**
  56301. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  56302. * the creation of the material.
  56303. */
  56304. _this.useScalarInLinearSpace = false;
  56305. /**
  56306. * BJS is using an harcoded light falloff based on a manually sets up range.
  56307. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  56308. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  56309. */
  56310. _this.usePhysicalLightFalloff = true;
  56311. /**
  56312. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  56313. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  56314. */
  56315. _this.useRadianceOverAlpha = true;
  56316. /**
  56317. * Allows using the bump map in parallax mode.
  56318. */
  56319. _this.useParallax = false;
  56320. /**
  56321. * Allows using the bump map in parallax occlusion mode.
  56322. */
  56323. _this.useParallaxOcclusion = false;
  56324. /**
  56325. * Controls the scale bias of the parallax mode.
  56326. */
  56327. _this.parallaxScaleBias = 0.05;
  56328. /**
  56329. * If sets to true, disables all the lights affecting the material.
  56330. */
  56331. _this.disableLighting = false;
  56332. /**
  56333. * Number of Simultaneous lights allowed on the material.
  56334. */
  56335. _this.maxSimultaneousLights = 4;
  56336. /**
  56337. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  56338. */
  56339. _this.invertNormalMapX = false;
  56340. /**
  56341. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  56342. */
  56343. _this.invertNormalMapY = false;
  56344. _this._renderTargets = new BABYLON.SmartArray(16);
  56345. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  56346. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  56347. _this._tempColor = new BABYLON.Color3();
  56348. _this._defines = new PBRMaterialDefines();
  56349. _this._cachedDefines = new PBRMaterialDefines();
  56350. _this._myScene = null;
  56351. _this._myShadowGenerator = null;
  56352. _this._cachedDefines.BonesPerMesh = -1;
  56353. _this.getRenderTargetTextures = function () {
  56354. _this._renderTargets.reset();
  56355. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  56356. _this._renderTargets.push(_this.reflectionTexture);
  56357. }
  56358. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  56359. _this._renderTargets.push(_this.refractionTexture);
  56360. }
  56361. return _this._renderTargets;
  56362. };
  56363. return _this;
  56364. }
  56365. PBRMaterial.prototype.getClassName = function () {
  56366. return "PBRMaterial";
  56367. };
  56368. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  56369. get: function () {
  56370. return this._useLogarithmicDepth;
  56371. },
  56372. set: function (value) {
  56373. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  56374. },
  56375. enumerable: true,
  56376. configurable: true
  56377. });
  56378. PBRMaterial.prototype.needAlphaBlending = function () {
  56379. if (this.linkRefractionWithTransparency) {
  56380. return false;
  56381. }
  56382. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  56383. };
  56384. PBRMaterial.prototype.needAlphaTesting = function () {
  56385. if (this.linkRefractionWithTransparency) {
  56386. return false;
  56387. }
  56388. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  56389. };
  56390. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  56391. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  56392. };
  56393. PBRMaterial.prototype.getAlphaTestTexture = function () {
  56394. return this.albedoTexture;
  56395. };
  56396. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56397. if (!mesh) {
  56398. return true;
  56399. }
  56400. if (this._defines.INSTANCES !== useInstances) {
  56401. return false;
  56402. }
  56403. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  56404. return true;
  56405. }
  56406. return false;
  56407. };
  56408. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  56409. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  56410. };
  56411. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  56412. if (!useScalarInLinear) {
  56413. color.toLinearSpaceToRef(ref);
  56414. }
  56415. else {
  56416. ref.r = color.r;
  56417. ref.g = color.g;
  56418. ref.b = color.b;
  56419. }
  56420. };
  56421. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  56422. var lightIndex = 0;
  56423. var depthValuesAlreadySet = false;
  56424. for (var index = 0; index < scene.lights.length; index++) {
  56425. var light = scene.lights[index];
  56426. if (!light.isEnabled()) {
  56427. continue;
  56428. }
  56429. if (!light.canAffectMesh(mesh)) {
  56430. continue;
  56431. }
  56432. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  56433. // GAMMA CORRECTION.
  56434. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  56435. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  56436. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  56437. if (defines["SPECULARTERM"]) {
  56438. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  56439. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  56440. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  56441. }
  56442. // Shadows
  56443. if (scene.shadowsEnabled) {
  56444. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  56445. }
  56446. lightIndex++;
  56447. if (lightIndex === maxSimultaneousLights)
  56448. break;
  56449. }
  56450. };
  56451. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  56452. if (this.isFrozen) {
  56453. if (this._wasPreviouslyReady) {
  56454. return true;
  56455. }
  56456. }
  56457. var scene = this.getScene();
  56458. var engine = scene.getEngine();
  56459. var needNormals = false;
  56460. var needUVs = false;
  56461. this._defines.reset();
  56462. if (scene.lightsEnabled && !this.disableLighting) {
  56463. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  56464. }
  56465. if (!this.checkReadyOnEveryCall) {
  56466. if (this._renderId === scene.getRenderId()) {
  56467. if (this._checkCache(scene, mesh, useInstances)) {
  56468. return true;
  56469. }
  56470. }
  56471. }
  56472. if (scene.texturesEnabled) {
  56473. if (scene.getEngine().getCaps().textureLOD) {
  56474. this._defines.LODBASEDMICROSFURACE = true;
  56475. }
  56476. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56477. if (!this.albedoTexture.isReady()) {
  56478. return false;
  56479. }
  56480. else {
  56481. needUVs = true;
  56482. this._defines.ALBEDO = true;
  56483. }
  56484. }
  56485. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  56486. if (!this.ambientTexture.isReady()) {
  56487. return false;
  56488. }
  56489. else {
  56490. needUVs = true;
  56491. this._defines.AMBIENT = true;
  56492. }
  56493. }
  56494. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  56495. if (!this.opacityTexture.isReady()) {
  56496. return false;
  56497. }
  56498. else {
  56499. needUVs = true;
  56500. this._defines.OPACITY = true;
  56501. if (this.opacityTexture.getAlphaFromRGB) {
  56502. this._defines.OPACITYRGB = true;
  56503. }
  56504. }
  56505. }
  56506. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  56507. if (!this.reflectionTexture.isReady()) {
  56508. return false;
  56509. }
  56510. else {
  56511. needNormals = true;
  56512. this._defines.REFLECTION = true;
  56513. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  56514. this._defines.INVERTCUBICMAP = true;
  56515. }
  56516. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  56517. switch (this.reflectionTexture.coordinatesMode) {
  56518. case BABYLON.Texture.CUBIC_MODE:
  56519. case BABYLON.Texture.INVCUBIC_MODE:
  56520. this._defines.REFLECTIONMAP_CUBIC = true;
  56521. break;
  56522. case BABYLON.Texture.EXPLICIT_MODE:
  56523. this._defines.REFLECTIONMAP_EXPLICIT = true;
  56524. break;
  56525. case BABYLON.Texture.PLANAR_MODE:
  56526. this._defines.REFLECTIONMAP_PLANAR = true;
  56527. break;
  56528. case BABYLON.Texture.PROJECTION_MODE:
  56529. this._defines.REFLECTIONMAP_PROJECTION = true;
  56530. break;
  56531. case BABYLON.Texture.SKYBOX_MODE:
  56532. this._defines.REFLECTIONMAP_SKYBOX = true;
  56533. break;
  56534. case BABYLON.Texture.SPHERICAL_MODE:
  56535. this._defines.REFLECTIONMAP_SPHERICAL = true;
  56536. break;
  56537. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  56538. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  56539. break;
  56540. }
  56541. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  56542. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  56543. needNormals = true;
  56544. if (this.reflectionTexture.isPMREM) {
  56545. this._defines.USEPMREMREFLECTION = true;
  56546. }
  56547. }
  56548. }
  56549. }
  56550. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  56551. if (!this.lightmapTexture.isReady()) {
  56552. return false;
  56553. }
  56554. else {
  56555. needUVs = true;
  56556. this._defines.LIGHTMAP = true;
  56557. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  56558. }
  56559. }
  56560. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  56561. if (!this.emissiveTexture.isReady()) {
  56562. return false;
  56563. }
  56564. else {
  56565. needUVs = true;
  56566. this._defines.EMISSIVE = true;
  56567. }
  56568. }
  56569. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  56570. if (this.metallicTexture) {
  56571. if (!this.metallicTexture.isReady()) {
  56572. return false;
  56573. }
  56574. else {
  56575. needUVs = true;
  56576. this._defines.METALLICWORKFLOW = true;
  56577. this._defines.METALLICROUGHNESSMAP = true;
  56578. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  56579. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  56580. }
  56581. }
  56582. else if (this.reflectivityTexture) {
  56583. if (!this.reflectivityTexture.isReady()) {
  56584. return false;
  56585. }
  56586. else {
  56587. needUVs = true;
  56588. this._defines.REFLECTIVITY = true;
  56589. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  56590. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  56591. }
  56592. }
  56593. }
  56594. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  56595. if (!this.bumpTexture.isReady()) {
  56596. return false;
  56597. }
  56598. else {
  56599. needUVs = true;
  56600. this._defines.BUMP = true;
  56601. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56602. this._defines.PARALLAX = true;
  56603. if (this.useParallaxOcclusion) {
  56604. this._defines.PARALLAXOCCLUSION = true;
  56605. }
  56606. }
  56607. if (this.invertNormalMapX) {
  56608. this._defines.INVERTNORMALMAPX = true;
  56609. }
  56610. if (this.invertNormalMapY) {
  56611. this._defines.INVERTNORMALMAPY = true;
  56612. }
  56613. if (scene._mirroredCameraPosition) {
  56614. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  56615. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  56616. }
  56617. }
  56618. }
  56619. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  56620. if (!this.refractionTexture.isReady()) {
  56621. return false;
  56622. }
  56623. else {
  56624. needUVs = true;
  56625. this._defines.REFRACTION = true;
  56626. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  56627. if (this.linkRefractionWithTransparency) {
  56628. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  56629. }
  56630. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  56631. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  56632. if (this.refractionTexture.isPMREM) {
  56633. this._defines.USEPMREMREFRACTION = true;
  56634. }
  56635. }
  56636. }
  56637. }
  56638. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  56639. if (!this.cameraColorGradingTexture.isReady()) {
  56640. return false;
  56641. }
  56642. else {
  56643. this._defines.CAMERACOLORGRADING = true;
  56644. }
  56645. }
  56646. }
  56647. // Effect
  56648. if (scene.clipPlane) {
  56649. this._defines.CLIPPLANE = true;
  56650. }
  56651. if (engine.getAlphaTesting()) {
  56652. this._defines.ALPHATEST = true;
  56653. }
  56654. if (this._shouldUseAlphaFromAlbedoTexture()) {
  56655. this._defines.ALPHAFROMALBEDO = true;
  56656. }
  56657. if (this.useEmissiveAsIllumination) {
  56658. this._defines.EMISSIVEASILLUMINATION = true;
  56659. }
  56660. if (this.linkEmissiveWithAlbedo) {
  56661. this._defines.LINKEMISSIVEWITHALBEDO = true;
  56662. }
  56663. if (this.useLogarithmicDepth) {
  56664. this._defines.LOGARITHMICDEPTH = true;
  56665. }
  56666. if (this.cameraContrast != 1) {
  56667. this._defines.CAMERACONTRAST = true;
  56668. }
  56669. if (this.cameraExposure != 1) {
  56670. this._defines.CAMERATONEMAP = true;
  56671. }
  56672. if (this.cameraColorCurves) {
  56673. this._defines.CAMERACOLORCURVES = true;
  56674. }
  56675. if (this.overloadedShadeIntensity != 1 ||
  56676. this.overloadedShadowIntensity != 1) {
  56677. this._defines.OVERLOADEDSHADOWVALUES = true;
  56678. }
  56679. if (this.overloadedMicroSurfaceIntensity > 0 ||
  56680. this.overloadedEmissiveIntensity > 0 ||
  56681. this.overloadedReflectivityIntensity > 0 ||
  56682. this.overloadedAlbedoIntensity > 0 ||
  56683. this.overloadedAmbientIntensity > 0 ||
  56684. this.overloadedReflectionIntensity > 0) {
  56685. this._defines.OVERLOADEDVALUES = true;
  56686. }
  56687. // Point size
  56688. if (this.pointsCloud || scene.forcePointsCloud) {
  56689. this._defines.POINTSIZE = true;
  56690. }
  56691. // Fog
  56692. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56693. this._defines.FOG = true;
  56694. }
  56695. if (BABYLON.StandardMaterial.FresnelEnabled) {
  56696. // Fresnel
  56697. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  56698. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56699. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  56700. this._defines.OPACITYFRESNEL = true;
  56701. }
  56702. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56703. this._defines.EMISSIVEFRESNEL = true;
  56704. }
  56705. needNormals = true;
  56706. this._defines.FRESNEL = true;
  56707. }
  56708. }
  56709. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  56710. this._defines.SPECULAROVERALPHA = true;
  56711. }
  56712. if (this.usePhysicalLightFalloff) {
  56713. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  56714. }
  56715. if (this.useRadianceOverAlpha) {
  56716. this._defines.RADIANCEOVERALPHA = true;
  56717. }
  56718. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  56719. this._defines.METALLICWORKFLOW = true;
  56720. }
  56721. // Attribs
  56722. if (mesh) {
  56723. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56724. this._defines.NORMAL = true;
  56725. }
  56726. if (needUVs) {
  56727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56728. this._defines.UV1 = true;
  56729. }
  56730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56731. this._defines.UV2 = true;
  56732. }
  56733. }
  56734. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56735. this._defines.VERTEXCOLOR = true;
  56736. if (mesh.hasVertexAlpha) {
  56737. this._defines.VERTEXALPHA = true;
  56738. }
  56739. }
  56740. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56741. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  56742. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  56743. }
  56744. // Instances
  56745. if (useInstances) {
  56746. this._defines.INSTANCES = true;
  56747. }
  56748. }
  56749. // Get correct effect
  56750. if (!this._defines.isEqual(this._cachedDefines)) {
  56751. this._defines.cloneTo(this._cachedDefines);
  56752. scene.resetCachedMaterial();
  56753. // Fallbacks
  56754. var fallbacks = new BABYLON.EffectFallbacks();
  56755. if (this._defines.REFLECTION) {
  56756. fallbacks.addFallback(0, "REFLECTION");
  56757. }
  56758. if (this._defines.REFRACTION) {
  56759. fallbacks.addFallback(0, "REFRACTION");
  56760. }
  56761. if (this._defines.REFLECTIVITY) {
  56762. fallbacks.addFallback(0, "REFLECTIVITY");
  56763. }
  56764. if (this._defines.BUMP) {
  56765. fallbacks.addFallback(0, "BUMP");
  56766. }
  56767. if (this._defines.PARALLAX) {
  56768. fallbacks.addFallback(1, "PARALLAX");
  56769. }
  56770. if (this._defines.PARALLAXOCCLUSION) {
  56771. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  56772. }
  56773. if (this._defines.SPECULAROVERALPHA) {
  56774. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  56775. }
  56776. if (this._defines.FOG) {
  56777. fallbacks.addFallback(1, "FOG");
  56778. }
  56779. if (this._defines.POINTSIZE) {
  56780. fallbacks.addFallback(0, "POINTSIZE");
  56781. }
  56782. if (this._defines.LOGARITHMICDEPTH) {
  56783. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  56784. }
  56785. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  56786. if (this._defines.SPECULARTERM) {
  56787. fallbacks.addFallback(0, "SPECULARTERM");
  56788. }
  56789. if (this._defines.OPACITYFRESNEL) {
  56790. fallbacks.addFallback(1, "OPACITYFRESNEL");
  56791. }
  56792. if (this._defines.EMISSIVEFRESNEL) {
  56793. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  56794. }
  56795. if (this._defines.FRESNEL) {
  56796. fallbacks.addFallback(3, "FRESNEL");
  56797. }
  56798. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  56799. fallbacks.addCPUSkinningFallback(0, mesh);
  56800. }
  56801. //Attributes
  56802. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56803. if (this._defines.NORMAL) {
  56804. attribs.push(BABYLON.VertexBuffer.NormalKind);
  56805. }
  56806. if (this._defines.UV1) {
  56807. attribs.push(BABYLON.VertexBuffer.UVKind);
  56808. }
  56809. if (this._defines.UV2) {
  56810. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56811. }
  56812. if (this._defines.VERTEXCOLOR) {
  56813. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56814. }
  56815. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  56816. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  56817. // Legacy browser patch
  56818. var join = this._defines.toString();
  56819. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  56820. "vFogInfos", "vFogColor", "pointSize",
  56821. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  56822. "mBones",
  56823. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  56824. "depthValues",
  56825. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  56826. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  56827. "logarithmicDepthConstant",
  56828. "vSphericalX", "vSphericalY", "vSphericalZ",
  56829. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  56830. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  56831. "vMicrosurfaceTextureLods",
  56832. "vCameraInfos"
  56833. ];
  56834. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  56835. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  56836. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  56837. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  56838. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  56839. }
  56840. if (!this._effect.isReady()) {
  56841. return false;
  56842. }
  56843. this._renderId = scene.getRenderId();
  56844. this._wasPreviouslyReady = true;
  56845. if (mesh) {
  56846. if (!mesh._materialDefines) {
  56847. mesh._materialDefines = new PBRMaterialDefines();
  56848. }
  56849. this._defines.cloneTo(mesh._materialDefines);
  56850. }
  56851. return true;
  56852. };
  56853. PBRMaterial.prototype.unbind = function () {
  56854. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  56855. this._effect.setTexture("reflection2DSampler", null);
  56856. }
  56857. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  56858. this._effect.setTexture("refraction2DSampler", null);
  56859. }
  56860. _super.prototype.unbind.call(this);
  56861. };
  56862. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56863. this._effect.setMatrix("world", world);
  56864. };
  56865. PBRMaterial.prototype.bind = function (world, mesh) {
  56866. this._myScene = this.getScene();
  56867. // Matrices
  56868. this.bindOnlyWorldMatrix(world);
  56869. // Bones
  56870. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  56871. if (this._myScene.getCachedMaterial() !== this) {
  56872. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  56873. if (BABYLON.StandardMaterial.FresnelEnabled) {
  56874. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  56875. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  56876. }
  56877. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56878. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  56879. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  56880. }
  56881. }
  56882. // Textures
  56883. if (this._myScene.texturesEnabled) {
  56884. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56885. this._effect.setTexture("albedoSampler", this.albedoTexture);
  56886. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  56887. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  56888. }
  56889. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  56890. this._effect.setTexture("ambientSampler", this.ambientTexture);
  56891. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  56892. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  56893. }
  56894. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  56895. this._effect.setTexture("opacitySampler", this.opacityTexture);
  56896. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  56897. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  56898. }
  56899. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  56900. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  56901. if (this.reflectionTexture.isCube) {
  56902. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  56903. }
  56904. else {
  56905. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  56906. }
  56907. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  56908. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  56909. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  56910. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  56911. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  56912. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  56913. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  56914. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  56915. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  56916. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  56917. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  56918. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  56919. }
  56920. }
  56921. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  56922. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  56923. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  56924. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  56925. }
  56926. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  56927. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  56928. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  56929. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  56930. }
  56931. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  56932. if (this.metallicTexture) {
  56933. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  56934. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  56935. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  56936. }
  56937. else if (this.reflectivityTexture) {
  56938. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  56939. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  56940. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  56941. }
  56942. }
  56943. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  56944. this._effect.setTexture("bumpSampler", this.bumpTexture);
  56945. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  56946. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  56947. }
  56948. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  56949. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  56950. var depth = 1.0;
  56951. if (this.refractionTexture.isCube) {
  56952. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  56953. }
  56954. else {
  56955. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  56956. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  56957. if (this.refractionTexture.depth) {
  56958. depth = this.refractionTexture.depth;
  56959. }
  56960. }
  56961. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  56962. }
  56963. if ((this.reflectionTexture || this.refractionTexture)) {
  56964. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  56965. }
  56966. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  56967. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  56968. }
  56969. }
  56970. // Clip plane
  56971. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  56972. // Point size
  56973. if (this.pointsCloud) {
  56974. this._effect.setFloat("pointSize", this.pointSize);
  56975. }
  56976. // Colors
  56977. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  56978. if (this._defines.METALLICWORKFLOW) {
  56979. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  56980. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  56981. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  56982. }
  56983. else {
  56984. // GAMMA CORRECTION.
  56985. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  56986. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  56987. }
  56988. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  56989. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  56990. // GAMMA CORRECTION.
  56991. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  56992. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  56993. // GAMMA CORRECTION.
  56994. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  56995. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  56996. }
  56997. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  56998. // GAMMA CORRECTION.
  56999. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  57000. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  57001. // Lights
  57002. if (this._myScene.lightsEnabled && !this.disableLighting) {
  57003. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  57004. }
  57005. // View
  57006. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  57007. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  57008. }
  57009. // Fog
  57010. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  57011. this._lightingInfos.x = this.directIntensity;
  57012. this._lightingInfos.y = this.emissiveIntensity;
  57013. this._lightingInfos.z = this.environmentIntensity;
  57014. this._lightingInfos.w = this.specularIntensity;
  57015. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  57016. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  57017. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  57018. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  57019. this._cameraInfos.x = this.cameraExposure;
  57020. this._cameraInfos.y = this.cameraContrast;
  57021. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  57022. if (this.cameraColorCurves) {
  57023. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  57024. }
  57025. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  57026. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  57027. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  57028. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  57029. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  57030. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  57031. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  57032. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  57033. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  57034. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  57035. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  57036. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  57037. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  57038. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  57039. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  57040. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  57041. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  57042. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  57043. // Log. depth
  57044. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  57045. }
  57046. _super.prototype.bind.call(this, world, mesh);
  57047. this._myScene = null;
  57048. };
  57049. PBRMaterial.prototype.getAnimatables = function () {
  57050. var results = [];
  57051. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  57052. results.push(this.albedoTexture);
  57053. }
  57054. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  57055. results.push(this.ambientTexture);
  57056. }
  57057. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  57058. results.push(this.opacityTexture);
  57059. }
  57060. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  57061. results.push(this.reflectionTexture);
  57062. }
  57063. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  57064. results.push(this.emissiveTexture);
  57065. }
  57066. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  57067. results.push(this.metallicTexture);
  57068. }
  57069. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  57070. results.push(this.reflectivityTexture);
  57071. }
  57072. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  57073. results.push(this.bumpTexture);
  57074. }
  57075. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  57076. results.push(this.lightmapTexture);
  57077. }
  57078. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  57079. results.push(this.refractionTexture);
  57080. }
  57081. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  57082. results.push(this.cameraColorGradingTexture);
  57083. }
  57084. return results;
  57085. };
  57086. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57087. if (forceDisposeTextures) {
  57088. if (this.albedoTexture) {
  57089. this.albedoTexture.dispose();
  57090. }
  57091. if (this.ambientTexture) {
  57092. this.ambientTexture.dispose();
  57093. }
  57094. if (this.opacityTexture) {
  57095. this.opacityTexture.dispose();
  57096. }
  57097. if (this.reflectionTexture) {
  57098. this.reflectionTexture.dispose();
  57099. }
  57100. if (this.emissiveTexture) {
  57101. this.emissiveTexture.dispose();
  57102. }
  57103. if (this.metallicTexture) {
  57104. this.metallicTexture.dispose();
  57105. }
  57106. if (this.reflectivityTexture) {
  57107. this.reflectivityTexture.dispose();
  57108. }
  57109. if (this.bumpTexture) {
  57110. this.bumpTexture.dispose();
  57111. }
  57112. if (this.lightmapTexture) {
  57113. this.lightmapTexture.dispose();
  57114. }
  57115. if (this.refractionTexture) {
  57116. this.refractionTexture.dispose();
  57117. }
  57118. if (this.cameraColorGradingTexture) {
  57119. this.cameraColorGradingTexture.dispose();
  57120. }
  57121. }
  57122. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57123. };
  57124. PBRMaterial.prototype.clone = function (name) {
  57125. var _this = this;
  57126. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  57127. };
  57128. PBRMaterial.prototype.serialize = function () {
  57129. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57130. serializationObject.customType = "BABYLON.PBRMaterial";
  57131. return serializationObject;
  57132. };
  57133. // Statics
  57134. PBRMaterial.Parse = function (source, scene, rootUrl) {
  57135. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  57136. };
  57137. return PBRMaterial;
  57138. }(BABYLON.Material));
  57139. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  57140. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  57141. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  57142. PBRMaterial._scaledReflection = new BABYLON.Color3();
  57143. __decorate([
  57144. BABYLON.serialize()
  57145. ], PBRMaterial.prototype, "directIntensity", void 0);
  57146. __decorate([
  57147. BABYLON.serialize()
  57148. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  57149. __decorate([
  57150. BABYLON.serialize()
  57151. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  57152. __decorate([
  57153. BABYLON.serialize()
  57154. ], PBRMaterial.prototype, "specularIntensity", void 0);
  57155. __decorate([
  57156. BABYLON.serialize()
  57157. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  57158. __decorate([
  57159. BABYLON.serialize()
  57160. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  57161. __decorate([
  57162. BABYLON.serialize()
  57163. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  57164. __decorate([
  57165. BABYLON.serialize()
  57166. ], PBRMaterial.prototype, "cameraExposure", void 0);
  57167. __decorate([
  57168. BABYLON.serialize()
  57169. ], PBRMaterial.prototype, "cameraContrast", void 0);
  57170. __decorate([
  57171. BABYLON.serializeAsTexture()
  57172. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  57173. __decorate([
  57174. BABYLON.serializeAsColorCurves()
  57175. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  57176. __decorate([
  57177. BABYLON.serializeAsColor3()
  57178. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  57179. __decorate([
  57180. BABYLON.serialize()
  57181. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  57182. __decorate([
  57183. BABYLON.serializeAsColor3()
  57184. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  57185. __decorate([
  57186. BABYLON.serialize()
  57187. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  57188. __decorate([
  57189. BABYLON.serializeAsColor3()
  57190. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  57191. __decorate([
  57192. BABYLON.serialize()
  57193. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  57194. __decorate([
  57195. BABYLON.serializeAsColor3()
  57196. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  57197. __decorate([
  57198. BABYLON.serialize()
  57199. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  57200. __decorate([
  57201. BABYLON.serializeAsColor3()
  57202. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  57203. __decorate([
  57204. BABYLON.serialize()
  57205. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  57206. __decorate([
  57207. BABYLON.serialize()
  57208. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  57209. __decorate([
  57210. BABYLON.serialize()
  57211. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  57212. __decorate([
  57213. BABYLON.serializeAsTexture()
  57214. ], PBRMaterial.prototype, "albedoTexture", void 0);
  57215. __decorate([
  57216. BABYLON.serializeAsTexture()
  57217. ], PBRMaterial.prototype, "ambientTexture", void 0);
  57218. __decorate([
  57219. BABYLON.serialize()
  57220. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  57221. __decorate([
  57222. BABYLON.serializeAsTexture()
  57223. ], PBRMaterial.prototype, "opacityTexture", void 0);
  57224. __decorate([
  57225. BABYLON.serializeAsTexture()
  57226. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  57227. __decorate([
  57228. BABYLON.serializeAsTexture()
  57229. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  57230. __decorate([
  57231. BABYLON.serializeAsTexture()
  57232. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  57233. __decorate([
  57234. BABYLON.serializeAsTexture()
  57235. ], PBRMaterial.prototype, "metallicTexture", void 0);
  57236. __decorate([
  57237. BABYLON.serialize()
  57238. ], PBRMaterial.prototype, "metallic", void 0);
  57239. __decorate([
  57240. BABYLON.serialize()
  57241. ], PBRMaterial.prototype, "roughness", void 0);
  57242. __decorate([
  57243. BABYLON.serializeAsTexture()
  57244. ], PBRMaterial.prototype, "bumpTexture", void 0);
  57245. __decorate([
  57246. BABYLON.serializeAsTexture()
  57247. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  57248. __decorate([
  57249. BABYLON.serializeAsTexture()
  57250. ], PBRMaterial.prototype, "refractionTexture", void 0);
  57251. __decorate([
  57252. BABYLON.serializeAsColor3("ambient")
  57253. ], PBRMaterial.prototype, "ambientColor", void 0);
  57254. __decorate([
  57255. BABYLON.serializeAsColor3("albedo")
  57256. ], PBRMaterial.prototype, "albedoColor", void 0);
  57257. __decorate([
  57258. BABYLON.serializeAsColor3("reflectivity")
  57259. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  57260. __decorate([
  57261. BABYLON.serializeAsColor3("reflection")
  57262. ], PBRMaterial.prototype, "reflectionColor", void 0);
  57263. __decorate([
  57264. BABYLON.serializeAsColor3("emissive")
  57265. ], PBRMaterial.prototype, "emissiveColor", void 0);
  57266. __decorate([
  57267. BABYLON.serialize()
  57268. ], PBRMaterial.prototype, "microSurface", void 0);
  57269. __decorate([
  57270. BABYLON.serialize()
  57271. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  57272. __decorate([
  57273. BABYLON.serialize()
  57274. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  57275. __decorate([
  57276. BABYLON.serializeAsFresnelParameters()
  57277. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  57278. __decorate([
  57279. BABYLON.serializeAsFresnelParameters()
  57280. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  57281. __decorate([
  57282. BABYLON.serialize()
  57283. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  57284. __decorate([
  57285. BABYLON.serialize()
  57286. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  57287. __decorate([
  57288. BABYLON.serialize()
  57289. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  57290. __decorate([
  57291. BABYLON.serialize()
  57292. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  57293. __decorate([
  57294. BABYLON.serialize()
  57295. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  57296. __decorate([
  57297. BABYLON.serialize()
  57298. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  57299. __decorate([
  57300. BABYLON.serialize()
  57301. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  57302. __decorate([
  57303. BABYLON.serialize()
  57304. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  57305. __decorate([
  57306. BABYLON.serialize()
  57307. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  57308. __decorate([
  57309. BABYLON.serialize()
  57310. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  57311. __decorate([
  57312. BABYLON.serialize()
  57313. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  57314. __decorate([
  57315. BABYLON.serialize()
  57316. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  57317. __decorate([
  57318. BABYLON.serialize()
  57319. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  57320. __decorate([
  57321. BABYLON.serialize()
  57322. ], PBRMaterial.prototype, "useParallax", void 0);
  57323. __decorate([
  57324. BABYLON.serialize()
  57325. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  57326. __decorate([
  57327. BABYLON.serialize()
  57328. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  57329. __decorate([
  57330. BABYLON.serialize()
  57331. ], PBRMaterial.prototype, "disableLighting", void 0);
  57332. __decorate([
  57333. BABYLON.serialize()
  57334. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  57335. __decorate([
  57336. BABYLON.serialize()
  57337. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  57338. __decorate([
  57339. BABYLON.serialize()
  57340. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  57341. __decorate([
  57342. BABYLON.serialize()
  57343. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  57344. BABYLON.PBRMaterial = PBRMaterial;
  57345. })(BABYLON || (BABYLON = {}));
  57346. //# sourceMappingURL=babylon.pbrMaterial.js.map
  57347. var BABYLON;
  57348. (function (BABYLON) {
  57349. var DebugLayer = (function () {
  57350. function DebugLayer(scene) {
  57351. this._scene = scene;
  57352. }
  57353. /** Creates the inspector window. */
  57354. DebugLayer.prototype._createInspector = function (popup) {
  57355. if (!this._inspector) {
  57356. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  57357. } // else nothing to do,; instance is already existing
  57358. };
  57359. DebugLayer.prototype.isVisible = function () {
  57360. return false;
  57361. };
  57362. DebugLayer.prototype.hide = function () {
  57363. if (this._inspector) {
  57364. this._inspector.dispose();
  57365. this._inspector = null;
  57366. }
  57367. };
  57368. DebugLayer.prototype.show = function (popup) {
  57369. if (typeof INSPECTOR == 'undefined') {
  57370. // Load inspector and add it to the DOM
  57371. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  57372. }
  57373. else {
  57374. // Otherwise creates the inspector
  57375. this._createInspector(popup);
  57376. }
  57377. };
  57378. return DebugLayer;
  57379. }());
  57380. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  57381. BABYLON.DebugLayer = DebugLayer;
  57382. })(BABYLON || (BABYLON = {}));
  57383. //# sourceMappingURL=babylon.debugLayer.js.map
  57384. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  57385. var BABYLON;
  57386. (function (BABYLON) {
  57387. var StandardRenderingPipeline = (function (_super) {
  57388. __extends(StandardRenderingPipeline, _super);
  57389. /**
  57390. * @constructor
  57391. * @param {string} name - The rendering pipeline name
  57392. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57393. * @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)
  57394. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57395. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57396. */
  57397. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57398. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57399. var _this = _super.call(this, scene.getEngine(), name) || this;
  57400. _this.downSampleX4PostProcess = null;
  57401. _this.brightPassPostProcess = null;
  57402. _this.gaussianBlurHPostProcesses = [];
  57403. _this.gaussianBlurVPostProcesses = [];
  57404. _this.textureAdderPostProcess = null;
  57405. _this.textureAdderFinalPostProcess = null;
  57406. _this.lensFlarePostProcess = null;
  57407. _this.lensFlareComposePostProcess = null;
  57408. _this.depthOfFieldPostProcess = null;
  57409. // Values
  57410. _this.brightThreshold = 1.0;
  57411. _this.blurWidth = 2.0;
  57412. _this.gaussianCoefficient = 0.25;
  57413. _this.gaussianMean = 1.0;
  57414. _this.gaussianStandardDeviation = 1.0;
  57415. _this.exposure = 1.0;
  57416. _this.lensTexture = null;
  57417. _this.lensColorTexture = null;
  57418. _this.lensFlareStrength = 20.0;
  57419. _this.lensFlareGhostDispersal = 1.4;
  57420. _this.lensFlareHaloWidth = 0.7;
  57421. _this.lensFlareDistortionStrength = 16.0;
  57422. _this.lensStarTexture = null;
  57423. _this.lensFlareDirtTexture = null;
  57424. _this.depthOfFieldDistance = 10.0;
  57425. // IAnimatable
  57426. _this.animations = [];
  57427. _this._depthRenderer = null;
  57428. // Getters and setters
  57429. _this._depthOfFieldEnabled = true;
  57430. _this._lensFlareEnabled = true;
  57431. // Initialize
  57432. _this._scene = scene;
  57433. // Create pass post-processe
  57434. if (!originalPostProcess) {
  57435. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  57436. }
  57437. else {
  57438. _this.originalPostProcess = originalPostProcess;
  57439. }
  57440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57441. // Create down sample X4 post-process
  57442. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  57443. // Create bright pass post-process
  57444. _this._createBrightPassPostProcess(scene, ratio / 2);
  57445. // Create gaussian blur post-processes (down sampling blurs)
  57446. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  57447. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  57448. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  57449. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  57450. // Create texture adder post-process
  57451. _this._createTextureAdderPostProcess(scene, ratio);
  57452. // Create depth-of-field source post-process
  57453. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57454. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57455. // Create lens flare post-process
  57456. _this._createLensFlarePostProcess(scene, ratio);
  57457. // Create gaussian blur used by depth-of-field
  57458. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  57459. // Create depth-of-field post-process
  57460. _this._createDepthOfFieldPostProcess(scene, ratio);
  57461. // Finish
  57462. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57463. if (cameras !== null) {
  57464. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57465. }
  57466. // Deactivate
  57467. _this.LensFlareEnabled = false;
  57468. _this.DepthOfFieldEnabled = false;
  57469. return _this;
  57470. }
  57471. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57472. get: function () {
  57473. return this._depthOfFieldEnabled;
  57474. },
  57475. set: function (enabled) {
  57476. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  57477. if (enabled && !this._depthOfFieldEnabled) {
  57478. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57479. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57480. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57481. this._depthRenderer = this._scene.enableDepthRenderer();
  57482. }
  57483. else if (!enabled && this._depthOfFieldEnabled) {
  57484. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57485. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57486. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57487. }
  57488. this._depthOfFieldEnabled = enabled;
  57489. },
  57490. enumerable: true,
  57491. configurable: true
  57492. });
  57493. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57494. get: function () {
  57495. return this._lensFlareEnabled;
  57496. },
  57497. set: function (enabled) {
  57498. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  57499. if (enabled && !this._lensFlareEnabled) {
  57500. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57501. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57502. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57503. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57504. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57505. }
  57506. else if (!enabled && this._lensFlareEnabled) {
  57507. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57508. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57509. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57510. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57511. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57512. }
  57513. this._lensFlareEnabled = enabled;
  57514. },
  57515. enumerable: true,
  57516. configurable: true
  57517. });
  57518. // Down Sample X4 Post-Processs
  57519. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57520. var _this = this;
  57521. var downSampleX4Offsets = new Array(32);
  57522. 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);
  57523. this.downSampleX4PostProcess.onApply = function (effect) {
  57524. var id = 0;
  57525. for (var i = -2; i < 2; i++) {
  57526. for (var j = -2; j < 2; j++) {
  57527. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  57528. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  57529. id += 2;
  57530. }
  57531. }
  57532. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57533. };
  57534. // Add to pipeline
  57535. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  57536. };
  57537. // Brightpass Post-Process
  57538. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57539. var _this = this;
  57540. var brightOffsets = new Array(8);
  57541. 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);
  57542. this.brightPassPostProcess.onApply = function (effect) {
  57543. var sU = (1.0 / _this.brightPassPostProcess.width);
  57544. var sV = (1.0 / _this.brightPassPostProcess.height);
  57545. brightOffsets[0] = -0.5 * sU;
  57546. brightOffsets[1] = 0.5 * sV;
  57547. brightOffsets[2] = 0.5 * sU;
  57548. brightOffsets[3] = 0.5 * sV;
  57549. brightOffsets[4] = -0.5 * sU;
  57550. brightOffsets[5] = -0.5 * sV;
  57551. brightOffsets[6] = 0.5 * sU;
  57552. brightOffsets[7] = -0.5 * sV;
  57553. effect.setArray2("dsOffsets", brightOffsets);
  57554. effect.setFloat("brightThreshold", _this.brightThreshold);
  57555. };
  57556. // Add to pipeline
  57557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  57558. };
  57559. // Create gaussian blur H&V post-processes
  57560. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  57561. var _this = this;
  57562. var blurOffsets = new Array(9);
  57563. var blurWeights = new Array(9);
  57564. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  57565. var callback = function (height) {
  57566. return function (effect) {
  57567. // Weights
  57568. var x = 0.0;
  57569. for (var i = 0; i < 9; i++) {
  57570. x = (i - 4.0) / 4.0;
  57571. blurWeights[i] =
  57572. _this.gaussianCoefficient
  57573. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  57574. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  57575. }
  57576. var lastOutputDimensions = {
  57577. width: scene.getEngine().getRenderWidth(),
  57578. height: scene.getEngine().getRenderHeight()
  57579. };
  57580. for (var i = 0; i < 9; i++) {
  57581. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57582. blurOffsets[i] = value;
  57583. }
  57584. effect.setArray("blurOffsets", blurOffsets);
  57585. effect.setArray("blurWeights", blurWeights);
  57586. effect.setFloat("blurWidth", _this.blurWidth);
  57587. };
  57588. };
  57589. // Create horizontal gaussian blur post-processes
  57590. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57591. gaussianBlurHPostProcess.onApply = callback(false);
  57592. // Create vertical gaussian blur post-process
  57593. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57594. gaussianBlurVPostProcess.onApply = callback(true);
  57595. // Add to pipeline
  57596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  57597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  57598. // Finish
  57599. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  57600. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  57601. };
  57602. // Create texture adder post-process
  57603. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57604. var _this = this;
  57605. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  57606. 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);
  57607. this.textureAdderPostProcess.onApply = function (effect) {
  57608. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  57609. effect.setTexture("lensSampler", _this.lensTexture);
  57610. effect.setFloat("exposure", _this.exposure);
  57611. };
  57612. // Add to pipeline
  57613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  57614. };
  57615. // Create lens flare post-process
  57616. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  57617. var _this = this;
  57618. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  57620. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  57621. 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);
  57622. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  57623. var resolution = new BABYLON.Vector2(0, 0);
  57624. // Lens flare
  57625. this.lensFlarePostProcess.onApply = function (effect) {
  57626. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  57627. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  57628. effect.setFloat("strength", _this.lensFlareStrength);
  57629. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  57630. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  57631. // Shift
  57632. resolution.x = _this.lensFlarePostProcess.width;
  57633. resolution.y = _this.lensFlarePostProcess.height;
  57634. effect.setVector2("resolution", resolution);
  57635. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  57636. };
  57637. // Compose
  57638. 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);
  57639. 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);
  57640. this.lensFlareComposePostProcess.onApply = function (effect) {
  57641. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57642. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  57643. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  57644. // Lens start rotation matrix
  57645. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  57646. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  57647. 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));
  57648. camRot *= 4.0;
  57649. 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);
  57650. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  57651. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  57652. };
  57653. };
  57654. // Create depth-of-field post-process
  57655. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  57656. var _this = this;
  57657. 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);
  57658. this.depthOfFieldPostProcess.onApply = function (effect) {
  57659. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57660. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  57661. effect.setFloat("distance", _this.depthOfFieldDistance);
  57662. };
  57663. // Add to pipeline
  57664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  57665. };
  57666. // Dispose
  57667. StandardRenderingPipeline.prototype.dispose = function () {
  57668. for (var i = 0; i < this._scene.cameras.length; i++) {
  57669. var camera = this._scene.cameras[i];
  57670. this.originalPostProcess.dispose(camera);
  57671. this.downSampleX4PostProcess.dispose(camera);
  57672. this.brightPassPostProcess.dispose(camera);
  57673. this.textureAdderPostProcess.dispose(camera);
  57674. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  57675. this.gaussianBlurHPostProcesses[j].dispose(camera);
  57676. }
  57677. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  57678. this.gaussianBlurVPostProcesses[j].dispose(camera);
  57679. }
  57680. this.textureAdderFinalPostProcess.dispose(camera);
  57681. this.lensFlarePostProcess.dispose(camera);
  57682. this.lensFlareComposePostProcess.dispose(camera);
  57683. this.depthOfFieldPostProcess.dispose(camera);
  57684. }
  57685. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57686. _super.prototype.dispose.call(this);
  57687. };
  57688. return StandardRenderingPipeline;
  57689. }(BABYLON.PostProcessRenderPipeline));
  57690. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  57691. })(BABYLON || (BABYLON = {}));
  57692. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  57693. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<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":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef 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<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  57694. 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)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","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 SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\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"};
  57695. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var p=!1,P=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(p=!0,P=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P);y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(p){var x=P*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";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.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.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.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){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(i,r,n,o){var e=t.Tmp.Quaternion[1];a.QuaternionRotationFromAxisToRef(i,r,n,e),e.toEulerAnglesToRef(o)},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.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}();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.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function i(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){var t=new i((-this.x),(-this.y),(-this.z),this.w);return t},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},i.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},i.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.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.QuaternionRotationFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.QuaternionRotationFromAxisToRef(t,r,n,e),e},i.QuaternionRotationFromAxisToRef=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),A=e*w-s*d+a*R,M=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*A+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,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=A*F,t.m[12]=M*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,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.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],A=t.m[6],M=t.m[7],F=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];\nreturn i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*A+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*A+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*A+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*A+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.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.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},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=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var A=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=A;var M=function(){function t(){}return t}();M.Color3=[r.Black(),r.Black(),r.Black()],M.Vector2=[o.Zero(),o.Zero(),o.Zero()],M.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],M.Vector4=[s.Zero(),s.Zero(),s.Zero()],M.Quaternion=[new a(0,0,0,0),new a(0,0,0,0)],M.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=M}(BABYLON||(BABYLON={}));";
  57696. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  57697. module.exports = BABYLON;
  57698. };